diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dfd2520..09e0ac6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,7 +3,7 @@ name: CI on: pull_request: push: - branches: [master, proposed_type_script_api_version] + branches: [master] permissions: contents: read diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ace2ee..eb960db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,115 @@ # Changelog +## 1.0.0-alpha.7 — what a browser app consumer asked for + +One breaking change, to attachments; everything else is additive. Each +entry says what a consumer changes, if anything. + +### Breaking + +- **An attachment is answered as a row of the Attachment type**, under + meta.v1's attribute names like every other row, plus `id`. It was the + one place the SDK had a vocabulary of its own. This holds for + `client.attachments.list`, `page`, `info`, `get` and `add`, and for + `AttachmentUploadError.attachment`. Migration, field by field: + - `oid` → `_oid` + - `id` → `id` (unchanged: the number attachment.img addresses) + - `name` → `Name`; `filename` → `Filename`; `description` → + `Description`; `createDate` → `CreateDate` + - `contentType` → `ContentType` (the recorded one) + - `createdBy` → `["CreatedBy.Name"]` (the select path, as selected) + - on `get`: `contentType` (the served type, falling back to the + recorded one) → `servedContentType ?? ContentType`; + `recordedContentType` → `ContentType` + `add`'s options (`filename`, `contentType`, `name`, `description`, + `inlineLimit`) are unchanged. The row type is closed (it does not + extend `Asset`): it has these keys and the ones a `select` named, so a + read the migration missed (`row.filename`) is a compile error rather + than `undefined`. + +### Added + +- **`client.attachments.list` / `page` take a `select`**: more to read + with each attachment, as a query's `select` on Attachment + (`Category.Name`, `Asset.Number`, a sub-select). Each row then carries + those keys too, as selected, translated like any row and typed by what + was selected. Migration: a second query for an attachment's other + attributes becomes `list(asset, { select })`. +- **A one-request read for a small attachment**: + `client.attachments.get(id, { inline: true })` reads the metadata and + the bytes in one query.v1 request (the Attachment's `Content` comes + back as Base64 beside its row) where the default is two (the row, then + attachment.img). For small files: the response is a third larger than + the file and is held in memory whole. `servedContentType` is then + null. Migration: none; add `{ inline: true }` where a thumbnail + or a small text file is read. +- **`normalizeQuery(query)`**: a query written with rest-1's spellings + becomes the `QueryBody` every read takes — `sel` → `select`, a textual + `where` → `filter`, comma-joined `select` / `sort` / `findin` → lists, + a `"size,start"` page → `{ size, start }`, sub-selects the same way. A + `QueryBody` comes back equal. Saying one thing twice (`sel` and + `select`) or asking for `deleted` is a `UsageError`. `QueryBody` itself + gains no alias. Migration: a consumer's own `sel`-to-`select` shim + becomes `client.query(normalizeQuery(q))`. +- **`@versionone/agility-sdk/testing`** exports `FakeAgilityClient`: a + real `AgilityApiClient` over a transport that sends nothing. A test + scripts answers in the model's shape (`onQuery("Story", rows)`, + `onSend(outcome)`, `onRequest(path, answer)` for any other endpoint) + and asserts on what was asked (`asked`, `sent`, `requests`). A scripted + list is paged by the fake, a write answers OIDs without a script, and a + read nothing was scripted for throws a `UsageError` instead of reading + as empty. `resolve.numbers` finds a number among the scripted rows, + a query from a create's alias reads the created asset back, `localize` + echoes a tag `onLocalize` did not script, and `fake.transport` can + serve a client the code under test builds itself. It evaluates no + filter and applies no write. Migration: a + hand-written fake client or fake Transport in a consumer's tests can be + replaced by it; nothing requires that. +- **`apiErrorFromResponse(status, data)`**: the `ApiError` the fetch + transport throws for a refused response, exported for a custom + `Transport` to throw, so message, `kind` and `details` are the same + whichever transport sent the request. Migration: a custom transport's + `new ApiError(text, status)` becomes `apiErrorFromResponse(status, + body)`. +- **`@versionone/agility-sdk/wire`**: the wire modules (`assetApi`, + `queryV1`, `rest1`, `meta`, `loc2`, `attachment`, `fields`, `select`) + under their own import path. The root still exports them in this + alpha and stops in the next. Migration: `import { assetApi } from + "@versionone/agility-sdk"` → `from "@versionone/agility-sdk/wire"`. + +### Fixed + +- **`Outcome.requestId` after `assets.sendGuarded` and `batch.run`** is + the server's id when the batch went out in one request (the usual + case); it was always null. It stays null when the batch took several + sends. (a CLI consumer.) Migration: none. + +### Documented + +- `Page.more` is the pager's signal: with a total it is exact; when + `total` is null it is whether the page came back full, so a pager + offers "next" on `more`, never on `total`. +- `kind: "usage"` (on `ApiError.kind`): the SDK refused the call before + sending anything — no request reached the server and `status` is 0. +- `ClientConfig.baseUrl` with a custom `Transport`: the transport alone + decides where requests go; `baseUrl` is then used only for the links + the client builds (`client.urls.*`, `embeddedImages.normalize`), so + give it the instance's public URL. +- **For authors of a custom `Transport`** (this should have been under + "Breaking" in alpha.5): a request with `acceptNotModified` must + resolve to `undefined` on a 304, after calling `onResponse` with the + 304's status and headers, instead of rejecting. `client.meta.etag`, + `meta.read`, `meta.readType` and `schema.revalidate` send such + requests. And `retries` / `timeoutMs` configure the built-in fetch + transport only: a client given its own Transport resends nothing unless + that transport does. +- `client.meta` answers the model's `Metamodel` / `AssetType` + (references as tokens), not meta.v1's own document; its doc said + "raw". +- `client.query`'s doc said a resend needed `retries` raised from 0 and + that `details` was the whole error document; both changed in alpha.5 + and the doc now says so. + ## 1.0.0-alpha.6 - The generated model is refreshed from meta.v1 26.3.2.13 (was diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 32267b0..b0379af 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -81,5 +81,6 @@ and consumers pin commits by SHA), and nothing new is added to it. npm run verify # typecheck, build, unit tests (including the public-tree check) ``` -Open the pull request against `proposed_type_script_api_version`. A -change to an invariant changes `specs/000-layers.md` in the same commit. +Open the pull request against `master`. A change to an invariant changes +`specs/000-layers.md` in the same commit, and a change a consumer can see +gets a `CHANGELOG.md` entry with its migration line. diff --git a/README.md b/README.md index 0b21154..eabe9cb 100644 --- a/README.md +++ b/README.md @@ -43,34 +43,54 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `AgilityApiClient` - the client. One query body everywhere; the client picks the endpoint: - `query` / `queries` - rows, translated (numbers as numbers, booleans as booleans, a single relation as one `Ref`), through query.v1: read-only, so a request is retried like a GET. A page is required; a refused query throws, never an empty result. Written with a literal `from`, `select` completes from the type's attributes and the rows are typed by what was selected - - `get(oid, select)` - one asset or null; `queryPage(q)` - rows with the total and whether more follow; `pages(q, { limit })` / `all(q, { limit })` - page by page up to a limit (default 1000); `me()` - the member the credentials belong to + - `get(oid, select)` - one asset or null; `queryPage(q)` - rows with the total and whether more follow (`more` is what a pager reads: when the server reports no total, `total` is null and `more` is whether the page came back full); `pages(q, { limit })` / `all(q, { limit })` - page by page up to a limit (default 1000); `me()` - the member the credentials belong to - `assets.send` - an api/asset batch, answered as an `Outcome` (`created`, `modified`, `operated`, `failures` with parsed violations, `queryResults`); `throwOnFailure` throws a `CommandFailureError` carrying the same Outcome. `assets.preview` - the projection. `assets.sendGuarded` - a batch as a compare-and-set on each asset's ChangeDate; changed assets come back `skipped` - `batch.run` / `batch.reversible` - preview, snapshot, (confirm,) send guarded, and a receipt with a reverse batch; undo reactivates a closed asset before deleting it and reopens what a close cascaded to - `resolve.numbers` / `resolve.ref` - asset numbers and OID tokens to assets, in one request - - `attachments.list` / `page` / `info` / `get` / `add` / `put` / `remove` - files attached to an asset; `add` sends a small file inline and a large one in two steps, and a failed upload throws `AttachmentUploadError` naming the empty attachment it left + - `attachments.list` / `page` / `info` / `get` / `add` / `put` / `remove` - files attached to an asset, each answered as a row of the Attachment type (`_oid`, `Name`, `Filename`, `ContentType`, …) plus `id`, the number its bytes are addressed by; `list` and `page` answer metadata, plus whatever keys a `select` adds; `get` reads metadata and bytes in two requests, or in one with `{ inline: true }` for a small file; `add` sends a small file inline and a large one in two steps, and a failed upload throws `AttachmentUploadError` naming the empty attachment it left - `embeddedImages.upload` / `normalize` - images in rich text; they cannot be deleted - `copy(oid)` - the Copy operation, answering the copy's OID (api/asset performs it but never says what it made); `data.operate(oid, op)` is the general form - `fields.describe(type, scope)` - what a form needs: required attributes (meta), the ones the product shows there (`api/visibleFields`, custom fields included), the scheme's important fields and whether they are enforced at close - `urls.asset(oidOrNumber)` / `attachment` / `embeddedImage` - where a browser opens each - `data.list` / `get` / `history` / `template` - rest-1 reads: deleted assets, history, and a new asset's template for a context (`New/?ctx=`); `meta.*` - meta.v1 raw, with conditional reads (`read` / `readType` with `ifNoneMatch`, `etag()`: meta.v1 sends one ETag for the whole schema); `schema` - the translated, cached view, `schema.revalidate()` drops it only when that tag moves; `localize` - loc-2 labels for tags (a violation's `tag` is one) -- Errors: everything thrown is an `ApiError` with a `kind` (`auth`, `forbidden`, `notFound`, `invalid`, `transient`, `aborted`, `commandFailure`, `protocol`, `usage`, `unknown`). A mistake caught before any request is a `UsageError` +- `normalizeQuery(q)` - a query written with rest-1's spellings (`sel`, a textual `where`, comma-joined lists, a `"size,start"` page) as the `QueryBody` every read takes +- Errors: everything thrown is an `ApiError` with a `kind` (`auth`, `forbidden`, `notFound`, `invalid`, `transient`, `aborted`, `commandFailure`, `protocol`, `usage`, `unknown`). A mistake caught before any request is a `UsageError`: `kind: "usage"` means nothing was sent (`status` is 0), so the fix is in the call, not on the server - `TypeCache` - one instance's loaded type definitions, shared by many clients (`new AgilityApiClient(config, { types })`) - `createFetchTransport` - configurable HTTP transport: `credentials` for same-origin cookie auth, `onUnauthorized` to re-authenticate on a 401 (resends idempotent requests once), and a per-request `signal`; `client.withSignal(signal)` ties a whole client to one -- The wire modules (`assetApi`, `queryV1`, `rest1`, `meta`, `loc2`, `attachment`) are exported for passthroughs and transport authors; they speak the endpoints' own shapes +- A custom `Transport` (`new AgilityApiClient(config, { transport })`) decides by itself where requests go; `config.baseUrl` is then used only for the links the client builds (`urls.*`, `embeddedImages.normalize`). `apiErrorFromResponse(status, data)` is the error the fetch transport throws for a refused response, for a custom transport to throw the same +- `@versionone/agility-sdk/wire` - the wire modules (`assetApi`, `queryV1`, `rest1`, `meta`, `loc2`, `attachment`, `fields`, `select`), for passthroughs and transport authors; they speak the endpoints' own shapes. (The root still exports them in this alpha and stops in the next.) + +## Testing code that uses the SDK + +`@versionone/agility-sdk/testing` exports `FakeAgilityClient`: a real client over a transport that sends nothing and answers what the test scripted, in the shape the client hands your code. + +```ts +import { FakeAgilityClient } from "@versionone/agility-sdk/testing"; + +const fake = new FakeAgilityClient() + .onQuery("Story", [{ _oid: "Story:1", Name: "Logon", Estimate: 2 }]); + +await closeStory(fake, "Story:1"); // your code, taking an AgilityApiClient + +expect(fake.asked[0]).toMatchObject({ from: "Story:1" }); // what it read +expect(fake.sent[0]).toEqual([{ from: "Story:1", execute: "QuickClose" }]); // what it wrote +``` + +- `onQuery(match, rows)` answers every read (`query`, `get`, `queryPage`, `pages`, …). A list is the whole result: the fake pages it and answers a read by OID with that row. A function gets the query and answers one page. A read nothing was scripted for throws; it never looks like an empty result. +- Writes need no script: a create answers a new OID, an update or operation by OID answers that OID. `onSend` scripts anything else, failures included. +- `resolve.numbers` finds a number among the scripted rows; `localize` answers `onLocalize` labels and echoes any other tag; `fake.transport` can be the transport of a client your code builds itself. +- `onRequest(path, answer)` answers any other endpoint in its own shape. An `Error` as an answer is thrown. +- The fake evaluates no filter or sort and applies no write. It proves what your code asks and what it does with the answer; what the server answers is for a test against an instance. API reference: https://docs.digital.ai/agility-api/ -## Extend with new APIs +## Adding to the SDK -1. Add a new folder under `src/apis/`. -2. Add request/response types under `src/types/`. -3. Implement methods using `Transport.request`. -4. Export from `src/index.ts`. -5. Add tests under `test/`. +`specs/000-layers.md` says how the code is arranged (types, wire modules, services, core) and what each layer may know; `CONTRIBUTING.md` says what may be committed to this public repository. A new endpoint is a new module under `src/wire/`, with a unit test that fakes the transport with a response copied from a live one and an integration test that proves it against an instance. -## Installing before a release +## Installing an unreleased commit -No registry package yet. Pin a commit: `npm install github:versionone/VersionOne.SDK.JavaScript#` builds `dist` on install (the `prepare` script). CI also uploads an `npm pack` tarball on every run. +`npm install github:versionone/VersionOne.SDK.JavaScript#` builds `dist` on install (the `prepare` script). CI also uploads an `npm pack` tarball on every run. ## Releasing diff --git a/package-lock.json b/package-lock.json index 81c8df7..8e5bcd3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.6", + "version": "1.0.0-alpha.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.6", + "version": "1.0.0-alpha.7", "license": "MIT", "devDependencies": { "@types/node": "^22.13.10", @@ -16,7 +16,7 @@ "vitest": "^5.1.0" }, "engines": { - "node": ">=18" + "node": ">=22" } }, "node_modules/@esbuild/aix-ppc64": { diff --git a/package.json b/package.json index e3b66e2..b38ced8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.6", + "version": "1.0.0-alpha.7", "description": "TypeScript SDK for the Digital.ai Agility (VersionOne) API: queries, batches, schema-translated rows, guarded writes, attachments", "keywords": [ "agility", @@ -26,6 +26,26 @@ "types": "./dist/index.d.cts", "default": "./dist/index.cjs" } + }, + "./wire": { + "import": { + "types": "./dist/wire.d.ts", + "default": "./dist/wire.js" + }, + "require": { + "types": "./dist/wire.d.cts", + "default": "./dist/wire.cjs" + } + }, + "./testing": { + "import": { + "types": "./dist/testing.d.ts", + "default": "./dist/testing.js" + }, + "require": { + "types": "./dist/testing.d.cts", + "default": "./dist/testing.cjs" + } } }, "files": [ diff --git a/specs/000-layers.md b/specs/000-layers.md index 576b0a8..30a4e90 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -13,6 +13,10 @@ src/services what to do imports: types, wire, core src/core transport, errors imports: nothing above it ``` +Beside the table, not in it: `src/client.ts` binds the layers into the +client, and `src/testing` (§5a) stands on the client. Nothing imports +`src/testing`. + - **`types`** is the vocabulary: the asset types generated from meta.v1 (`src/types/assets/`, one file per asset type, the `extends` chain from the metamodel's `Base` chain) and the hand-written roots in @@ -151,6 +155,24 @@ index lag, what a preview echoes — are what fakes cannot reproduce; the integration tier is where a live probe becomes permanent, with an expect-zero control beside every "it returned rows". +## 5a. Three import paths, and a fake for consumers + +The package has three entries: the root (the client, the model, the +services), `/wire` (the wire modules, for passthroughs and transport +authors) and `/testing`. They are built with shared chunks in both module +formats, so a class is one class whichever path imported it; the CommonJS +unit test proves it. + +`/testing` holds `FakeAgilityClient`: the real client over a transport +that sends nothing. It is scripted in the **model's** shape, the one shape +of §2, because that is the contract a consumer codes against; it runs with +a schema that knows no type, so scripted rows pass through as written. It +therefore proves nothing about translation or about the server, and says +so: it evaluates no filter, applies no write, and throws for a read +nothing was scripted for (§6: a failure never reads as an empty). The +corollary of §2a still binds this repository's own unit tests, which fake +the *transport* with what the server sends. + ## 6. Politeness is in the layer No read is unbounded: `assetApi.queries` and `queryV1.queries` refuse a diff --git a/src/client.ts b/src/client.ts index 3359e56..2fb8b93 100644 --- a/src/client.ts +++ b/src/client.ts @@ -9,6 +9,7 @@ import * as guard from "./services/guard"; import * as resolve from "./services/resolve"; import { Schema, type TypeCache } from "./services/schema"; import type { Asset, Oid } from "./types/asset"; +import type { Attachment } from "./types/assets/Attachment"; import type { Member } from "./types/assets/Member"; import type { Metamodel } from "./types/metamodel"; import type { From, RowOf, RowsOf, Selected, SelectPath, TypeOf } from "./types/query"; @@ -44,7 +45,19 @@ export interface ClientOptions { } /** One page of rows, with the total number of matches when the server reports it, and whether more pages follow. */ -export interface Page { rows: Row[]; total: number | null; more: boolean } +export interface Page { + rows: Row[]; + /** The number of matches across all pages; null when the server did not report one. */ + total: number | null; + /** + * Whether more pages follow: what a pager reads. With a total it is exact + * (`start + rows.length < total`). When `total` is null it is whether + * this page came back full, the only signal left, so a pager keeps + * offering "next" on `more` and never on `total`; the page after a full + * last page is then empty with `more` false. + */ + more: boolean; +} export interface PagesOptions { /** @@ -118,11 +131,11 @@ export class AgilityApiClient { /** * One query, its rows, translated. Sent to query.v1: it cannot write, so - * the request is marked idempotent and the transport may resend it after - * a network failure or a 5xx — when `retries` is set above its default - * of 0. A page is required; a query the server refuses throws an - * ApiError (kind "invalid", code QUERY_REJECTED; `message` holds the - * server's sentences, `details` its whole error document), never an + * the request is marked idempotent and the transport resends it once + * after a network failure or a 5xx (`retries`, default 1). A page is + * required; a query the server refuses throws an ApiError (kind + * "invalid", code QUERY_REJECTED; `message` holds the server's + * sentences, `details` each exception's type and message), never an * empty result. */ query>(q: Q & assetApi.QueryBody): Promise[]>; @@ -207,8 +220,13 @@ export class AgilityApiClient { // ---- the endpoints behind the reads ----------------------------------------------- /** - * meta.v1: the instance's schema, raw. (The translated, cached view is - * `schema`; `schema.revalidate()` drops it when the schema's tag moves.) + * meta.v1: the instance's schema, read on request and not cached (the + * cached view queries use is `schema`; `schema.revalidate()` drops it + * when the schema's tag moves). What comes back is the model's + * `Metamodel` / `AssetType` — references as tokens (`Base: "Story"`, + * `RelatedAsset: "Member"`), operations by name — not meta.v1's own + * document, which spells them `{ nameref, href }`; for that document, + * read `/meta.v1` through the transport. * `read` and `readType` are conditional: pass the tag a previous answer * carried and an unchanged schema answers null without a download — * meta.v1 sends one strong ETag for the whole schema. `etag()` reads that @@ -338,13 +356,16 @@ export class AgilityApiClient { /** * The files attached to assets: metadata on Attachment assets, bytes * through attachment.img. `add` sends a small file inline (one request) - * and a large one in two steps. + * and a large one in two steps; `get` reads a small one inline on request. */ readonly attachments = { - list: (asset: string, options?: { page?: { size: number; start: number } }) => attachments.list(this.transport, asset, options), - page: (asset: string, options?: { page?: { size: number; start: number } }) => attachments.page(this.transport, asset, options), + /** One page of an asset's attachments, newest first, metadata only; `select` adds keys to each row. */ + list: | assetApi.QueryBody)[] | undefined = undefined>(asset: string, options?: Omit, "schema">) => attachments.list(this.transport, asset, { ...options, schema: this.schema }), + /** The same page with the total and whether more follow. */ + page: | assetApi.QueryBody)[] | undefined = undefined>(asset: string, options?: Omit, "schema">) => attachments.page(this.transport, asset, { ...options, schema: this.schema }), info: (id: string | number) => attachments.info(this.transport, id), - get: (id: string | number) => attachments.get(this.transport, id), + /** Metadata and bytes: two requests, or one with `{ inline: true }` (for small files; the content rides in the row as Base64). */ + get: (id: string | number, options?: attachments.GetOptions) => attachments.get(this.transport, id, options), add: (asset: string, data: attachment.Bytes, options: attachments.AddOptions) => attachments.add(this.transport, asset, data, options), put: (id: string | number, data: attachment.Bytes, contentType?: string) => attachments.put(this.transport, id, data, contentType), remove: (id: string | number) => attachments.remove(this.transport, id), diff --git a/src/core/clientConfig.ts b/src/core/clientConfig.ts index cdabed5..a9cb584 100644 --- a/src/core/clientConfig.ts +++ b/src/core/clientConfig.ts @@ -1,13 +1,28 @@ import type { FetchTransportConfig } from "./fetchTransport"; export interface ClientConfig extends Pick { - /** The instance base URL: "https://agility.example.com/MyInstance". */ + /** + * The instance base URL: "https://agility.example.com/MyInstance". The + * built-in fetch transport sends every request under it. With a custom + * Transport (`new AgilityApiClient(config, { transport })`) the transport + * alone decides where requests go, and `baseUrl` is used for one thing: + * the links the client builds for a browser (`client.urls.*`, + * `client.embeddedImages.normalize`). Give it the instance's public URL + * even when the transport talks to a proxy. + */ baseUrl: string; /** A ready Authorization header value ("Basic …" for a dev instance). Wins over accessToken. */ authorization?: string; /** An access token, sent as "Bearer ". */ accessToken?: string; + /** Per-attempt timeout of the built-in fetch transport. A custom Transport does its own timing. */ timeoutMs?: number; + /** + * Resends of an idempotent request by the built-in fetch transport + * (default 1). Retrying is the transport's job: with a custom Transport + * this is not read, and nothing is resent unless that transport does it + * (`RequestOptions.idempotent` tells it which requests may be). + */ retries?: number; defaultHeaders?: Record; } diff --git a/src/core/errors.ts b/src/core/errors.ts index 13358ed..494819c 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -46,6 +46,12 @@ export class ApiError extends Error { readonly status: number; readonly code?: string; readonly details?: unknown; + /** + * What to do about it (see ErrorKind). "usage" means the SDK refused the + * call before sending anything: no request reached the server, `status` + * is 0, and the fix is in the calling code, so a formatter should not + * word it as a server error. + */ readonly kind: ErrorKind; constructor(message: string, status: number, code?: string, details?: unknown, kind: ErrorKind = kindOf(status, code)) { @@ -59,6 +65,40 @@ export class ApiError extends Error { } } +/** + * The message of an error response, from the shapes the Agility endpoints + * actually send: rest-1's { _type: "Error", error, exceptions: [{ message }] }, + * api/asset's { Exceptions: ["…"] } (a request it could not parse — 400 + * with the parser's message since 2026-11, an opaque 500 before), a bare + * { message }, or text. + */ +function messageOf(data: unknown, status: number): string { + if (data && typeof data === "object") { + const d = data as Record; + const first = Array.isArray(d.exceptions) && d.exceptions[0] && typeof d.exceptions[0] === "object" ? (d.exceptions[0] as Record).message : undefined; + const listed = Array.isArray(d.Exceptions) ? d.Exceptions.filter((x): x is string => typeof x === "string" && !!x).join("; ") : undefined; + for (const candidate of [d.error, first, listed, d.message]) { + if (typeof candidate === "string" && candidate) return candidate; + } + } + if (typeof data === "string" && data.trim()) return data.trim().slice(0, 200); + return `HTTP ${status}`; +} + +/** + * The ApiError for a response the server refused: what the fetch transport + * throws for a status outside 2xx, for a custom Transport to throw too, so + * its errors carry the same message, `kind` and `details` whichever + * transport sent the request. `data` is the response body as read — the + * parsed JSON when the server sent JSON, else the text. The message comes + * from the shapes the endpoints send (rest-1's `exceptions`, api/asset's + * `Exceptions`, a bare `message`, or the text itself), `HTTP ` + * when the body says nothing; `details` is `data` unchanged. + */ +export function apiErrorFromResponse(status: number, data?: unknown): ApiError { + return new ApiError(messageOf(data, status), status, undefined, data); +} + /** * A mistake in the call, caught before any request is sent: an unpaged * query, an empty batch, a string that is not an OID token. Nothing on the diff --git a/src/core/fetchTransport.ts b/src/core/fetchTransport.ts index 7838fd7..fdf9599 100644 --- a/src/core/fetchTransport.ts +++ b/src/core/fetchTransport.ts @@ -1,4 +1,4 @@ -import { ApiError } from "./errors"; +import { ApiError, apiErrorFromResponse } from "./errors"; import type { RequestBody, RequestOptions, ResponseType, Transport } from "./transport"; /** @@ -118,26 +118,6 @@ async function readBody(response: Response, responseType: ResponseType): Promise return response.text(); } -/** - * The message of an error response, from the shapes the Agility endpoints - * actually send: rest-1's { _type: "Error", error, exceptions: [{ message }] }, - * api/asset's { Exceptions: ["…"] } (a request it could not parse — 400 - * with the parser's message since 2026-11, an opaque 500 before), a bare - * { message }, or text. - */ -function messageOf(data: unknown, status: number): string { - if (data && typeof data === "object") { - const d = data as Record; - const first = Array.isArray(d.exceptions) && d.exceptions[0] && typeof d.exceptions[0] === "object" ? (d.exceptions[0] as Record).message : undefined; - const listed = Array.isArray(d.Exceptions) ? d.Exceptions.filter((x): x is string => typeof x === "string" && !!x).join("; ") : undefined; - for (const candidate of [d.error, first, listed, d.message]) { - if (typeof candidate === "string" && candidate) return candidate; - } - } - if (typeof data === "string" && data.trim()) return data.trim().slice(0, 200); - return `HTTP ${status}`; -} - const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); /** The longest a Retry-After is honoured before the request is given up instead. */ @@ -227,7 +207,7 @@ export function createFetchTransport(config: FetchTransportConfig): Transport { // An answer, not a failure to get one. 5xx may be retried when // idempotent; anything else is final. const data = await readBody(response, responseType === "bytes" ? "text" : responseType === "json" ? "auto" : responseType); - lastError = new ApiError(messageOf(data, response.status), response.status, undefined, data); + lastError = apiErrorFromResponse(response.status, data); } catch (error) { if (callerSignal?.aborted) throw abortedError(callerSignal); throw error; diff --git a/src/index.ts b/src/index.ts index 71352ac..8bc0f06 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ export { AgilityApiClient } from "./client"; export type { ClientOptions, Me, Page, PagesOptions } from "./client"; -export { ApiError, UsageError, WrappedError, kindOf } from "./core/errors"; +export { ApiError, UsageError, WrappedError, apiErrorFromResponse, kindOf } from "./core/errors"; export type { ErrorKind } from "./core/errors"; export { createFetchTransport } from "./core/fetchTransport"; export type { FetchTransportConfig, UnauthorizedContext, UnauthorizedDecision } from "./core/fetchTransport"; @@ -16,7 +16,9 @@ export type { AssetType, AttributeDefinition, AttributeLookup, AttributeType, At export type * from "./types/assets/index"; export type { CreateType, CustomList, From, RowOf, RowsOf, SelectKey, SelectPath, SelectValue, Selected, TypeOf } from "./types/query"; -// The wire layer: one module per endpoint. +// The wire layer: one module per endpoint. Also importable from +// "@versionone/agility-sdk/wire", which is where these six move for good: +// the root re-exports of the modules go in the next alpha. export { assetApi, rest1, meta, loc2, queryV1, attachment, fields } from "./wire"; export type { OperationResult, Template } from "./wire/rest1"; export type { FieldsOf } from "./services/fields"; @@ -26,7 +28,8 @@ export * as select from "./wire/select"; export type { AssetApiResponse, Command, CommandBody, CommandFailureDetail, Outcome, CommandValue, CreateBody, ExecuteBody, QueryBody, UpdateBody, ReadOptions, RowContext, SendOptions } from "./wire/assetApi"; export { CommandFailureError, parseViolation } from "./wire/assetApi"; export type { Violation } from "./wire/assetApi"; -export type { AssetDocument, AssetsDocument, ReadParams, ReadResult } from "./wire/rest1"; +export type { AssetDocument, AssetsDocument, LooseQuery, ReadParams, ReadResult } from "./wire/rest1"; +export { normalizeQuery } from "./wire/rest1"; export type { Localizations, LocalizeOptions } from "./wire/loc2"; export type { ConditionalOptions, Tagged } from "./wire/meta"; export type { QueryRejection } from "./wire/queryV1"; @@ -34,7 +37,7 @@ export type { QueryRejection } from "./wire/queryV1"; // Services: what to do. export { Schema, TypeCache } from "./services/schema"; export { AttachmentUploadError, INLINE_LIMIT } from "./services/attachments"; -export type { AddOptions as AttachmentAddOptions, AttachmentInfo } from "./services/attachments"; +export type { AddOptions as AttachmentAddOptions, AttachmentFile, AttachmentInfo, GetOptions as AttachmentGetOptions, ListOptions as AttachmentListOptions, ListedAttachment } from "./services/attachments"; export { CHUNK as RESOLVE_CHUNK, NUMBER_ROOTS, isAssetNumber, resolveNumbers, resolveRef } from "./services/resolve"; export type { Resolution, ResolvedAsset } from "./services/resolve"; export { UNGUARDABLE_TYPES, UnguardableError, guard, sendGuarded, stampsOf, touchedBy, unguardable } from "./services/guard"; diff --git a/src/services/attachments.ts b/src/services/attachments.ts index c15846e..370dda5 100644 --- a/src/services/attachments.ts +++ b/src/services/attachments.ts @@ -11,67 +11,141 @@ * Attachment with empty Content, then POST the raw bytes. A failed * upload leaves an empty Attachment, which is reported, not hidden. * - * Listing never selects Content: across many attachments that would Base64 - * every file into one response. Reading one file's bytes goes through - * attachment.img. + * Listing never selects Content by itself: across many attachments that + * would Base64 every file into one response. Reading one file's bytes goes + * through attachment.img, or — for a small file, on request — comes inline + * with its row in one read (`get` with `inline`). */ import { ApiError, WrappedError } from "../core/errors"; import type { Transport } from "../core/transport"; -import type { Oid } from "../types/asset"; +import type { Asset, DateString, Oid } from "../types/asset"; +import type { Attachment } from "../types/assets/Attachment"; import { momentless } from "../types/oid"; +import type { SelectKey, SelectPath, SelectValue } from "../types/query"; import * as assetApi from "../wire/assetApi"; -import { getFile, numericId, putBytes, toBase64, toUint8Array, type Bytes } from "../wire/attachment"; +import { fromBase64, getFile, numericId, putBytes, toBase64, toUint8Array, type Bytes } from "../wire/attachment"; +import * as queryV1 from "../wire/queryV1"; +import type { Schema } from "./schema"; /** Files up to this size go inline by default; larger ones in two steps. */ export const INLINE_LIMIT = 1_000_000; +/** + * An attachment as the SDK answers it: a row of the Attachment asset type, + * under meta.v1's own attribute names like every other row, with what was + * selected and nothing else — plus `id`, the number attachment.img + * addresses the file by (the one place the API uses a bare id). The type + * is closed: it has these keys and the ones a `select` named, so reading + * any other (`row.filename`, `row.FileName`) is a compile error. + */ export interface AttachmentInfo { - oid: Oid; - /** The numeric id attachment.img addresses it by. */ + /** The attachment's OID token, momentless: "Attachment:5678". */ + _oid: Oid; + /** The numeric id attachment.img addresses it by: "5678" for Attachment:5678. */ id: string; - name: string | null; - filename: string | null; - contentType: string | null; - description: string | null; - createDate: string | null; - createdBy: string | null; + Name: string | null; + Filename: string | null; + /** The content type recorded on the Attachment. */ + ContentType: string | null; + Description: string | null; + CreateDate: DateString | null; + /** The creating member's name: the select path, as selected. */ + "CreatedBy.Name": string | null; } -type Row = { _oid: string; Name?: string | null; Filename?: string | null; ContentType?: string | null; Description?: string | null; CreateDate?: string | null; "CreatedBy.Name"?: string | null }; -const SELECT = ["Name", "Filename", "ContentType", "Description", "CreateDate", "CreatedBy.Name"]; -const infoOf = (r: Row): AttachmentInfo => { - const oid = momentless(r._oid); - return { oid, id: numericId(oid), name: r.Name ?? null, filename: r.Filename ?? null, contentType: r.ContentType ?? null, description: r.Description ?? null, createDate: r.CreateDate ?? null, createdBy: r["CreatedBy.Name"] ?? null }; +/** What every attachment read selects. */ +export const SELECT = ["Name", "Filename", "ContentType", "Description", "CreateDate", "CreatedBy.Name"] as const; +const DEFAULTS: Record = Object.fromEntries(SELECT.map((k) => [k, null])); +/** A row as answered: OID momentless, its numeric id beside it, an attribute the server left out read as null. */ +const infoOf = (row: Asset): T => { + const oid = momentless(row._oid); + return { ...DEFAULTS, ...row, _oid: oid, id: numericId(oid) } as unknown as T; }; -/** One page of the files attached to an asset, newest first, metadata only, with the total and whether more pages follow. */ -export async function page(transport: Transport, asset: Oid, options: { page?: { size: number; start: number } } = {}): Promise<{ attachments: AttachmentInfo[]; total: number | null; more: boolean }> { - const { rows, total, more } = await assetApi.queryPage(transport, { from: "Attachment", select: SELECT, filter: ["Asset=$asset"], with: { $asset: momentless(asset) }, sort: ["-CreateDate"], page: options.page ?? { size: 50, start: 0 } }); - return { attachments: rows.map((r) => infoOf(r as unknown as Row)), total, more }; +type Extra = readonly (SelectPath | assetApi.QueryBody)[]; + +/** What `list` and `page` take: the page (default the first 50) and, optionally, more to select. */ +export interface ListOptions { + page?: { size: number; start: number }; + /** + * More to read with each attachment, as a query's `select` on Attachment + * (`Category.Name`, `Asset.Number`, a sub-select): each row then carries + * those keys too, as selected. The metadata is always read. Selecting + * `Content` here Base64s every file on the page into one response: for + * one small file use `get` with `inline`. + */ + select?: S; + /** The schema to translate the extra values with (numbers as numbers, a single relation as one Ref); the client passes its own. Without it they keep the endpoint's spelling. */ + schema?: Schema; } -/** The files attached to an asset, newest first, metadata only (one page; `page` also gives the total). */ -export async function list(transport: Transport, asset: Oid, options: { page?: { size: number; start: number } } = {}): Promise { - const rows = await assetApi.query(transport, { from: "Attachment", select: SELECT, filter: ["Asset=$asset"], with: { $asset: momentless(asset) }, sort: ["-CreateDate"], page: options.page ?? { size: 50, start: 0 } }); - return rows.map((r) => infoOf(r as unknown as Row)); +/** An attachment row with the extra keys a `select` added, typed by what was selected. */ +export type ListedAttachment = S extends readonly (infer E)[] ? AttachmentInfo & { [K in SelectKey]: SelectValue } : AttachmentInfo; + +/** The query `list` and `page` send, and how to read it. */ +async function listing(asset: Oid, options: ListOptions) { + const extra = (options.select ?? []) as readonly (string | assetApi.QueryBody)[]; + const have = new Set(SELECT); + const q: assetApi.QueryBody = { from: "Attachment", select: [...SELECT, ...extra.filter((e) => !(typeof e === "string" && have.has(e)))], filter: ["Asset=$asset"], with: { $asset: momentless(asset) }, sort: ["-CreateDate"], page: options.page ?? { size: 50, start: 0 } }; + if (options.select && options.schema) await options.schema.ensureFor([q]); + const read: assetApi.ReadOptions = options.select && options.schema ? { lookup: options.schema } : {}; + return { q, read }; +} + +/** One page of the files attached to an asset, newest first, metadata only (plus whatever `select` adds), with the total and whether more pages follow. */ +export async function page(transport: Transport, asset: Oid, options: ListOptions = {}): Promise<{ attachments: ListedAttachment[]; total: number | null; more: boolean }> { + const { q, read } = await listing(asset, options); + const { rows, total, more } = await assetApi.queryPage(transport, q, read); + return { attachments: rows.map((r) => infoOf>(r)), total, more }; +} + +/** The files attached to an asset, newest first, metadata only (plus whatever `select` adds); one page (`page` also gives the total). */ +export async function list(transport: Transport, asset: Oid, options: ListOptions = {}): Promise[]> { + const { q, read } = await listing(asset, options); + return (await assetApi.query(transport, q, read)).map((r) => infoOf>(r)); } /** One attachment's metadata, or null when there is none with that id. */ export async function info(transport: Transport, id: Oid | string | number): Promise { - const [row] = await assetApi.query(transport, { from: "Attachment", select: SELECT, filter: ["ID=$id"], with: { $id: `Attachment:${numericId(id)}` }, page: { size: 1, start: 0 } }); - return row ? infoOf(row as unknown as Row) : null; + const [row] = await assetApi.query(transport, { from: "Attachment", select: [...SELECT], filter: ["ID=$id"], with: { $id: `Attachment:${numericId(id)}` }, page: { size: 1, start: 0 } }); + return row ? infoOf(row) : null; +} + +export interface GetOptions { + /** + * Read the bytes inline with the metadata, in one request instead of + * two: the Attachment's Content comes back as Base64 beside its row + * (through query.v1, so the read is resent like a GET). For small files: + * the response is a third larger than the file and is held in memory + * whole, and the size is not known until it arrives. `servedContentType` + * is then null (no attachment.img response to read one from). + */ + inline?: boolean; +} + +/** An attachment with its bytes. */ +export interface AttachmentFile extends AttachmentInfo { + bytes: Uint8Array; + /** The Content-Type attachment.img served the bytes with; null for an inline read. `ContentType` is the recorded one. */ + servedContentType: string | null; } /** - * One attachment: its metadata and its bytes. `contentType` is the type the - * server sent the bytes with, falling back to the Attachment's recorded - * one; `recordedContentType` is always the latter. + * One attachment: its metadata and its bytes. Two requests by default (the + * row, then attachment.img), one with `inline`. */ -export async function get(transport: Transport, id: Oid | string | number): Promise { +export async function get(transport: Transport, id: Oid | string | number, options: GetOptions = {}): Promise { + if (options.inline) { + const [row] = await queryV1.query(transport, { from: "Attachment", select: [...SELECT, "Content"], filter: ["ID=$id"], with: { $id: `Attachment:${numericId(id)}` }, page: { size: 1, start: 0 } }); + if (!row) throw new ApiError(`attachment ${numericId(id)}: not found`, 404, "NOT_FOUND"); + const { Content: content, ...rest } = row as Asset & { Content?: unknown }; + if (typeof content !== "string") throw new ApiError(`attachment ${numericId(id)}: the row came without its Content`, 200, "BAD_RESPONSE", row); + return { ...infoOf(rest), bytes: fromBase64(content), servedContentType: null }; + } const meta = await info(transport, id); if (!meta) throw new ApiError(`attachment ${numericId(id)}: not found`, 404, "NOT_FOUND"); const file = await getFile(transport, meta.id); - return { ...meta, bytes: file.bytes, contentType: file.contentType ?? meta.contentType, recordedContentType: meta.contentType }; + return { ...meta, bytes: file.bytes, servedContentType: file.contentType }; } export interface AddOptions { @@ -88,12 +162,12 @@ export interface AddOptions { /** An Attachment was created but its bytes could not be uploaded: it exists, empty. Remove it or upload again with `put`. */ export class AttachmentUploadError extends WrappedError { constructor(readonly attachment: AttachmentInfo, cause: unknown) { - super(`${attachment.oid} was created on its asset with no content, and uploading the file failed: ${cause instanceof Error ? cause.message : String(cause)}`, "ATTACHMENT_UPLOAD", cause); + super(`${attachment._oid} was created on its asset with no content, and uploading the file failed: ${cause instanceof Error ? cause.message : String(cause)}`, "ATTACHMENT_UPLOAD", cause); this.name = "AttachmentUploadError"; } } -/** Attach a file to an asset. Inline up to `inlineLimit` bytes, two-step above it. */ +/** Attach a file to an asset. Inline up to `inlineLimit` bytes, two-step above it. Answers the attachment as written (its `CreateDate` and creator are null: read it with `info` for those). */ export async function add(transport: Transport, asset: Oid, data: Bytes, options: AddOptions): Promise { const bytes = await toUint8Array(data); const contentType = options.contentType ?? (typeof Blob !== "undefined" && data instanceof Blob && data.type ? data.type : "application/octet-stream"); @@ -101,7 +175,8 @@ export async function add(transport: Transport, asset: Oid, data: Bytes, options const create: assetApi.CreateBody = { AssetType: "Attachment", Asset: momentless(asset), Name: options.name ?? options.filename, Filename: options.filename, ContentType: contentType, Content: inline ? toBase64(bytes) : "" }; if (options.description) create.Description = options.description; const oid = assetApi.outcomeOf(await assetApi.send(transport, [create], { throwOnFailure: true })).created[0]!; - const created: AttachmentInfo = { oid, id: numericId(oid), name: String(create.Name), filename: options.filename, contentType, description: options.description ?? null, createDate: null, createdBy: null }; + // What was written; the server's own stamps (CreateDate, the creator) are not read back. + const created: AttachmentInfo = { _oid: oid, id: numericId(oid), Name: String(create.Name), Filename: options.filename, ContentType: contentType, Description: options.description ?? null, CreateDate: null, "CreatedBy.Name": null }; if (!inline) { try { await putBytes(transport, created.id, bytes, contentType); diff --git a/src/services/guard.ts b/src/services/guard.ts index 2643c19..19c9658 100644 --- a/src/services/guard.ts +++ b/src/services/guard.ts @@ -185,6 +185,7 @@ export async function sendPasses(transport: Transport const passes = passesOf(projected); const outcome = assetApi.emptyOutcome(); const sent: Command[] = [], unstamped: Oid[] = []; + const requestIds: (string | null)[] = []; let applied = new Set(); for (const [k, pass] of passes.entries()) { let current: { commands: Command[]; unstamped: Oid[] }; @@ -209,8 +210,11 @@ export async function sendPasses(transport: Transport } sent.push(...commands); assetApi.mergeOutcome(outcome, done, offset); + requestIds.push(done.requestId); applied = new Set([...done.modified, ...done.operated].map(momentless)); } + // One send (the usual case) has one request id, and it is the outcome's; several sends have none that is "the" request. + if (requestIds.length === 1) outcome.requestId = requestIds[0]!; return { outcome, sent, unstamped: [...new Set(unstamped)] }; } diff --git a/src/testing/index.ts b/src/testing/index.ts new file mode 100644 index 0000000..1d2baa5 --- /dev/null +++ b/src/testing/index.ts @@ -0,0 +1,265 @@ +/** + * `@versionone/agility-sdk/testing`: a client for a consumer's unit tests. + * + * A FakeAgilityClient is a real AgilityApiClient — every check the client + * makes before a request (a page on every read, a well-formed OID) still + * runs, and every service still composes its requests — over a transport + * that sends nothing and answers from what the test scripted. It is + * scripted in the model's shape, the shape the client hands a consumer: + * rows with numbers as numbers and a relation as a Ref, OIDs for a write. + * What it does not do is behave like the server: it evaluates no filter, + * sort or `where`, applies no write, and translates nothing. A test + * asserts on what was asked (`asked`, `sent`, `requests`) and scripts + * what comes back; whether the server would answer that way is what an + * integration test against an instance is for. + */ +import { AgilityApiClient } from "../client"; +import type { ClientConfig } from "../core/clientConfig"; +import { ApiError, UsageError, apiErrorFromResponse } from "../core/errors"; +import type { RequestOptions, Transport } from "../core/transport"; +import { Schema } from "../services/schema"; +import type { Asset, Oid } from "../types/asset"; +import { isOidToken, momentless, typeOfOid } from "../types/oid"; +import type { Command, CommandBody, QueryBody } from "../wire/assetApi"; + +/** A scripted row: an OID and whatever the code under test selects, in the model's shape. */ +export type FakeRow = Asset & { [attribute: string]: unknown }; + +/** What a scripted query answers: the rows, or the rows with the total a paged read reports. */ +export type FakeRows = readonly FakeRow[] | { rows: readonly FakeRow[]; total?: number | null }; + +/** What a scripted write answers; anything left out is empty. `failures` are by index in the batch as sent. */ +export interface FakeOutcome { + created?: Oid[]; + modified?: Oid[]; + operated?: Oid[]; + failures?: { index: number; message: string }[]; +} + +type QueryAnswer = FakeRows | Error | ((q: QueryBody) => FakeRows); +type SendAnswer = FakeOutcome | Error | ((commands: Command[]) => FakeOutcome); +type RequestAnswer = unknown | ((request: RequestOptions) => unknown); +type QueryMatch = string | ((q: QueryBody) => boolean); +type RequestMatch = string | RegExp | ((request: RequestOptions) => boolean); + +const bodyOf = (command: Command): CommandBody => { + const keys = Object.keys(command); + return (keys.length === 1 && keys[0]!.startsWith("@") ? (command as Record)[keys[0]!] : command) as CommandBody; +}; +const isQuery = (body: CommandBody): body is QueryBody => typeof (body as QueryBody).from === "string" && !("update" in body) && !("execute" in body) && !("AssetType" in body); +const typeOfFrom = (from: string): string => (isOidToken(from) ? typeOfOid(from) ?? from : from); + +interface Script { + queries: { match: QueryMatch; answer: QueryAnswer }[]; + sends: SendAnswer[]; + requests: { match: RequestMatch; answer: RequestAnswer }[]; + labels: Record; + seen: { requests: RequestOptions[]; asked: QueryBody[]; sent: Command[][] }; + nextId: number; +} + +/** The scripted rows for one query, and the total a paged read would report. */ +const hitFor = (script: Script, q: QueryBody, type: string) => + // The answer scripted last wins, so a test can override what a shared setup scripted. + [...script.queries].reverse().find(({ match }) => (typeof match === "function" ? match(q) : match === q.from || match === type)); + +/** Every row scripted as a list, whatever its type: what a lookup by Number searches. */ +const scriptedRows = (script: Script): FakeRow[] => + script.queries.flatMap(({ answer }) => (Array.isArray(answer) ? answer : answer && typeof answer === "object" && !(answer instanceof Error) && "rows" in answer ? [...(answer as { rows: readonly FakeRow[] }).rows] : []) as FakeRow[]); + +/** The resolver's question: one query per number root, each `Number=$numbers`. */ +const isNumberLookup = (q: QueryBody): boolean => q.filter?.length === 1 && q.filter[0] === "Number=$numbers" && Array.isArray(q.with?.$numbers); + +/** The scripted rows for one query, and the total a paged read would report. `created` is the asset an alias `from` ("@story") names: the create earlier in the same batch. */ +function answerQuery(script: Script, q: QueryBody, created?: { type: string; oid: Oid | undefined; sent: Record }): { rows: Asset[]; total: number | null } { + script.seen.asked.push(q); + const type = created?.type ?? typeOfFrom(q.from); + const hit = hitFor(script, q, type); + if (!hit) throw new UsageError(`FakeAgilityClient: no answer scripted for a query of ${q.from}${created ? ` (the ${type} the batch creates)` : ""}; script one with fake.onQuery("${type}", rows)`); + if (hit.answer instanceof Error) throw hit.answer; + if (typeof hit.answer === "function") { + const answered = hit.answer(q); + return Array.isArray(answered) ? { rows: [...answered], total: null } : { rows: [...(answered as { rows: readonly Asset[] }).rows], total: (answered as { total?: number | null }).total ?? null }; + } + const scripted = hit.answer as FakeRows; + if (!Array.isArray(scripted)) { const s = scripted as { rows: readonly Asset[]; total?: number | null }; return { rows: [...s.rows], total: s.total ?? null }; } + // Rows scripted as a list are the whole result: a read by OID gets the row + // with that OID, and a page gets its slice, so `get` and `pages` end as + // they would against a server. + // A read-back of the batch's own create: the first scripted row of its type stands in for what the server + // would add (a Number, defaults), the scalar values the create sent win over it (a relation, sent as an + // OID token or an alias, is not a row's Ref and is left to the script), and the OID is the created one. + if (created) { + const sent = Object.fromEntries(Object.entries(created.sent).filter(([k, v]) => k !== "AssetType" && (v === null || typeof v !== "object") && !isOidToken(v) && !(typeof v === "string" && v.startsWith("@")))); + return { rows: created.oid ? [{ ...(scripted[0] ?? {}), ...sent, _oid: created.oid }] : [], total: created.oid ? 1 : 0 }; + } + const all = isOidToken(q.from) ? scripted.filter((row) => momentless(row._oid) === momentless(q.from)) : [...scripted]; + const page = q.page ?? { size: all.length, start: 0 }; + return { rows: all.slice(page.start, page.start + page.size), total: all.length }; +} + +/** What a batch's writes answer: the scripted outcome, or one made up from the commands (a new OID per create, the addressed OID for an update or an operation). */ +function answerSend(script: Script, commands: Command[], writes: { body: CommandBody; index: number }[]): Required { + script.seen.sent.push(commands); + const answer = script.sends[script.sends.length - 1]; + if (answer instanceof Error) throw answer; + if (answer) return { created: [], modified: [], operated: [], failures: [], ...(typeof answer === "function" ? answer(commands) : answer) }; + const out: Required = { created: [], modified: [], operated: [], failures: [] }; + for (const { body } of writes) { + if ("AssetType" in body) out.created.push(`${String(body.AssetType)}:${script.nextId++}`); + else if ("update" in body && isOidToken(body.from)) out.modified.push(momentless(body.from)); + else if ("execute" in body && isOidToken(body.from)) out.operated.push(momentless(body.from)); + } + return out; +} + +function respond(script: Script, request: RequestOptions): unknown { + script.seen.requests.push(request); + const raw = [...script.requests].reverse().find(({ match }) => (typeof match === "string" ? request.path.startsWith(match) : match instanceof RegExp ? match.test(request.path) : match(request))); + if (raw) { + if (raw.answer instanceof Error) throw raw.answer; + return typeof raw.answer === "function" ? (raw.answer as (r: RequestOptions) => unknown)(request) : raw.answer; + } + // A type nothing scripted is a type the fake's instance does not have: a client built on `fake.transport` then reads rows as scripted, like the fake itself. + if (request.method === "GET" && request.path.startsWith("/meta.v1/")) throw apiErrorFromResponse(404, { error: "Not Found", exceptions: [{ message: `FakeAgilityClient knows no asset type at ${request.path}` }] }); + if (request.path.startsWith("/loc-2.v1")) { + // loc-2 answers a tag it does not know with the tag itself; so does the fake, for every tag onLocalize did not script. + const encoded = request.method === "GET" ? request.path.slice(request.path.indexOf("?") + 1) : String(request.body); + return Object.fromEntries((JSON.parse(decodeURIComponent(encoded)) as string[]).map((tag) => [tag, script.labels[tag] ?? tag])); + } + if (request.method === "POST" && request.path === "/query.v1") return (request.body as QueryBody[]).map((q) => answerQuery(script, q).rows); + if (request.method === "POST" && request.path === "/api/asset" && Array.isArray(request.body)) { + const commands = request.body as Command[]; + // A preview answers the projection; the fake's is the batch as written. + if (request.query?.previewOnly) return commands; + const bodies = commands.map((c, index) => ({ body: bodyOf(c), index, alias: Object.keys(c).length === 1 && Object.keys(c)[0]!.startsWith("@") ? Object.keys(c)[0]! : null })); + const writes = bodies.filter(({ body }) => !isQuery(body)); + const done = writes.length ? answerSend(script, commands, writes) : { created: [], modified: [], operated: [], failures: [] }; + // The i-th create made the i-th created OID; a query from its alias reads that asset back. + const creates = writes.filter(({ body }) => "AssetType" in body); + const createdBy = (from: string) => { + const i = creates.findIndex(({ alias }) => alias === from); + return i < 0 ? undefined : { type: String((creates[i]!.body as { AssetType: unknown }).AssetType), oid: done.created[i], sent: creates[i]!.body as Record }; + }; + const asked = bodies.filter(({ body }) => isQuery(body)).map(({ body }) => body as QueryBody); + let answers: { rows: Asset[]; total: number | null }[]; + if (asked.length && asked.every(isNumberLookup) && !asked.some((q) => hitFor(script, q, q.from))) { + // resolve.numbers asks every number root at once; which roots is the SDK's business, so the fake answers + // from every row a test scripted, by Number, whatever its type. A number no row has is simply not found. + const wanted = new Set((asked[0]!.with!.$numbers as string[]).map((n) => n.toUpperCase())); + const found = scriptedRows(script).filter((row) => typeof row.Number === "string" && wanted.has(row.Number.toUpperCase())); + script.seen.asked.push(...asked); + answers = asked.map((_, i) => ({ rows: i === 0 ? found : [], total: i === 0 ? found.length : 0 })); + } else answers = asked.map((q) => answerQuery(script, q, q.from.startsWith("@") ? createdBy(q.from) : undefined)); + const tokens = (oidTokens: Oid[]) => ({ oidTokens, count: oidTokens.length }); + return { + requestId: `fake-${script.seen.requests.length}`, createdDate: "", completedDate: "", duration: "", durationSeconds: 0, complete: true, processing: false, + assetsCreated: tokens(done.created), assetsModified: tokens(done.modified), assetsOperatedOn: tokens(done.operated), + commandFailures: { commands: done.failures.map(({ index, message }) => ({ error: { message, sourceCommandIndex: index } })), count: done.failures.length }, + queryResult: { results: answers.map((a) => a.rows), resultMetaData: answers.map((a) => ({ total: a.total })), count: answers.length } + }; + } + throw new UsageError(`FakeAgilityClient: no answer scripted for ${request.method} ${request.path}; script one with fake.onRequest("${request.path}", answer)`); +} + +/** + * An AgilityApiClient that sends nothing: reads answer the rows a test + * scripted, writes are recorded and answer OIDs, and everything asked is + * kept for the test to assert on. + * + * ```ts + * import { FakeAgilityClient } from "@versionone/agility-sdk/testing"; + * + * const fake = new FakeAgilityClient() + * .onQuery("Story", [{ _oid: "Story:1", Name: "Logon", Estimate: 2 }]); + * const rows = await listStories(fake); // the code under test takes an AgilityApiClient + * expect(fake.asked[0]).toMatchObject({ from: "Story", filter: ["Scope=$scope"] }); + * ``` + * + * - `onQuery(match, rows)` answers `query`, `queries`, `get`, `queryPage`, + * `pages`, `all` and everything built on them. Rows are in the model's + * shape and come back as scripted. A list is the whole result: the fake + * pages it, reports its length as the total, and answers a read by OID + * with the row of that OID. A function gets the query and answers one + * page itself (`onQuery((q) => q.from === "StoryStatus" && + * q.filter?.[0]?.startsWith("Team."), teamStatuses)` tells two queries + * of one type apart). No filter, `where` or sort is evaluated. A query nothing + * was scripted for throws a UsageError: an unscripted read never looks + * like an empty result. + * - `assets.send` needs no script: each create answers a new OID + * (`Story:1000`, `Story:1001`, …), each update or operation addressed by + * OID answers that OID. `onSend` scripts anything else (failures by + * index, a create's OID). + * - A query from an alias of a create in the same batch (`from: "@story"`) + * answers the first row scripted for the created type, under the OID the + * create answered and with the scalar values the create sent. `resolve.numbers` and `resolve.ref` find a number + * among every row scripted as a list, by its `Number`; one no row has is + * `missing`. `localize` answers each tag with its `onLocalize` label, or + * with the tag itself. + * - `fake.transport` can be the Transport of another client (one your code + * builds and wraps): it reads rows as scripted too, because the fake + * answers every meta.v1 type read with 404, "no such type". + * - `onRequest(match, answer)` answers any other request by path, in the + * endpoint's own shape (rest-1 behind `client.data`, attachment bytes, + * meta.v1), and wins over everything above. Guarded sends and + * `batch.run` are not scripted by the fake: their request sequence is + * internal to the SDK and changes between alphas, so fake the function + * of yours that calls them. + * - An `Error` as an answer is thrown: `new ApiError("Unauthorized", 401)`, + * or `apiErrorFromResponse(status, body)` for a refusal as the fetch + * transport words it. + */ +export class FakeAgilityClient extends AgilityApiClient { + /** Every request the client made, in order, as a Transport sees it. */ + readonly requests: RequestOptions[]; + /** Every query asked, in order, whichever read asked it. */ + readonly asked: QueryBody[]; + /** Every batch that carried a write, in order, as sent: a Ref is written as its OID token. */ + readonly sent: Command[][]; + private readonly script: Script; + + constructor(config: Partial = {}) { + const script: Script = { queries: [], sends: [], requests: [], labels: {}, seen: { requests: [], asked: [], sent: [] }, nextId: 1000 }; + const transport: Transport = { + // Answers are computed synchronously and delivered as a real response would be: later, and a throw as a rejection. + request: async (request: RequestOptions): Promise => { + if (request.signal?.aborted) throw new ApiError("Request aborted", 0, "ABORTED", { cause: request.signal.reason }); + return respond(script, request) as T; + } + }; + // A schema with nothing to load: rows are scripted in the model's shape and pass through as written. + super({ baseUrl: "https://agility.example.com/Fake", ...config }, { transport, schema: new Schema() }); + this.script = script; + this.requests = script.seen.requests; + this.asked = script.seen.asked; + this.sent = script.seen.sent; + } + + /** + * Script the answer to queries of an asset type (`"Story"`, which also + * matches a read by OID of that type), of one OID (`"Story:1"`), or + * matching a predicate. The answer scripted last wins. + */ + onQuery(match: QueryMatch, answer: QueryAnswer): this { + this.script.queries.push({ match, answer }); + return this; + } + + /** Script what writes answer from here on: an outcome, a function of the batch, or an Error to throw. */ + onSend(answer: SendAnswer): this { + this.script.sends.push(answer); + return this; + } + + /** Script labels for `client.localize`: tag → label. A tag nothing scripted answers itself, as loc-2 answers a tag it does not know. */ + onLocalize(labels: Record): this { + Object.assign(this.script.labels, labels); + return this; + } + + /** Script the answer to any request by path (a prefix, a RegExp, or a predicate), in the endpoint's own shape. Wins over onQuery and onSend. */ + onRequest(match: RequestMatch, answer: RequestAnswer): this { + this.script.requests.push({ match, answer }); + return this; + } +} diff --git a/src/wire/rest1.ts b/src/wire/rest1.ts index f87e37d..e32a338 100644 --- a/src/wire/rest1.ts +++ b/src/wire/rest1.ts @@ -38,6 +38,7 @@ import { ApiError, UsageError } from "../core/errors"; import type { Transport } from "../core/transport"; import { assetStateOf, type Asset, type Oid, type Ref } from "../types/asset"; import { momentless } from "../types/oid"; +import type { QueryBody } from "./assetApi"; export { momentless }; @@ -191,3 +192,78 @@ export const history = (transport: Transport, target: const path = id ? `/rest-1.v1/Hist/${encodeURIComponent(type!)}/${encodeURIComponent(id)}` : `/rest-1.v1/Hist/${encodeURIComponent(type!)}`; return read(transport, path, params, true); }; + +// ---- rest-1 spellings of a query ----------------------------------------------- + +/** + * A query as someone who knows rest-1 writes it, or as a saved rest-1 URL's + * parameters read: `sel` for `select`, `where` as filter text, lists as + * comma-joined strings, `page` as "size,start". Anything a QueryBody + * already says is accepted unchanged. + */ +export interface LooseQuery { + from: string; + select?: string | (string | LooseQuery)[]; + /** rest-1's spelling of `select`. */ + sel?: string | (string | LooseQuery)[]; + filter?: string | string[]; + /** rest-1's spelling: filter text (one term, or a list of terms). An object is a query's own `where` (attribute → value) and stays one. */ + where?: string | string[] | Record; + sort?: string | string[]; + findin?: string | string[]; + /** `{ size, start }`, or rest-1's "size,start". */ + page?: { size: number | string; start: number | string } | string; + [key: string]: unknown; +} + +/** Split a comma-joined list outside brackets, parentheses and quotes: "Name,Owners[Name='a,b'].Name" is two entries. */ +function splitList(text: string): string[] { + const parts: string[] = []; + let depth = 0, quote: string | null = null, current = ""; + for (const ch of text) { + if (quote) { current += ch; if (ch === quote) quote = null; continue; } + if (ch === "'" || ch === '"') quote = ch; + else if (ch === "[" || ch === "(") depth += 1; + else if (ch === "]" || ch === ")") depth -= 1; + else if (ch === "," && depth === 0) { parts.push(current); current = ""; continue; } + current += ch; + } + parts.push(current); + return parts.map((p) => p.trim()).filter(Boolean); +} +const listOf = (value: string | string[]): string[] => (typeof value === "string" ? splitList(value) : value); + +/** + * A query written with rest-1's spellings, as the QueryBody every read + * takes: `sel` becomes `select`, a textual `where` becomes `filter`, + * comma-joined `select` / `sort` / `findin` become lists, and a + * "size,start" page becomes `{ size, start }`; sub-selects are normalised + * the same way, and every other key is kept as written. A query that + * already is a QueryBody comes back equal. Nothing is sent. Saying one + * thing twice (`sel` and `select`, a textual `where` and `filter`) is a + * UsageError rather than a guess at which was meant, and so is `deleted`: + * a QueryBody cannot ask for deleted assets (`client.data.list` can). + */ +export function normalizeQuery(query: LooseQuery): QueryBody { + if (!query || typeof query !== "object" || typeof query.from !== "string" || !query.from) throw new UsageError("a query needs a `from`: an asset type token or an OID token"); + const { sel, select, where, filter, sort, findin, page, ...rest } = query; + if (sel !== undefined && select !== undefined) throw new UsageError(`query of ${query.from} has both \`sel\` and \`select\`: write one (\`select\`)`); + if ("deleted" in rest) throw new UsageError(`query of ${query.from} asks for \`deleted\`: only rest-1 reads deleted assets — use client.data.list(type, { deleted: true, … })`); + const out: Record = { ...rest }; + const chosen = select ?? sel; + if (chosen !== undefined) out.select = listOf(chosen as string | string[]).map((entry: string | LooseQuery) => (typeof entry === "string" ? entry : normalizeQuery(entry))); + const textualWhere = typeof where === "string" || Array.isArray(where); + if (textualWhere && filter !== undefined) throw new UsageError(`query of ${query.from} has both a textual \`where\` and \`filter\`: write one (\`filter\`)`); + if (textualWhere) out.filter = typeof where === "string" ? [where] : where; + else if (where !== undefined) out.where = where; + if (filter !== undefined) out.filter = typeof filter === "string" ? [filter] : filter; + if (sort !== undefined) out.sort = listOf(sort); + if (findin !== undefined) out.findin = listOf(findin); + if (page !== undefined) { + const [size, start] = typeof page === "string" ? page.split(",").map((n) => Number(n.trim())) : [Number(page.size), Number(page.start)]; + if (!Number.isInteger(size) || !Number.isInteger(start) || size! < 0 || start! < 0) throw new UsageError(`query of ${query.from}: page ${JSON.stringify(page)} is not { size, start } or "size,start"`); + out.page = { size, start }; + } + for (const flag of ["needTotal"]) if (out[flag] === "true" || out[flag] === "false") out[flag] = out[flag] === "true"; + return out as unknown as QueryBody; +} diff --git a/test/integration/attachments.test.ts b/test/integration/attachments.test.ts index ec828ca..c630c11 100644 --- a/test/integration/attachments.test.ts +++ b/test/integration/attachments.test.ts @@ -32,23 +32,51 @@ describeInstance("attachments (live)", () => { it("a small file inline and a large one in two steps both store their bytes; list sees both, metadata only", async () => { const small = await client.attachments.add(story, text("hello attachment\n"), { filename: "sdk-integration small.txt", contentType: "text/plain" }); const large = await client.attachments.add(story, new Blob([text("two-step bytes\n")], { type: "text/plain" }), { filename: "sdk-integration large.txt", inlineLimit: 0, description: "two-step" }); - made.push(small.oid, large.oid); + made.push(small._oid, large._oid); expect(decode((await client.attachments.get(small.id)).bytes)).toBe("hello attachment\n"); - const got = await client.attachments.get(large.oid); + const got = await client.attachments.get(large._oid); expect(decode(got.bytes)).toBe("two-step bytes\n"); - expect(got).toMatchObject({ filename: "sdk-integration large.txt", contentType: "text/plain", description: "two-step" }); + expect(got).toMatchObject({ Filename: "sdk-integration large.txt", ContentType: "text/plain", Description: "two-step" }); + expect(typeof got["CreatedBy.Name"]).toBe("string"); const listed = await client.attachments.list(story); - expect(listed.map((a) => a.oid).sort()).toEqual([small.oid, large.oid].sort()); + expect(listed.map((a) => a._oid).sort()).toEqual([small._oid, large._oid].sort()); // The type the server served the bytes with, and a page with its total. - expect((await client.attachments.get(small.id)).contentType).toMatch(/^text\/plain/); + expect((await client.attachments.get(small.id)).servedContentType).toMatch(/^text\/plain/); const first = await client.attachments.page(story, { page: { size: 1, start: 0 } }); expect(first).toMatchObject({ total: 2, more: true }); expect(first.attachments).toHaveLength(1); }); + it("get with inline reads metadata and bytes in one request; list with a select brings the extra values, translated", async () => { + const a = await client.attachments.add(story, text("inline read\n"), { filename: "sdk-integration inline.txt", contentType: "text/plain", description: "one request" }); + made.push(a._oid); + const calls: string[] = []; + const counting = new AgilityApiClient({ baseUrl: instance!.url }, { transport: { request: (o) => { calls.push(o.path); return t.request(o); } }, schema: client.schema }); + const got = await counting.attachments.get(a._oid, { inline: true }); + expect(calls).toEqual(["/query.v1"]); + expect(decode(got.bytes)).toBe("inline read\n"); + expect(got).toMatchObject({ _oid: a._oid, id: a.id, Filename: "sdk-integration inline.txt", ContentType: "text/plain", servedContentType: null, Description: "one request" }); + expect(got).not.toHaveProperty("Content"); + // The same bytes the two-request read serves. + expect(decode((await client.attachments.get(a._oid)).bytes)).toBe("inline read\n"); + // A two-step attachment whose upload never happened reads as zero bytes; one that does not exist is NOT_FOUND. + await expect(client.attachments.get("Attachment:1", { inline: true })).rejects.toMatchObject({ code: "NOT_FOUND" }); + + const listed = await client.attachments.list(story, { select: ["Asset", "Asset.Name", "Category", "Days", "IsDeleted"] }); + const mine = listed.find((x) => x._oid === a._oid)!; + expect(mine.Filename).toBe("sdk-integration inline.txt"); + expect(mine.Asset).toMatchObject({ _oid: story }); + expect(mine).toMatchObject({ Category: null, IsDeleted: false }); + expect(typeof mine.Days).toBe("number"); + expect(String(mine["Asset.Name"])).toMatch(/^sdk-integration attachments/); + const paged = await client.attachments.page(story, { select: ["Days"], page: { size: 1, start: 0 } }); + expect(typeof paged.attachments[0]!.Days).toBe("number"); + expect(paged.total).toBeGreaterThanOrEqual(1); + }); + it("put replaces the bytes; remove deletes the attachment; a missing one is NOT_FOUND", async () => { const a = await client.attachments.add(story, text("before\n"), { filename: "sdk-integration replace.txt", contentType: "text/plain" }); - made.push(a.oid); + made.push(a._oid); await client.attachments.put(a.id, text("after\n"), "text/plain"); expect(decode((await client.attachments.get(a.id)).bytes)).toBe("after\n"); await client.attachments.remove(a.id); diff --git a/test/integration/client.test.ts b/test/integration/client.test.ts index 8e2edba..81a90ea 100644 --- a/test/integration/client.test.ts +++ b/test/integration/client.test.ts @@ -1,6 +1,7 @@ import { expect, it } from "vitest"; import { AgilityApiClient } from "../../src/client"; import type { Story } from "../../src/types/assets/Story"; +import { normalizeQuery } from "../../src/wire/rest1"; import { describeInstance, fixtureName, instance } from "./instance"; /** @@ -29,6 +30,14 @@ describeInstance("client reads (live)", () => { expect(new Set(all.map((r) => r._oid)).size).toBe(all.length); }); + it("a query written with rest-1's spellings, normalised, reads the same rows as the QueryBody it stands for (and a where that matches nothing reads none)", async () => { + const me = await client.me(); + const loose = normalizeQuery({ from: "Member", sel: "Name,Username", where: `ID='${me._oid}';IsSelf='true'`, sort: "Name", page: "5,0" }); + expect(loose).toEqual({ from: "Member", select: ["Name", "Username"], filter: [`ID='${me._oid}';IsSelf='true'`], sort: ["Name"], page: { size: 5, start: 0 } }); + expect(await client.query(loose)).toEqual([{ _oid: me._oid, Name: me.Name, Username: me.Username }]); + expect(await client.query(normalizeQuery({ from: "Member", sel: "Name", where: `ID='${me._oid}';IsSelf='false'`, page: "5,0" }))).toEqual([]); + }); + it("the asset page URL answers for a real asset (assetdetail.v1 redirects to the type's detail page)", async () => { const me = await client.me(); const response = await fetch(client.urls.asset(me._oid), { headers: { authorization: `Bearer ${process.env.V1_ACCESS_TOKEN ?? ""}` }, redirect: "manual" }); diff --git a/test/unit/attachment.test.ts b/test/unit/attachment.test.ts index 71d3698..fa57c6d 100644 --- a/test/unit/attachment.test.ts +++ b/test/unit/attachment.test.ts @@ -4,7 +4,8 @@ import { AgilityApiClient } from "../../src/client"; import { ApiError } from "../../src/core/errors"; import { createFetchTransport } from "../../src/core/fetchTransport"; import type { RequestOptions, Transport } from "../../src/core/transport"; -import { AttachmentUploadError, add, list, page } from "../../src/services/attachments"; +import { AttachmentUploadError, add, get, list, page } from "../../src/services/attachments"; +import { Schema } from "../../src/services/schema"; import { queryPage } from "../../src/wire/assetApi"; import { fromBase64, getBytes, getFile, normalizeEmbeddedImageUrls, numericId, toBase64, uploadEmbeddedImage } from "../../src/wire/attachment"; @@ -70,7 +71,7 @@ describe("attachments service", () => { const created = await add(t, "Story:1", new TextEncoder().encode("hello attachment\n"), { filename: "a.txt", contentType: "text/plain" }); expect(t.calls).toHaveLength(1); expect(t.calls[0]!.body).toEqual([{ AssetType: "Attachment", Asset: "Story:1", Name: "a.txt", Filename: "a.txt", ContentType: "text/plain", Content: "aGVsbG8gYXR0YWNobWVudAo=" }]); - expect(created).toMatchObject({ oid: "Attachment:77", id: "77", filename: "a.txt" }); + expect(created).toEqual({ _oid: "Attachment:77", id: "77", Name: "a.txt", Filename: "a.txt", ContentType: "text/plain", Description: null, CreateDate: null, "CreatedBy.Name": null }); }); it("a large file goes in two steps: create with empty Content, then POST the bytes", async () => { @@ -86,7 +87,7 @@ describe("attachments service", () => { const t = fake(envelope({ assetsCreated: { oidTokens: ["Attachment:79"], count: 1 } }), new ApiError("too big", 413)); const err = (await add(t, "Story:1", new Uint8Array(20), { filename: "c.bin", inlineLimit: 10 }).catch((e: unknown) => e)) as AttachmentUploadError; expect(err).toBeInstanceOf(AttachmentUploadError); - expect(err.attachment.oid).toBe("Attachment:79"); + expect(err.attachment._oid).toBe("Attachment:79"); expect(err.message).toMatch(/Attachment:79 was created .* no content.*maximum request length/); }); @@ -96,7 +97,43 @@ describe("attachments service", () => { const q = (t.calls[0]!.body as Record[])[0]!; expect(q).toMatchObject({ from: "Attachment", filter: ["Asset=$asset"], with: { $asset: "Story:1" }, sort: ["-CreateDate"], page: { size: 50, start: 0 } }); expect(q.select).not.toContain("Content"); - expect(rows).toEqual([{ oid: "Attachment:5", id: "5", name: "n", filename: "f.png", contentType: "image/png", description: null, createDate: "2026-11-07T10:00:00", createdBy: "Dana" }]); + expect(rows).toEqual([{ _oid: "Attachment:5", id: "5", Name: "n", Filename: "f.png", ContentType: "image/png", Description: null, CreateDate: "2026-11-07T10:00:00", "CreatedBy.Name": "Dana" }]); + }); + + it("list and page take more to select: the extra keys come back on the row as selected, translated when a schema is given, beside the metadata", async () => { + // Attachment and AttachmentCategory as far as this select goes; the row as query.v1 and api/asset spell it (the API-testing instance, 2026-11-26). + const text = (type: string, name: string) => ({ _type: "AttributeDefinition", Name: name, Token: `${type}.${name}`, DisplayName: "", AttributeType: "Text", IsReadOnly: false, IsRequired: false, IsMultivalue: false, IsCanned: false, IsCustom: false }); + const schema = Schema.fromMetamodel({ Version: "x", AssetTypes: { + Attachment: { _type: "AssetType", Name: "Attachment", Token: "Attachment", DisplayName: "", Abstract: false, Attributes: { + "Attachment.Name": text("Attachment", "Name"), + "Attachment.Category": { ...text("Attachment", "Category"), AttributeType: "Relation", RelatedAsset: "AttachmentCategory" }, + "Attachment.Days": { ...text("Attachment", "Days"), AttributeType: "Numeric" } } }, + AttachmentCategory: { _type: "AssetType", Name: "AttachmentCategory", Token: "AttachmentCategory", DisplayName: "", Abstract: false, Attributes: { "AttachmentCategory.Name": text("AttachmentCategory", "Name") } } + } } as never); + const row = { _oid: "Attachment:5", Name: "n", Filename: "f.png", ContentType: "image/png", Description: null, CreateDate: "2026-11-07T10:00:00", "CreatedBy.Name": "Dana", Category: { _oid: "NULL" }, "Category.Name": null, Days: "19" }; + const t = fake(envelope({ queryResult: { results: [[row]], resultMetaData: [], count: 1 } }), envelope({ queryResult: { results: [[row]], resultMetaData: [{ total: 1 }], count: 1 } }), envelope({ queryResult: { results: [[row]], resultMetaData: [], count: 1 } })); + const [listed] = await list(t, "Story:1", { select: ["Category", "Category.Name", "Days", "Name"], schema }); + expect((t.calls[0]!.body as { select: string[] }[])[0]!.select).toEqual(["Name", "Filename", "ContentType", "Description", "CreateDate", "CreatedBy.Name", "Category", "Category.Name", "Days"]); + expect(listed).toEqual({ _oid: "Attachment:5", id: "5", Name: "n", Filename: "f.png", ContentType: "image/png", Description: null, CreateDate: "2026-11-07T10:00:00", "CreatedBy.Name": "Dana", Category: null, "Category.Name": null, Days: 19 }); + const paged = await page(t, "Story:1", { select: ["Days"], schema }); + expect(paged).toMatchObject({ total: 1, more: false, attachments: [{ _oid: "Attachment:5", id: "5", Days: 19 }] }); + // Without a schema the extra values keep the endpoint's spelling. + expect((await list(t, "Story:1", { select: ["Days"] }))[0]!.Days).toBe("19"); + }); + + it("get with inline reads the row and its Content in one query.v1 request and decodes the bytes; a missing attachment is NOT_FOUND", async () => { + // Content inline as Base64, as query.v1 sends it (the API-testing instance, 2026-11-26). + const t = fake([[{ _oid: "Attachment:145797", Name: "n", Filename: "check.txt", ContentType: "text/plain", Description: null, CreateDate: "2026-11-07T10:00:00", "CreatedBy.Name": "Dana", Content: "aGVsbG8gYXR0YWNobWVudAo=" }]]); + const got = await get(t, "Attachment:145797", { inline: true }); + expect(t.calls).toHaveLength(1); + expect(t.calls[0]).toMatchObject({ method: "POST", path: "/query.v1", idempotent: true }); + expect((t.calls[0]!.body as Record[])[0]).toMatchObject({ from: "Attachment", filter: ["ID=$id"], with: { $id: "Attachment:145797" }, page: { size: 1, start: 0 } }); + expect(new TextDecoder().decode(got.bytes)).toBe("hello attachment\n"); + expect(got).toMatchObject({ _oid: "Attachment:145797", id: "145797", Filename: "check.txt", ContentType: "text/plain", servedContentType: null, "CreatedBy.Name": "Dana" }); + expect(got).not.toHaveProperty("Content"); + await expect(get(fake([[]]), 9, { inline: true })).rejects.toMatchObject({ code: "NOT_FOUND", kind: "notFound" }); + // An attachment created empty reads as zero bytes, not as a failure. + expect((await get(fake([[{ _oid: "Attachment:6", Content: "" }]]), 6, { inline: true })).bytes).toEqual(new Uint8Array(0)); }); it("the client exposes attachments and embedded images, with URLs on its own base", () => { @@ -133,6 +170,6 @@ describe("attachment gaps the CLI consumer found", () => { const last = await queryPage(fake(withTotal([{ _oid: "Story:3" }], 3)), { from: "Story", select: ["Name"], page: { size: 2, start: 2 } }); expect(last).toMatchObject({ total: 3, more: false }); const a = await page(fake(withTotal([{ _oid: "Attachment:5", Name: "n" }], 1)), "Story:1"); - expect(a).toMatchObject({ total: 1, more: false, attachments: [{ oid: "Attachment:5", id: "5" }] }); + expect(a).toMatchObject({ total: 1, more: false, attachments: [{ _oid: "Attachment:5", id: "5", Name: "n", Filename: null }] }); }); }); diff --git a/test/unit/cjs.test.ts b/test/unit/cjs.test.ts index f2b73e1..6cd95ba 100644 --- a/test/unit/cjs.test.ts +++ b/test/unit/cjs.test.ts @@ -23,8 +23,9 @@ beforeAll(async () => { const installed = join(dir, "node_modules", "@versionone", "agility-sdk"); // tsup reads entries as glob patterns, where "\\" is an escape: on Windows an // absolute path (D:\\source\\…) matches nothing. Forward slashes work everywhere. - const entry = join(root, "src", "index.ts").replace(/\\/g, "/"); - await build({ config: false, entry: [entry], format: ["cjs"], outDir: join(installed, "dist"), target: "node18", dts: false, sourcemap: false, silent: true }); + const entry = (...parts: string[]) => join(root, "src", ...parts).replace(/\\/g, "/"); + // The package's own entries and splitting (tsup.config.ts): shared code in chunks, so the three import paths share one copy of every class. + await build({ config: false, entry: { index: entry("index.ts"), wire: entry("wire", "index.ts"), testing: entry("testing", "index.ts") }, format: ["cjs"], splitting: true, outDir: join(installed, "dist"), target: "node22", dts: false, sourcemap: false, silent: true }); copyFileSync(join(root, "package.json"), join(installed, "package.json")); }, 30_000); afterAll(() => { if (dir) rmSync(dir, { recursive: true, force: true }); }); @@ -53,6 +54,15 @@ const fetchImpl = async (url) => { assert.ok(err instanceof sdk.CommandFailureError && err instanceof sdk.ApiError && err instanceof Error); assert.equal(err.failures[0].index, 0); assert.equal(sdk.momentless("Story:1:99"), "Story:1"); + // The other import paths resolve, and share the root's classes: one ApiError, one client. + const wire = require("@versionone/agility-sdk/wire"); + const { FakeAgilityClient } = require("@versionone/agility-sdk/testing"); + assert.equal(wire.assetApi.send, sdk.assetApi.send); + const fake = new FakeAgilityClient().onQuery("Story", [{ _oid: "Story:1", Name: "n" }]); + assert.ok(fake instanceof sdk.AgilityApiClient); + assert.deepEqual(await fake.query({ from: "Story", select: ["Name"], page: { size: 5, start: 0 } }), [{ _oid: "Story:1", Name: "n" }]); + const unscripted = await fake.query({ from: "Epic", page: { size: 1, start: 0 } }).catch((e) => e); + assert.ok(unscripted instanceof sdk.UsageError); process.stdout.write("ok " + seen.length); })().catch((e) => { process.stderr.write(String(e && e.stack || e)); process.exit(1); }); `; @@ -71,5 +81,8 @@ describe("CommonJS consumers", () => { const entry = pkg.exports["."]!; expect(entry.require).toEqual({ types: "./dist/index.d.cts", default: "./dist/index.cjs" }); expect(entry.import).toEqual({ types: "./dist/index.d.ts", default: "./dist/index.js" }); + for (const path of ["wire", "testing"]) { + expect(pkg.exports[`./${path}`]).toEqual({ import: { types: `./dist/${path}.d.ts`, default: `./dist/${path}.js` }, require: { types: `./dist/${path}.d.cts`, default: `./dist/${path}.cjs` } }); + } }); }); diff --git a/test/unit/errors.test.ts b/test/unit/errors.test.ts index 5cf5a09..ea2cdb7 100644 --- a/test/unit/errors.test.ts +++ b/test/unit/errors.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; -import { ApiError, UsageError, WrappedError, kindOf } from "../../src/core/errors"; +import { ApiError, UsageError, WrappedError, apiErrorFromResponse, kindOf } from "../../src/core/errors"; +import { createFetchTransport } from "../../src/core/fetchTransport"; import { AttachmentUploadError } from "../../src/services/attachments"; import { BatchSendError } from "../../src/services/batch"; import { UnguardableError } from "../../src/services/guard"; @@ -52,7 +53,7 @@ describe("error kinds", () => { expect(new WrappedError("x", "X", new Error("plain")).kind).toBe("unknown"); const receipt = { receipt: 1 } as never; expect(new BatchSendError(cause, receipt).kind).toBe("transient"); - expect(new AttachmentUploadError({ oid: "Attachment:1", id: "1", name: null, filename: null, contentType: null, description: null, createDate: null, createdBy: null }, new ApiError("too big", 413, "TOO_LARGE")).kind).toBe("invalid"); + expect(new AttachmentUploadError({ _oid: "Attachment:1", id: "1", Name: null, Filename: null, ContentType: null, Description: null, CreateDate: null, "CreatedBy.Name": null }, new ApiError("too big", 413, "TOO_LARGE")).kind).toBe("invalid"); }); it("a command failure is kind commandFailure, and its violations are parsed", () => { @@ -71,3 +72,33 @@ describe("error kinds", () => { expect(parseViolation("")).toBeNull(); }); }); + +describe("apiErrorFromResponse: a custom Transport's errors match the fetch transport's", () => { + const bodies: [number, unknown, string, string][] = [ + // rest-1 and query.v1: { error, exceptions: [{ message }] }; api/asset's parser: { Exceptions: [...] }; a bare message; text; nothing. + [400, { _type: "Error", error: "Bad Request", exceptions: [{ type: "X", message: "Unknown token" }] }, "Bad Request", "invalid"], + [400, { Exceptions: ["The request body is not valid JSON.", "Second"] }, "The request body is not valid JSON.; Second", "invalid"], + [403, { message: "No permission" }, "No permission", "forbidden"], + [401, " Unauthorized ", "Unauthorized", "auth"], + [503, undefined, "HTTP 503", "transient"], + [404, "", "HTTP 404", "notFound"] + ]; + + it("reads the message from the shapes the endpoints send, keeps the body as details, and the status gives the kind", () => { + for (const [status, data, message, kind] of bodies) { + const error = apiErrorFromResponse(status, data); + expect(error).toBeInstanceOf(ApiError); + expect({ status: error.status, message: error.message, kind: error.kind, details: error.details }).toEqual({ status, message, kind, details: data }); + } + }); + + it("is what the fetch transport itself throws for the same response", async () => { + for (const [status, data] of bodies) { + const body = data === undefined ? null : typeof data === "string" ? data : JSON.stringify(data); + const fetchImpl = async () => new Response(body, { status, headers: typeof data === "object" ? { "content-type": "application/json" } : {} }); + const thrown = (await createFetchTransport({ baseUrl: "https://x", retries: 0, fetchImpl: fetchImpl as typeof fetch }).request({ method: "GET", path: "/x" }).catch((e: unknown) => e)) as ApiError; + const built = apiErrorFromResponse(status, data === undefined ? "" : data); + expect({ status: thrown.status, message: thrown.message, kind: thrown.kind, code: thrown.code }).toEqual({ status: built.status, message: built.message, kind: built.kind, code: built.code }); + } + }); +}); diff --git a/test/unit/guard.test.ts b/test/unit/guard.test.ts index 01a6507..e6f890a 100644 --- a/test/unit/guard.test.ts +++ b/test/unit/guard.test.ts @@ -108,5 +108,9 @@ describe("guard passes: two commands on one asset", () => { expect(sent[1]).toEqual([{ from: "Story", filter: ["ID=$oid", "ChangeDate='2026-11-07T12:00:00.5'"], with: { $oid: "Story:1" }, execute: { op: "Delete", args: {} } }]); // Story:2's Delete never sent expect(r.sent).toHaveLength(3); expect(r.outcome.operated).toEqual(["Story:1", "Story:1"]); + // Two sends: no one request id stands for the batch. One send keeps its own. + expect(r.outcome.requestId).toBeNull(); + const once = await sendPasses(transport, [P("Story:1", { execute: { op: "Reactivate", args: {} } })], { "Story:1": "2026-11-07T11:00:00.1" }); + expect(once.outcome.requestId).toBe("r"); }); }); diff --git a/test/unit/layers.test.ts b/test/unit/layers.test.ts index fab4e11..e2b0e2f 100644 --- a/test/unit/layers.test.ts +++ b/test/unit/layers.test.ts @@ -17,7 +17,9 @@ const ALLOWED: Record = { core: ["core"], types: ["types", "core"], wire: ["wire", "types", "core"], - services: ["services", "wire", "types", "core"] + services: ["services", "wire", "types", "core"], + // The consumer-facing fake stands on the client itself (src/client.ts, the layer "client" here) and everything under it; nothing imports it. + testing: ["testing", "client", "services", "wire", "types", "core"] }; function walk(dir: string): string[] { @@ -46,6 +48,11 @@ describe("layers", () => { expect(violations).toEqual([]); }); + it("nothing in the SDK imports the testing entry: it ships beside the client, never inside it", () => { + const importers = walk(src).filter((f) => layerOf(f) !== "testing" && importedLayers(f).some(({ layer }) => layer === "testing")); + expect(importers.map((f) => relative(src, f))).toEqual([]); + }); + it("envelope types live in the wire module that owns them, never in types", () => { const leaks: string[] = []; for (const file of walk(join(src, "types"))) { diff --git a/test/unit/rest1.test.ts b/test/unit/rest1.test.ts index 086cc9e..c88bafd 100644 --- a/test/unit/rest1.test.ts +++ b/test/unit/rest1.test.ts @@ -1,7 +1,8 @@ import { describe, expect, it, vi } from "vitest"; import type { RequestOptions, Transport } from "../../src/core/transport"; import type { Story } from "../../src/types/assets/Story"; -import { fromAssetDocument, get, history, list, operate, template, toQuery, type AssetDocument, type AssetsDocument } from "../../src/wire/rest1"; +import { UsageError } from "../../src/core/errors"; +import { fromAssetDocument, get, history, list, normalizeQuery, operate, template, toQuery, type AssetDocument, type AssetsDocument } from "../../src/wire/rest1"; function fakeTransport(...answers: unknown[]): Transport & { calls: RequestOptions[] } { const calls: RequestOptions[] = []; @@ -110,3 +111,25 @@ describe("rest-1: operate and template (the two things api/asset cannot answer)" }); }); + +describe("normalizeQuery: a query written with rest-1's spellings", () => { + it("sel becomes select, a textual where becomes filter, comma-joined lists become lists, and a \"size,start\" page becomes { size, start }", () => { + expect(normalizeQuery({ from: "Story", sel: "Name,Owners[Name='a,b'].Name,Status.Name", where: "Scope='Scope:0';AssetState!='Closed'", sort: "-ChangeDate,Name", findin: "Name,Description", find: "logon", page: "20,40", needTotal: "true", asof: "2026-01-01" })) + .toEqual({ from: "Story", select: ["Name", "Owners[Name='a,b'].Name", "Status.Name"], filter: ["Scope='Scope:0';AssetState!='Closed'"], sort: ["-ChangeDate", "Name"], findin: ["Name", "Description"], find: "logon", page: { size: 20, start: 40 }, needTotal: true, asof: "2026-01-01" }); + expect(normalizeQuery({ from: "Story", sel: ["Name", { from: "Children", sel: "Name", where: ["AssetState!='Dead'"] }], where: ["A='1'", "B='2'"], page: { size: "5", start: 0 } })) + .toEqual({ from: "Story", select: ["Name", { from: "Children", select: ["Name"], filter: ["AssetState!='Dead'"] }], filter: ["A='1'", "B='2'"], page: { size: 5, start: 0 } }); + }); + + it("a QueryBody comes back equal: a where object is a query's own where, and keys it does not know are kept", () => { + const q = { from: "Story", select: ["Name"], filter: ["Estimate>$n"], where: { Name: "x" }, with: { $n: 3 }, sort: ["Name"], page: { size: 1, start: 0 }, group: ["Status"] }; + expect(normalizeQuery(q)).toEqual(q); + }); + + it("saying one thing twice, asking for deleted assets, a bad page or no from is a UsageError: nothing is guessed", () => { + expect(() => normalizeQuery({ from: "Story", sel: "Name", select: ["Name"] })).toThrow(/both `sel` and `select`/); + expect(() => normalizeQuery({ from: "Story", where: "A='1'", filter: ["B='2'"] })).toThrow(/both a textual `where` and `filter`/); + expect(() => normalizeQuery({ from: "Story", deleted: true })).toThrow(/client\.data\.list/); + expect(() => normalizeQuery({ from: "Story", page: "ten" })).toThrow(UsageError); + expect(() => normalizeQuery({ sel: "Name" } as never)).toThrow(UsageError); + }); +}); diff --git a/test/unit/testing.test.ts b/test/unit/testing.test.ts new file mode 100644 index 0000000..6dd1f8d --- /dev/null +++ b/test/unit/testing.test.ts @@ -0,0 +1,142 @@ +import { describe, expect, expectTypeOf, it } from "vitest"; +import { AgilityApiClient } from "../../src/client"; +import { ApiError, UsageError, apiErrorFromResponse } from "../../src/core/errors"; +import { FakeAgilityClient } from "../../src/testing"; +import { CommandFailureError } from "../../src/wire/assetApi"; + +/** + * The consumer-facing fake: a real client over a transport that answers + * what a test scripted, in the model's shape. + */ +const stories = [ + { _oid: "Story:1", Name: "Logon", Estimate: 2, IsClosed: false, Status: { _oid: "StoryStatus:5", Name: "Done" }, Owners: [{ _oid: "Member:20" }] }, + { _oid: "Story:2", Name: "Logoff", Estimate: null, IsClosed: true, Status: null, Owners: [] }, + { _oid: "Story:3", Name: "Reset", Estimate: 0.5, IsClosed: false, Status: null, Owners: [] } +]; + +describe("FakeAgilityClient", () => { + it("is an AgilityApiClient, so code under test takes it unchanged, and the client's own checks still run", async () => { + const fake = new FakeAgilityClient(); + expect(fake).toBeInstanceOf(AgilityApiClient); + expectTypeOf(fake).toMatchTypeOf(); + await expect(fake.query({ from: "Story" })).rejects.toThrow(/without a page/); + expect(fake.requests).toEqual([]); + expect(fake.urls.asset("Story:1")).toBe("https://agility.example.com/Fake/assetdetail.v1?oid=Story:1"); + }); + + it("answers a query with the scripted rows exactly as scripted, and records what was asked", async () => { + const fake = new FakeAgilityClient().onQuery("Story", stories); + const rows = await fake.query({ from: "Story", select: ["Name", "Estimate", "IsClosed", "Status", "Owners"], filter: ["Scope=$s"], with: { $s: "Scope:0" }, page: { size: 10, start: 0 } }); + expect(rows).toEqual(stories); + expect(fake.asked).toEqual([{ from: "Story", select: ["Name", "Estimate", "IsClosed", "Status", "Owners"], filter: ["Scope=$s"], with: { $s: "Scope:0" }, page: { size: 10, start: 0 } }]); + expect(fake.requests.map((r) => `${r.method} ${r.path}`)).toEqual(["POST /query.v1"]); + }); + + it("pages a scripted list: pages and all end, queryPage reports the list's length as the total, get answers the row of that OID or null", async () => { + const fake = new FakeAgilityClient().onQuery("Story", stories); + expect((await fake.all({ from: "Story", page: { size: 2, start: 0 } })).map((r) => r._oid)).toEqual(["Story:1", "Story:2", "Story:3"]); + expect(await fake.queryPage({ from: "Story", page: { size: 2, start: 0 } })).toMatchObject({ total: 3, more: true, rows: [{ _oid: "Story:1" }, { _oid: "Story:2" }] }); + expect(await fake.queryPage({ from: "Story", page: { size: 2, start: 2 } })).toMatchObject({ total: 3, more: false }); + expect(await fake.get("Story:2:99", ["Name"])).toMatchObject({ _oid: "Story:2", Name: "Logoff" }); + expect(await fake.get("Story:404", ["Name"])).toBeNull(); + }); + + it("a function answers one page itself; the answer scripted last wins; several queries in one request each get theirs", async () => { + const fake = new FakeAgilityClient() + .onQuery("Story", stories) + .onQuery((q) => q.from === "Story" && !!q.find, (q) => ({ rows: stories.filter((s) => s.Name.includes(q.find!)), total: 40 })) + .onQuery("Member", [{ _oid: "Member:20", Name: "Dana" }]); + expect(await fake.queryPage({ from: "Story", find: "Logo", page: { size: 2, start: 0 } })).toMatchObject({ total: 40, more: true, rows: [{ Name: "Logon" }, { Name: "Logoff" }] }); + const [s, m] = await fake.queries([{ from: "Story", page: { size: 1, start: 0 } }, { from: "Member", page: { size: 1, start: 0 } }]); + expect([s!.length, m![0]]).toEqual([1, { _oid: "Member:20", Name: "Dana" }]); + expect(await fake.me()).toEqual({ _oid: "Member:20", Name: "Dana" }); + }); + + it("a query nothing was scripted for throws a UsageError naming it: an unscripted read never looks like an empty result", async () => { + const error = await new FakeAgilityClient().query({ from: "Epic", page: { size: 1, start: 0 } }).catch((e: unknown) => e); + expect(error).toBeInstanceOf(UsageError); + expect((error as Error).message).toMatch(/no answer scripted for a query of Epic.*onQuery\("Epic"/); + }); + + it("a write needs no script: a create answers a new OID, an update or operation by OID answers that OID, and the batch is recorded as sent", async () => { + const fake = new FakeAgilityClient(); + const outcome = await fake.assets.send([ + { AssetType: "Story", Name: "new", Scope: { _oid: "Scope:0" } }, + { from: "Story:7", update: { Name: "renamed" } }, + { from: "Story:8:123", execute: "QuickClose" } + ]); + expect(outcome).toMatchObject({ created: ["Story:1000"], modified: ["Story:7"], operated: ["Story:8"], failures: [] }); + expect((await fake.assets.send([{ AssetType: "Task", Name: "t" }])).created).toEqual(["Task:1001"]); + // As sent: the Ref is written as its OID token. + expect(fake.sent[0]![0]).toEqual({ AssetType: "Story", Name: "new", Scope: "Scope:0" }); + expect(fake.sent).toHaveLength(2); + }); + + it("onSend scripts an outcome, failures included: returned by default, thrown with throwOnFailure, parsed like the server's", async () => { + const fake = new FakeAgilityClient().onSend({ failures: [{ index: 0, message: "Violation'Required'AttributeDefinition'Scope'Story" }] }); + const outcome = await fake.assets.send([{ AssetType: "Story", Name: "x" }]); + expect(outcome.failures[0]).toMatchObject({ index: 0, violation: { rule: "Required", attribute: "Story.Scope" } }); + await expect(fake.assets.send([{ AssetType: "Story", Name: "x" }], { throwOnFailure: true })).rejects.toBeInstanceOf(CommandFailureError); + fake.onSend((commands) => ({ created: commands.map((_, i) => `Story:${50 + i}`) })); + expect((await fake.assets.send([{ AssetType: "Story", Name: "a" }, { AssetType: "Story", Name: "b" }])).created).toEqual(["Story:50", "Story:51"]); + }); + + it("an Error as an answer is thrown, as the client would throw it", async () => { + const fake = new FakeAgilityClient().onQuery("Story", apiErrorFromResponse(401, { error: "Unauthorized" })).onSend(new ApiError("down", 503)); + await expect(fake.query({ from: "Story", page: { size: 1, start: 0 } })).rejects.toMatchObject({ kind: "auth", status: 401, message: "Unauthorized" }); + await expect(fake.assets.send([{ AssetType: "Story", Name: "x" }])).rejects.toMatchObject({ kind: "transient" }); + }); + + it("onRequest answers any other endpoint by path, in the endpoint's shape, and an unscripted one is a UsageError", async () => { + const fake = new FakeAgilityClient() + .onRequest("/loc-2.v1", { "Plural'Story": "Backlog Items" }) + .onRequest(/^\/attachment\.img\/5$/, () => new Uint8Array([1, 2])); + expect(await fake.localize(["Plural'Story"])).toEqual({ "Plural'Story": "Backlog Items" }); + fake.onQuery("Attachment", [{ _oid: "Attachment:5", Name: "n", Filename: "f.txt", ContentType: "text/plain" }]); + expect((await fake.attachments.get(5)).bytes).toEqual(new Uint8Array([1, 2])); + await expect(fake.data.get("Story:1")).rejects.toThrow(/no answer scripted for GET \/rest-1\.v1\/Data\/Story\/1/); + }); + + it("a batch that creates and reads back through an alias answers the scripted row of that type under the created OID", async () => { + const fake = new FakeAgilityClient().onQuery("Story", [{ _oid: "Story:1", Number: "S-01001", Name: "template" }]); + const outcome = await fake.assets.send([{ "@story": { AssetType: "Story", Name: "new", Scope: "Scope:0" } }, { from: "@story", select: ["Number"], page: { size: 1, start: 0 } }]); + expect(outcome.created).toEqual(["Story:1000"]); + // The scripted row stands in for what the server adds (the Number); what the create sent wins (the Name); a relation is not copied. + expect(outcome.queryResults).toEqual([[{ _oid: "Story:1000", Number: "S-01001", Name: "new" }]]); + await expect(new FakeAgilityClient().assets.send([{ "@e": { AssetType: "Epic", Name: "x" } }, { from: "@e", page: { size: 1, start: 0 } }])).rejects.toThrow(/query of @e \(the Epic the batch creates\).*onQuery\("Epic"/); + }); + + it("resolve finds a number among every scripted row, whatever its type, and reports the rest missing; the test names no number root", async () => { + const fake = new FakeAgilityClient() + .onQuery("Story", [{ _oid: "Story:1", Number: "S-01001", Name: "Logon", AssetState: "Active" }]) + .onQuery("Defect", { rows: [{ _oid: "Defect:9", Number: "D-00009", Name: "Crash", AssetState: "Closed" }] }); + expect(await fake.resolve.numbers(["d-00009", "S-01001", "S-99999"])).toEqual({ + found: [{ number: "D-00009", oid: "Defect:9", type: "Defect", name: "Crash", assetState: "Closed" }, { number: "S-01001", oid: "Story:1", type: "Story", name: "Logon", assetState: "Active" }], + missing: ["S-99999"] + }); + expect(await fake.resolve.ref("S-01001")).toMatchObject({ oid: "Story:1" }); + expect(await new FakeAgilityClient().resolve.ref("S-1")).toBeNull(); + }); + + it("localize answers scripted labels and echoes any other tag, as loc-2 does, over GET and POST alike", async () => { + const fake = new FakeAgilityClient().onLocalize({ Story: "Backlog Item" }); + expect(await fake.localize(["Story", "Plural'Epic"])).toEqual({ Story: "Backlog Item", "Plural'Epic": "Plural'Epic" }); + expect(await fake.localize(["Story", "Defect"], { maxGetLength: 0 })).toEqual({ Story: "Backlog Item", Defect: "Defect" }); + }); + + it("fake.transport serves a client the code under test builds itself: it reads rows as scripted, with no asset type to script", async () => { + const fake = new FakeAgilityClient().onQuery("Member", [{ _oid: "Member:20", Name: "Dana", IsSelf: true }]); + const calls: string[] = []; + const wrapped = new AgilityApiClient({ baseUrl: "https://x" }, { transport: { request: (o) => { calls.push(o.path); return fake.transport.request(o); } } }); + expect(await wrapped.query({ from: "Member", select: ["Name", "IsSelf"], page: { size: 1, start: 0 } })).toEqual([{ _oid: "Member:20", Name: "Dana", IsSelf: true }]); + expect(calls).toEqual(["/meta.v1/Member", "/query.v1"]); + expect(fake.asked).toHaveLength(1); + }); + + it("an aborted signal ends a read as ABORTED, like the fetch transport", async () => { + const controller = new AbortController(); + controller.abort(); + const fake = new FakeAgilityClient().onQuery("Story", stories); + await expect(fake.withSignal(controller.signal).query({ from: "Story", page: { size: 1, start: 0 } })).rejects.toMatchObject({ kind: "aborted" }); + }); +}); diff --git a/test/unit/typedQuery.test.ts b/test/unit/typedQuery.test.ts index b493bd1..e35ec5b 100644 --- a/test/unit/typedQuery.test.ts +++ b/test/unit/typedQuery.test.ts @@ -84,3 +84,30 @@ describe("typed queries", () => { expect(explicit.length + loose.length + typed.length + custom.length).toBeGreaterThan(0); }); }); + +describe("typed attachment listing", () => { + it("an attachment is a row under meta.v1's names; a select adds its keys to the row, typed by what was selected", async () => { + const plain = await client.attachments.list("Story:1"); + expectTypeOf(plain[0]!).toEqualTypeOf(); + expectTypeOf(plain[0]!.Filename).toEqualTypeOf(); + const more = await client.attachments.list("Story:1", { select: ["Category", "Days", "Asset.Number"] }); + expectTypeOf(more[0]!.Name).toEqualTypeOf(); + expectTypeOf(more[0]!.Days).toEqualTypeOf(); + expectTypeOf(more[0]!["Asset.Number"]).toBeUnknown(); + // @ts-expect-error IsDeleted was not selected + void more[0]!.IsDeleted; + // The row type is closed: a stale camelCase name, a misspelling and an unselected custom attribute are compile errors. + // @ts-expect-error the attribute is Filename + void plain[0]!.filename; + // @ts-expect-error the attribute is Filename + void plain[0]!.FileName; + // @ts-expect-error not selected + void plain[0]!.Custom_Anything; + const file = await client.attachments.get(5, { inline: true }).catch(() => null); + // @ts-expect-error get answers ContentType (recorded) and servedContentType + void file?.contentType; + expectTypeOf["servedContentType"]>().toEqualTypeOf(); + const paged = await client.attachments.page("Story:1", { select: ["Days"], page: { size: 1, start: 0 } }); + expectTypeOf(paged.attachments[0]!.Days).toEqualTypeOf(); + }); +}); diff --git a/tsup.config.ts b/tsup.config.ts index 23d2913..c2b9b69 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -1,8 +1,13 @@ import { defineConfig } from "tsup"; export default defineConfig({ - entry: ["src/index.ts"], + // One entry per public import path: the root, `/wire` (the endpoints' own + // shapes) and `/testing` (FakeAgilityClient). Code they share is split + // into chunks in both formats, so a class is the same class whichever + // path it was imported through (`instanceof ApiError` holds across them). + entry: { index: "src/index.ts", wire: "src/wire/index.ts", testing: "src/testing/index.ts" }, format: ["esm", "cjs"], + splitting: true, dts: true, sourcemap: true, clean: true,