From 1d47cde41c59019285653195e086d10a880aa8a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:04:38 +0000 Subject: [PATCH 01/17] alpha.8 (1 of 3): writes on the client, wire modules off the root, the deprecated aliases gone The removals, moves and renames of the last breaking batch; no behaviour of the server is assumed that was not already tested. - client.assets.send / preview / sendGuarded become client.send / preview / sendGuarded; client.assets is gone. - The root no longer exports the wire modules or the endpoints' envelope types; they are at @versionone/agility-sdk/wire. What a caller writes and reads moves into the model first (src/types/command.ts: QueryBody, Query, Command, Outcome, CommandFailureDetail, Violation), so nobody needs /wire to type a query. The layers test now matches envelope field names as whole words (Outcome.queryResults is not queryResult). - Removed, deprecated since alpha.3: client.queryV1, client.assets.query and queries, attachments.url, embeddedImages.url, rest-1 sel / where, and the bare Transport as the constructor's second argument. - A read takes a Query: a QueryBody whose page is required by the type. The run-time check stays for callers the types do not reach and now runs before the schema load, so a usage error really is "nothing was sent". needTotal leaves QueryBody; queryPage sets it. - ClientOptions keeps `types` (a TypeCache) and loses metamodel and schema. FakeAgilityClient therefore runs on the 404 it answers for every type, and leaves those loads out of `requests`. - code "CommandFailure" becomes "COMMAND_FAILURE", like every other code. - The Ref type's doc no longer claims a dotted path lands on the Ref. Version 1.0.0-alpha.8; the changelog has a migration line per change. The guard's move to Moment and the remaining approved items follow. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 58 ++++++++++ README.md | 8 +- package-lock.json | 4 +- package.json | 2 +- specs/000-layers.md | 6 +- src/client.ts | 146 +++++++++++--------------- src/core/errors.ts | 2 +- src/index.ts | 24 ++--- src/testing/index.ts | 16 +-- src/types/asset.ts | 7 +- src/types/command.ts | 136 ++++++++++++++++++++++++ src/wire/assetApi.ts | 128 ++-------------------- src/wire/index.ts | 2 +- src/wire/rest1.ts | 15 ++- test/integration/attachments.test.ts | 2 +- test/integration/client.test.ts | 6 +- test/integration/customFields.test.ts | 2 +- test/integration/queryV1.test.ts | 2 +- test/integration/rest1.test.ts | 12 +-- test/integration/schema.test.ts | 2 +- test/unit/assetApi.test.ts | 2 +- test/unit/attachment.test.ts | 4 +- test/unit/cjs.test.ts | 10 +- test/unit/client.test.ts | 28 +++-- test/unit/errors.test.ts | 2 +- test/unit/fields.test.ts | 2 +- test/unit/layers.test.ts | 3 +- test/unit/queryV1.test.ts | 2 +- test/unit/rest1.test.ts | 8 +- test/unit/testing.test.ts | 19 ++-- test/unit/translate.test.ts | 8 +- test/unit/transportAuth.test.ts | 4 +- test/unit/typeCache.test.ts | 6 +- test/unit/typedQuery.test.ts | 10 +- 34 files changed, 379 insertions(+), 309 deletions(-) create mode 100644 src/types/command.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index abc2007..3236646 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,63 @@ # Changelog +## 1.0.0-alpha.8 — the last breaking batch before 1.0 + +Each entry has the line a consumer follows to migrate. + +### Breaking + +- **Writes are on the client itself**: `client.assets.send` → + `client.send`; `client.assets.preview` → `client.preview`; + `client.assets.sendGuarded` → `client.sendGuarded`. `client.assets` is + gone. Migration: delete `.assets`. +- **The wire modules are at `@versionone/agility-sdk/wire` only.** The + root no longer exports `assetApi`, `queryV1`, `rest1`, `meta`, `loc2`, + `attachment`, `fields`, `select`, nor the endpoints' envelope types + (`AssetApiResponse`, `AssetDocument`, `AssetsDocument`, `RowContext`, + `ReadOptions`). Migration: `import { assetApi } from + "@versionone/agility-sdk/wire"`. What a caller writes and reads stays + on the root: `QueryBody`, `Command`, `CreateBody`, `UpdateBody`, + `ExecuteBody`, `Outcome`, `CommandFailureDetail`, `Violation`, + `CommandFailureError`, `parseViolation`, `normalizeQuery`. +- **The aliases deprecated in alpha.3 are removed**: + - `client.queryV1.query` / `.queries` → `client.query` / + `client.queries` + - `client.assets.query` / `.queries` → `client.query` / + `client.queries`, or `client.queryPage` for a total + - `client.attachments.url`, `client.embeddedImages.url` → + `client.urls.attachment`, `client.urls.embeddedImage` + - rest-1 `sel` / `where` on `client.data.list` and `history` → + `select` / `filter` + - `new AgilityApiClient(config, transport)` → `new + AgilityApiClient(config, { transport })` +- **A read's `page` is required by the type.** `client.query`, + `queries`, `queryPage`, `pages` and `all` take a `Query` (a `QueryBody` + with its page), so an unpaged read no longer compiles; it threw a + `UsageError` at run time before, and still does for a caller the types + do not reach — now before any request, a schema load included. + Migration: add `page: { size, start }`; a variable typed `QueryBody` + that is passed to a read becomes `Query`. A sub-select stays a + `QueryBody`. +- **`needTotal` is no longer a key of `QueryBody`.** `client.queryPage` + is how a total is asked for. Migration: remove the key; call + `queryPage`. +- **One way to hand the client its types**: `ClientOptions.metamodel` and + `ClientOptions.schema` are gone; `types` (a `TypeCache`) stays. + Migration: `{ metamodel }` → `{ types: TypeCache.fromMetamodel(metamodel) + }`; `{ schema }` → `{ types: schema.cache }`. +- **Error codes are spelled one way**: `code: "CommandFailure"` → + `"COMMAND_FAILURE"`. `kind` (`"commandFailure"`) is unchanged and is + what to branch on. Migration: a comparison with the old code string + changes; one on `kind` or `instanceof CommandFailureError` does not. + +### Changed + +- `FakeAgilityClient.requests` leaves out the client's own unscripted + meta.v1 type loads: it lists what the code under test asked for. +- The `Ref` type's doc said a dotted path lands on the Ref; it does not. + A sub-select puts attributes on a Ref; a path selected by name arrives + under its own key. + ## 1.0.0-alpha.7 — what a browser app consumer asked for One breaking change, to attachments; everything else is additive. Each diff --git a/README.md b/README.md index eabe9cb..934d021 100644 --- a/README.md +++ b/README.md @@ -42,9 +42,9 @@ npm test 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 + - `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 (by the type: an unpaged read does not compile); 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 (`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` + - `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. `preview` - the projection. `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, 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 @@ -55,10 +55,10 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `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) - `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 })`) +- `TypeCache` - one instance's loaded type definitions, shared by many clients (`new AgilityApiClient(config, { types })`); `TypeCache.fromMetamodel(metamodel)` seeds one so nothing is loaded - `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 - 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.) +- `@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. ## Testing code that uses the SDK diff --git a/package-lock.json b/package-lock.json index 8e5bcd3..edfd662 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.7", + "version": "1.0.0-alpha.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.7", + "version": "1.0.0-alpha.8", "license": "MIT", "devDependencies": { "@types/node": "^22.13.10", diff --git a/package.json b/package.json index b38ced8..7fc5ba9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.7", + "version": "1.0.0-alpha.8", "description": "TypeScript SDK for the Digital.ai Agility (VersionOne) API: queries, batches, schema-translated rows, guarded writes, attachments", "keywords": [ "agility", diff --git a/specs/000-layers.md b/specs/000-layers.md index 30a4e90..470ead9 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -21,7 +21,9 @@ client, and `src/testing` (§5a) stands on the client. Nothing imports (`src/types/assets/`, one file per asset type, the `extends` chain from the metamodel's `Base` chain) and the hand-written roots in `src/types/asset.ts` (`Asset`, `Ref`, `Oid`, `DateString`, - `AssetStateValue`, `CustomAttributes`). + `AssetStateValue`, `CustomAttributes`), and the vocabulary of a batch in + `src/types/command.ts`: what a caller writes (`QueryBody`, `Command`) + and what a batch did in the model's terms (`Outcome`). - **`wire`** is one module per endpoint (`assetApi`, `rest1`, `queryV1`, `meta`, `loc2`, `attachment`, `fields`, …). Each knows exactly two things: the envelope its endpoint takes and returns, typed as the server @@ -199,7 +201,7 @@ command, so a failed command is reported inside the envelope it there by default and throws a `CommandFailureError` (an `ApiError` carrying every failure by index and the whole translated response, so what did commit is still known) when asked with `throwOnFailure`. Reads — -`assetApi.query`/`queries`, and the client's `assets.query`/`queries` — +`assetApi.query`/`queries`, and the client's `query`/`queries`/`queryPage` — always throw: a query the server rejected must not come back as `[]`. The server drops a failed query's slot from `queryResult.results` (later results shift up); `send` restores it as `null` by `sourceCommandIndex`, so diff --git a/src/client.ts b/src/client.ts index 2dd0152..62796bc 100644 --- a/src/client.ts +++ b/src/client.ts @@ -11,7 +11,6 @@ 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"; import { isOidToken, momentless } from "./types/oid"; import { isAssetNumber } from "./services/resolve"; @@ -26,20 +25,14 @@ import * as rest1 from "./wire/rest1"; export interface ClientOptions { /** Bring your own transport (a fake in tests, an instrumented one in an app). */ transport?: Transport; - /** - * Seed the schema so no type is fetched: a metamodel document as - * meta.getMetamodel returns it, or the committed metamodel.json run - * through meta.toMetamodel. Without it, types are loaded from meta.v1 as - * queries first touch them. - */ - metamodel?: Metamodel; - /** Share an existing schema (and its cache) instead of starting a new one. */ - schema?: Schema; /** * Share loaded type definitions with other clients of the same instance, * whatever their credentials: this client's schema keeps its types in * `types` and loads anything missing through this client's transport. * A server that builds a client per user keeps one TypeCache per instance. + * To load nothing at all, seed one from a metamodel document: + * `TypeCache.fromMetamodel(metamodel)`. Without it, types are loaded from + * meta.v1 as queries first touch them. */ types?: TypeCache; } @@ -72,6 +65,11 @@ export interface PagesOptions { export type Me = Pick; const DEFAULT_LIMIT = 1000; + +/** Every read is bounded: the type says so, and for a caller the type did not reach this says so before any request (not even a schema load) is sent. */ +function bounded(qs: readonly assetApi.QueryBody[]): void { + for (const q of qs) if (!q.page) throw new UsageError(`query of ${q.from} without a page: every read must be bounded`); +} const ME_SELECT = ["Name", "Username", "Nickname", "Email"]; /** @@ -87,17 +85,15 @@ const ME_SELECT = ["Name", "Username", "Nickname", "Email"]; * nowhere to put a total; api/asset reports one (`needTotal`) beside the * rows, which is why `queryPage` goes there and `query` does not. rest-1 * sits behind `data` for what neither does: deleted assets, history, a - * new asset's template, an operation's result. Writes: `assets.send`, - * `assets.sendGuarded`, `batch.run`, `copy`. Services: `resolve`, + * new asset's template, an operation's result. Writes: `send`, + * `sendGuarded`, `batch.run`, `copy`. Services: `resolve`, * `fields`, `attachments`, `embeddedImages`, `schema`, `localize`, `urls`. */ export class AgilityApiClient { readonly transport: Transport; readonly schema: Schema; - constructor(config: ClientConfig, options: ClientOptions | Transport = {}) { - // A bare Transport as the second argument is the older spelling; keep it working. - const opts: ClientOptions = "request" in options ? { transport: options } : options; + constructor(config: ClientConfig, opts: ClientOptions = {}) { this.transport = opts.transport ?? createFetchTransport({ baseUrl: config.baseUrl, authorization: config.authorization, @@ -110,7 +106,7 @@ export class AgilityApiClient { unauthorizedStatuses: config.unauthorizedStatuses }); this.config = config; - this.schema = opts.schema ?? new Schema(this.transport, opts.metamodel, opts.types); + this.schema = new Schema(this.transport, undefined, opts.types); } private readonly config: ClientConfig; @@ -118,13 +114,13 @@ export class AgilityApiClient { /** * The same client, with every request it sends tied to `signal`: abort it * (on navigation, say) and in-flight requests end with an ApiError coded - * ABORTED. The schema and its cache are shared; a type load that other + * ABORTED. The loaded types are shared; a type load that other * callers are waiting on is not cancelled. */ withSignal(signal: AbortSignal): AgilityApiClient { const base = this.transport; const transport: Transport = { request: (options) => base.request({ ...options, signal: options.signal ?? signal }) }; - return new AgilityApiClient(this.config, { transport, schema: this.schema }); + return new AgilityApiClient(this.config, { transport, types: this.schema.cache }); } // ---- reads ------------------------------------------------------------------ @@ -138,17 +134,19 @@ export class AgilityApiClient { * sentences, `details` each exception's type and message), never an * empty result. */ - query>(q: Q & assetApi.QueryBody): Promise[]>; - query(q: assetApi.QueryBody): Promise; - async query(q: assetApi.QueryBody): Promise { + query>(q: Q & assetApi.Query): Promise[]>; + query(q: assetApi.Query): Promise; + async query(q: assetApi.Query): Promise { + bounded([q]); await this.schema.ensureFor([q]); return queryV1.query(this.transport, q, { lookup: this.schema }); } /** Several queries in one request; one array of rows per query, in order. */ - queries(qs: Qs): Promise>; - queries(qs: assetApi.QueryBody[]): Promise; - async queries(qs: readonly assetApi.QueryBody[]): Promise { + queries(qs: Qs): Promise>; + queries(qs: assetApi.Query[]): Promise; + async queries(qs: readonly assetApi.Query[]): Promise { + bounded(qs); await this.schema.ensureFor(qs); return queryV1.queries(this.transport, [...qs], { lookup: this.schema }); } @@ -170,9 +168,10 @@ export class AgilityApiClient { * asked (query.v1 does not), so this read goes there. `total` is null * when the server did not say; `more` is then whether the page was full. */ - queryPage>(q: Q & assetApi.QueryBody): Promise>>; - queryPage(q: assetApi.QueryBody): Promise>; - async queryPage(q: assetApi.QueryBody): Promise { + queryPage>(q: Q & assetApi.Query): Promise>>; + queryPage(q: assetApi.Query): Promise>; + async queryPage(q: assetApi.Query): Promise { + bounded([q]); await this.schema.ensureFor([q]); return assetApi.queryPage(this.transport, q, { lookup: this.schema }); } @@ -184,10 +183,10 @@ export class AgilityApiClient { * Each page is a plain read on query.v1, so a long walk survives a * transient failure like any GET. */ - pages>(q: Q & assetApi.QueryBody, options?: PagesOptions): AsyncGenerator[], void, undefined>; - pages(q: assetApi.QueryBody, options?: PagesOptions): AsyncGenerator; - async *pages(q: assetApi.QueryBody, options: PagesOptions = {}): AsyncGenerator { - if (!q.page) throw new UsageError(`query of ${q.from} without a page: every read must be bounded`); + pages>(q: Q & assetApi.Query, options?: PagesOptions): AsyncGenerator[], void, undefined>; + pages(q: assetApi.Query, options?: PagesOptions): AsyncGenerator; + async *pages(q: assetApi.Query, options: PagesOptions = {}): AsyncGenerator { + bounded([q]); const limit = options.limit ?? DEFAULT_LIMIT; const size = q.page.size; let start = q.page.start, read = 0; @@ -202,9 +201,9 @@ export class AgilityApiClient { } /** Every row of the query up to `limit` (default 1000), read page by page. */ - all>(q: Q & assetApi.QueryBody, options?: PagesOptions): Promise[]>; - all(q: assetApi.QueryBody, options?: PagesOptions): Promise; - async all(q: assetApi.QueryBody, options: PagesOptions = {}): Promise { + all>(q: Q & assetApi.Query, options?: PagesOptions): Promise[]>; + all(q: assetApi.Query, options?: PagesOptions): Promise; + async all(q: assetApi.Query, options: PagesOptions = {}): Promise { const out: Asset[] = []; for await (const page of this.pages(q, options)) out.push(...page); return out; @@ -281,51 +280,38 @@ export class AgilityApiClient { visibleByAsset: (oid: Oid) => fields.visibleFieldsByAsset(this.transport, oid) }; - /** @deprecated since 1.0.0-alpha.3: use `client.query` / `client.queries` (the same endpoint, query.v1; only the name moved). Removed in 1.0.0. */ - readonly queryV1 = { - query: (q: assetApi.QueryBody) => this.query(q), - queries: (qs: assetApi.QueryBody[]) => this.queries(qs) - }; - // ---- writes ----------------------------------------------------------------------- - /** api/asset: batches, answered in the model's terms. */ - readonly assets = { - /** - * Send a batch. The Outcome says what it did — created, modified and - * operated OIDs, failures by index (each with its parsed violation), - * query rows per query command — and never the envelope. api/asset - * commits per command and answers 200 either way, so a failed command - * is in `failures`, or thrown as a CommandFailureError with - * `throwOnFailure` (the error carries the same Outcome). - */ - send: async (commands: assetApi.Command[], options?: Omit): Promise> => { - await this.schema.ensureFor(commands); - return assetApi.outcomeOf(await assetApi.send(this.transport, commands, { ...options, lookup: this.schema })); - }, - /** The server's projection of a batch: one command per asset it would touch, nothing applied. */ - preview: (commands: assetApi.Command[]) => assetApi.preview(this.transport, commands), - /** - * Send as a compare-and-set: each asset is changed only if nobody has - * changed it since the preview read it; the rest come back `skipped`. - * Throws UnguardableError, before any request, for shapes it cannot - * cover. - */ - sendGuarded: async (commands: assetApi.Command[], options?: Pick) => { - await this.schema.ensureFor(commands); - return guard.sendGuarded(this.transport, commands, { ...options, lookup: this.schema }); - }, - /** @deprecated since 1.0.0-alpha.3: use `client.query` (rows, through query.v1) or `client.queryPage` (rows and a total, through api/asset as this does). Removed in 1.0.0. */ - query: async (q: assetApi.QueryBody) => { - await this.schema.ensureFor([q]); - return assetApi.query(this.transport, q, { lookup: this.schema }); - }, - /** @deprecated since 1.0.0-alpha.3: use `client.queries`. Removed in 1.0.0. */ - queries: async (qs: assetApi.QueryBody[]) => { - await this.schema.ensureFor(qs); - return assetApi.queries(this.transport, qs, { lookup: this.schema }); - } - }; + /** + * Send a batch (api/asset). The Outcome says what it did — created, + * modified and operated OIDs, failures by index (each with its parsed + * violation), query rows per query command — and never the envelope. + * The server commits per command and answers 200 either way, so a + * failed command is in `failures`, or thrown as a CommandFailureError + * with `throwOnFailure` (the error carries the same Outcome). Not + * guarded: it writes whatever is there now. `sendGuarded` is the + * compare-and-set. + */ + async send(commands: assetApi.Command[], options?: Omit): Promise> { + await this.schema.ensureFor(commands); + return assetApi.outcomeOf(await assetApi.send(this.transport, commands, { ...options, lookup: this.schema })); + } + + /** The server's projection of a batch: one command per asset it would touch, nothing applied. */ + preview(commands: assetApi.Command[]): Promise { + return assetApi.preview(this.transport, commands); + } + + /** + * Send as a compare-and-set: each asset is changed only if nobody has + * changed it since the preview read it; the rest come back `skipped`. + * Throws UnguardableError, before any request, for shapes it cannot + * cover. + */ + async sendGuarded(commands: assetApi.Command[], options?: Pick): Promise> { + await this.schema.ensureFor(commands); + return guard.sendGuarded(this.transport, commands, { ...options, lookup: this.schema }); + } /** * Services: what a person types, turned into assets. Numbers resolve in @@ -363,9 +349,7 @@ export class AgilityApiClient { 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), - /** @deprecated since 1.0.0-alpha.3: `client.urls.attachment`. Removed in 1.0.0. */ - url: (id: string | number) => this.urls.attachment(id) + remove: (id: string | number) => attachments.remove(this.transport, id) }; /** @@ -376,8 +360,6 @@ export class AgilityApiClient { */ readonly embeddedImages = { upload: (asset: string, data: attachment.Bytes, options?: { filename?: string; contentType?: string }) => attachment.uploadEmbeddedImage(this.transport, asset, data, options), - /** @deprecated since 1.0.0-alpha.3: `client.urls.embeddedImage`. Removed in 1.0.0. */ - url: (id: string | number) => this.urls.embeddedImage(id), normalize: (html: string) => attachment.normalizeEmbeddedImageUrls(html, this.config.baseUrl) }; diff --git a/src/core/errors.ts b/src/core/errors.ts index 494819c..4e8d4bd 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -26,7 +26,7 @@ export function kindOf(status: number, code?: string): ErrorKind { case "BAD_JSON": case "BAD_RESPONSE": return "protocol"; case "USAGE": return "usage"; - case "CommandFailure": return "commandFailure"; + case "COMMAND_FAILURE": return "commandFailure"; case "QUERY_REJECTED": case "TOO_LARGE": return "invalid"; case "NOT_FOUND": return "notFound"; diff --git a/src/index.ts b/src/index.ts index 8bc0f06..6c50e1c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,23 +16,21 @@ 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. 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"; -export { importantName } from "./services/fields"; -export type { Bytes, EmbeddedImage } from "./wire/attachment"; -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, LooseQuery, ReadParams, ReadResult } from "./wire/rest1"; +// What a caller writes and what a batch answers (src/types/command.ts). +export type { Alias, Command, CommandBody, CommandFailureDetail, CommandValue, CreateBody, ExecuteBody, Outcome, Query, QueryBody, UpdateBody, Violation } from "./types/command"; +export { parseViolation } from "./types/command"; +export { CommandFailureError } from "./wire/assetApi"; +export type { SendOptions } from "./wire/assetApi"; export { normalizeQuery } from "./wire/rest1"; +export type { LooseQuery, OperationResult, ReadParams, ReadResult, Template } from "./wire/rest1"; +export type { Bytes, EmbeddedImage } from "./wire/attachment"; export type { Localizations, LocalizeOptions } from "./wire/loc2"; export type { ConditionalOptions, Tagged } from "./wire/meta"; export type { QueryRejection } from "./wire/queryV1"; +export type { FieldsOf } from "./services/fields"; +export { importantName } from "./services/fields"; +// The wire modules themselves (assetApi, queryV1, rest1, meta, loc2, attachment, fields, select) and the +// endpoints' envelope types are at "@versionone/agility-sdk/wire". // Services: what to do. export { Schema, TypeCache } from "./services/schema"; diff --git a/src/testing/index.ts b/src/testing/index.ts index 4d65a77..8b0df13 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -17,7 +17,6 @@ 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"; @@ -109,14 +108,15 @@ function answerSend(script: Script, commands: Command[], writes: { body: Command } 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))); + // A type nothing scripted is a type the fake's instance does not have, so rows are read as scripted. These + // reads are the client's own schema loading, not something the code under test asked for: they are not recorded. + if (!raw && request.method === "GET" && request.path.startsWith("/meta.v1/")) throw apiErrorFromResponse(404, { error: "Not Found", exceptions: [{ message: `FakeAgilityClient knows no asset type at ${request.path}` }] }); + script.seen.requests.push(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); @@ -179,7 +179,7 @@ function respond(script: Script, request: RequestOptions): unknown { * page itself. 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 + * - `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). @@ -203,7 +203,7 @@ function respond(script: Script, request: RequestOptions): unknown { * transport words it. */ export class FakeAgilityClient extends AgilityApiClient { - /** Every request the client made, in order, as a Transport sees it. */ + /** Every request the client made, in order, as a Transport sees it (the client's own unscripted meta.v1 type loads left out). */ readonly requests: RequestOptions[]; /** Every query asked, in order, whichever read asked it. */ readonly asked: QueryBody[]; @@ -220,8 +220,8 @@ export class FakeAgilityClient extends AgilityApiClient { 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() }); + // The fake's instance has no asset type (every meta.v1 read answers 404), so rows scripted in the model's shape pass through as written. + super({ baseUrl: "https://agility.example.com/Fake", ...config }, { transport }); this.script = script; this.requests = script.seen.requests; this.asked = script.seen.asked; diff --git a/src/types/asset.ts b/src/types/asset.ts index 67ca7f9..39e5bb8 100644 --- a/src/types/asset.ts +++ b/src/types/asset.ts @@ -39,8 +39,11 @@ export function assetStateOf(value: unknown): AssetStateValue | string | null { } /** - * A reference to another asset: always at least its OID, plus whatever a - * select pulled through (Owners.Name lands on the Ref as Name). + * A reference to another asset: always its OID. It carries more only when + * asked to: a sub-select (`{ from: "Owners", select: ["Name"] }`) puts + * `Name` on each Ref. A dotted path selected by name (`"Owners.Name"`) is + * not folded onto the Ref: it arrives under its own key, `row["Owners.Name"]`, + * like everything a query selects. */ export type Ref = { _oid: Oid } & Partial>; diff --git a/src/types/command.ts b/src/types/command.ts new file mode 100644 index 0000000..38517f9 --- /dev/null +++ b/src/types/command.ts @@ -0,0 +1,136 @@ +/** + * The vocabulary of a batch: the commands a caller writes (a query, a + * create, an update, an operation) and what a batch did, in the model's + * terms. One shape whichever endpoint carries it (spec 000 section 2): + * query.v1 and api/asset take the same query, and a write's answer is an + * Outcome, never an endpoint's envelope. The wire modules translate. + */ +import type { Asset, Oid, Ref } from "./asset"; +import type { AttributeTokenRef } from "./metamodel"; +import type { CreateType, From, SelectPath, TypeOf } from "./query"; + +// ---- what a caller writes ----------------------------------------------------- + +/** A value in a command as the MODEL writes it: scalars, Refs, lists of either, or a nested command. */ +export type CommandValue = string | number | boolean | null | Ref | CommandValue[] | { [key: string]: CommandValue }; + +export interface CreateBody { AssetType: CreateType; [attribute: string]: CommandValue } +/** + * A query. Written with a literal `from`, `select` completes from that + * type's attributes and the rows come back typed by what was selected + * (src/types/query.ts); written from variables, it is what it always was. + */ +export interface QueryBody { + from: F | From; + select?: (SelectPath> | QueryBody)[]; + filter?: string[]; + where?: Record; + with?: Record; + sort?: string[]; + page?: { size: number; start: number }; + find?: string; + findin?: string[]; + asof?: string; + /** Group the rows by a relation: each result row is then a group, its rows under `_children` (translated like any row of `from`). */ + group?: (string | { from: string; [key: string]: unknown })[]; +} +/** + * A query as a read takes it: a QueryBody with its page. Every read is + * bounded, and the type says so, so an unpaged read does not compile. (A + * sub-select inside `select` is a plain QueryBody: it has no page.) + */ +export type Query = QueryBody & { page: { size: number; start: number } }; + +/** + * An update. Each key of `update` is an attribute; its value replaces a + * scalar or a single relation (null clears it). A multi-value relation is + * changed with `{ add: [...], remove: [...] }`. A plain list does NOT + * replace a multi-value relation: the server ADDS its members, like rest-1's + * `act: "add"` (seen live on the API-testing instance, 2026-11-07). To set one exactly, + * remove what should go and add what should come. A change comment goes in + * the update node as `ChangeComment`. + */ +export interface UpdateBody { from: From; filter?: string[]; where?: Record; with?: Record; update: Record } +/** + * An operation (QuickClose, Inactivate, Reactivate, Delete, …), optionally + * with arguments. It cannot carry a change comment. Agility refuses to + * Delete a closed asset (Violation'AssetCannotDeleteClosed): Reactivate it + * first, as batch.reversible does. + */ +export interface ExecuteBody { from: From; filter?: string[]; where?: Record; with?: Record; execute: string | { op: string; args?: Record; list?: Record[] } } +export type CommandBody = CreateBody | QueryBody | UpdateBody | ExecuteBody; + +/** An alias key: "@story". */ +export type Alias = `@${string}`; +/** A command as sent: aliased ({ "@x": body }) or bare (the body itself). */ +export type Command = { [alias: Alias]: CommandBody } | CommandBody; + +// ---- what comes back ----------------------------------------------------------- + +/** + * One failed command, normalised. `index` is the zero-based position, in + * the batch as sent, of the command that produced the failure (the server's + * sourceCommandIndex — the echoed alias is replaced by a generated one, so + * the index is the only key back to the request); null when the server gave + * none. Several failures can share one index: a failed create fails every + * descendant it would have parented, and the first entry is the root cause. + * `message` is the server's text, often an apostrophe-delimited token + * ("Violation'Invalid'Epic.Scope") a caller can branch on or run through + * loc-2 — but an unknown attribute reads differently in `select` and in + * `where`, so match on text with care. stackTrace is never kept: only + * internal development builds send it. + */ +export interface CommandFailureDetail { + index: number | null; + message: string; + /** + * The command as the server echoed it, under a generated alias: what a + * caller resends after correcting it. Readable on every failure but not + * enumerable, so a serialised failure (a receipt, a log line) carries + * index, message and violation and not the whole command. + */ + readonly echoed: Record; + /** The message read as a validation violation, when it is one. */ + violation: Violation | null; +} + +/** + * A validation failure as api/asset words it: `Violation''`, + * where the rule is Required, Invalid, AssetCannotDeleteClosed, … and the + * rest, when present, names what was violated. The attribute form is a + * loc-2 tag (`AttributeDefinition'Scope'Story`, live 2026-11-12), which + * `client.localize` turns into the attribute's label; an older spelling is + * the token itself (`Epic.Scope`). Both read as `attribute: "Story.Scope"`. + */ +export interface Violation { + rule: string; + /** "Story.Scope" when the violation names an attribute; null otherwise. */ + attribute: AttributeTokenRef | null; + /** The loc-2 tag naming what was violated (`AttributeDefinition'Scope'Story`), when the message carries one; null for the token spelling. */ + tag: string | null; +} + +/** The violation a failure message describes, or null when it is not one. */ +export function parseViolation(message: string): Violation | null { + const parts = message.trim().split("'"); + if (parts[0] !== "Violation" || !parts[1]) return null; + const rule = parts[1], rest = parts.slice(2).filter((p) => p !== ""); + if (rest[0] === "AttributeDefinition" && rest[1] && rest[2]) return { rule, attribute: `${rest[2]}.${rest[1]}`, tag: rest.join("'") }; + // The older spelling names the attribute by its token ("Epic.Scope"): not a loc-2 tag, so `tag` is null there. + const token = rest.length === 1 && /^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/.test(rest[0]!) ? (rest[0] as AttributeTokenRef) : null; + return { rule, attribute: token, tag: !token && rest.length > 1 ? rest.join("'") : null }; +} + +/** What a batch did, in the model's terms: the services read this, never the envelope. */ +export interface Outcome { + /** The server's id for the request: what to quote when asking about a batch. Null for an outcome merged from several sends. */ + requestId: string | null; + created: Oid[]; + modified: Oid[]; + operated: Oid[]; + failures: CommandFailureDetail[]; + /** One slot per query, in request order; null where the query failed. */ + queryResults: (Row[] | null)[]; + durationSeconds: number | null; +} + diff --git a/src/wire/assetApi.ts b/src/wire/assetApi.ts index bfac017..de93eb2 100644 --- a/src/wire/assetApi.ts +++ b/src/wire/assetApi.ts @@ -27,63 +27,15 @@ import { ApiError, UsageError } from "../core/errors"; import type { Transport } from "../core/transport"; import type { Asset, Oid, Ref } from "../types/asset"; +import { parseViolation, type Command, type CommandFailureDetail, type CommandValue, type Outcome, type QueryBody } from "../types/command"; import type { AssetTypeToken, AttributeLookup, AttributeTokenRef, AttributeType } from "../types/metamodel"; -import type { CreateType, From, SelectPath, TypeOf } from "../types/query"; import { momentless } from "../types/oid"; import { fromTypeOf, resolvePath, type PathResolution } from "./select"; export { momentless }; - -// ---- what the endpoint takes ------------------------------------------------ - -/** A value in a command as the MODEL writes it: scalars, Refs, lists of either, or a nested command. */ -export type CommandValue = string | number | boolean | null | Ref | CommandValue[] | { [key: string]: CommandValue }; - -export interface CreateBody { AssetType: CreateType; [attribute: string]: CommandValue } -/** - * A query. Written with a literal `from`, `select` completes from that - * type's attributes and the rows come back typed by what was selected - * (src/types/query.ts); written from variables, it is what it always was. - */ -export interface QueryBody { - from: F | From; - select?: (SelectPath> | QueryBody)[]; - filter?: string[]; - where?: Record; - with?: Record; - sort?: string[]; - page?: { size: number; start: number }; - find?: string; - findin?: string[]; - asof?: string; - /** Ask api/asset for the total number of matches (query.v1 ignores it); read it with queryPage. */ - needTotal?: boolean; - /** Group the rows by a relation: each result row is then a group, its rows under `_children` (translated like any row of `from`). */ - group?: (string | { from: string; [key: string]: unknown })[]; -} -/** - * An update. Each key of `update` is an attribute; its value replaces a - * scalar or a single relation (null clears it). A multi-value relation is - * changed with `{ add: [...], remove: [...] }`. A plain list does NOT - * replace a multi-value relation: the server ADDS its members, like rest-1's - * `act: "add"` (seen live on the API-testing instance, 2026-11-07). To set one exactly, - * remove what should go and add what should come. A change comment goes in - * the update node as `ChangeComment`. - */ -export interface UpdateBody { from: From; filter?: string[]; where?: Record; with?: Record; update: Record } -/** - * An operation (QuickClose, Inactivate, Reactivate, Delete, …), optionally - * with arguments. It cannot carry a change comment. Agility refuses to - * Delete a closed asset (Violation'AssetCannotDeleteClosed): Reactivate it - * first, as batch.reversible does. - */ -export interface ExecuteBody { from: From; filter?: string[]; where?: Record; with?: Record; execute: string | { op: string; args?: Record; list?: Record[] } } -export type CommandBody = CreateBody | QueryBody | UpdateBody | ExecuteBody; - -/** An alias key: "@story". */ -export type Alias = `@${string}`; -/** A command as sent: aliased ({ "@x": body }) or bare (the body itself). */ -export type Command = { [alias: Alias]: CommandBody } | CommandBody; +// The vocabulary of a batch — what a caller writes and what comes back in the model's terms — lives in the model (src/types/command.ts). +export { parseViolation }; +export type { Alias, Command, CommandBody, CommandFailureDetail, CommandValue, CreateBody, ExecuteBody, Outcome, Query, QueryBody, UpdateBody, Violation } from "../types/command"; // ---- what the endpoint returns ---------------------------------------------- @@ -218,33 +170,6 @@ function toNumber(value: unknown): unknown { return Number.isNaN(n) ? value : n; } -/** - * One failed command, normalised. `index` is the zero-based position, in - * the batch as sent, of the command that produced the failure (the server's - * sourceCommandIndex — the echoed alias is replaced by a generated one, so - * the index is the only key back to the request); null when the server gave - * none. Several failures can share one index: a failed create fails every - * descendant it would have parented, and the first entry is the root cause. - * `message` is the server's text, often an apostrophe-delimited token - * ("Violation'Invalid'Epic.Scope") a caller can branch on or run through - * loc-2 — but an unknown attribute reads differently in `select` and in - * `where`, so match on text with care. stackTrace is never kept: only - * internal development builds send it. - */ -export interface CommandFailureDetail { - index: number | null; - message: string; - /** - * The command as the server echoed it, under a generated alias: what a - * caller resends after correcting it. Readable on every failure but not - * enumerable, so a serialised failure (a receipt, a log line) carries - * index, message and violation and not the whole command. - */ - readonly echoed: Record; - /** The message read as a validation violation, when it is one. */ - violation: Violation | null; -} - /** A failure detail with `echoed` readable but not enumerable. */ function failureDetail(index: number | null, message: string, echoed: Record): CommandFailureDetail { const detail = { index, message, violation: parseViolation(message) } as CommandFailureDetail; @@ -252,33 +177,6 @@ function failureDetail(index: number | null, message: string, echoed: Record'`, - * where the rule is Required, Invalid, AssetCannotDeleteClosed, … and the - * rest, when present, names what was violated. The attribute form is a - * loc-2 tag (`AttributeDefinition'Scope'Story`, live 2026-11-12), which - * `client.localize` turns into the attribute's label; an older spelling is - * the token itself (`Epic.Scope`). Both read as `attribute: "Story.Scope"`. - */ -export interface Violation { - rule: string; - /** "Story.Scope" when the violation names an attribute; null otherwise. */ - attribute: AttributeTokenRef | null; - /** The loc-2 tag naming what was violated (`AttributeDefinition'Scope'Story`), when the message carries one; null for the token spelling. */ - tag: string | null; -} - -/** The violation a failure message describes, or null when it is not one. */ -export function parseViolation(message: string): Violation | null { - const parts = message.trim().split("'"); - if (parts[0] !== "Violation" || !parts[1]) return null; - const rule = parts[1], rest = parts.slice(2).filter((p) => p !== ""); - if (rest[0] === "AttributeDefinition" && rest[1] && rest[2]) return { rule, attribute: `${rest[2]}.${rest[1]}`, tag: rest.join("'") }; - // The older spelling names the attribute by its token ("Epic.Scope"): not a loc-2 tag, so `tag` is null there. - const token = rest.length === 1 && /^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/.test(rest[0]!) ? (rest[0] as AttributeTokenRef) : null; - return { rule, attribute: token, tag: !token && rest.length > 1 ? rest.join("'") : null }; -} - /** The failures of a response, normalised: index and message, always both. */ export function failuresOf(response: AssetApiResponse): CommandFailureDetail[] { return (response.commandFailures?.commands ?? []).map(({ error, ...echoed }) => failureDetail( @@ -288,19 +186,6 @@ export function failuresOf(response: AssetApiResponse )); } -/** What a batch did, in the model's terms: the services read this, never the envelope. */ -export interface Outcome { - /** The server's id for the request: what to quote when asking about a batch. Null for an outcome merged from several sends. */ - requestId: string | null; - created: Oid[]; - modified: Oid[]; - operated: Oid[]; - failures: CommandFailureDetail[]; - /** One slot per query, in request order; null where the query failed. */ - queryResults: (Row[] | null)[]; - durationSeconds: number | null; -} - /** * The outcome of a (translated) response: OIDs momentless, failures * normalised. Every field has a default, so a partial envelope (a test fake @@ -358,7 +243,7 @@ export class CommandFailureError extends ApiError { readonly outcome: Outcome; constructor(response: AssetApiResponse, failures: CommandFailureDetail[] = failuresOf(response)) { - super(failures.map((f) => f.message).join("; ") || "command failed", 200, "CommandFailure", failures); + super(failures.map((f) => f.message).join("; ") || "command failed", 200, "COMMAND_FAILURE", failures); this.name = "CommandFailureError"; this.failures = failures; this.response = response; @@ -481,7 +366,8 @@ export async function query(transport: Transport, q: */ export async function queryPage(transport: Transport, q: QueryBody, options: ReadOptions = {}): Promise<{ rows: Row[]; total: number | null; more: boolean }> { if (!q.page) throw new UsageError(`query of ${q.from} without a page: every api/asset read must be bounded`); - const response = await send(transport, [{ ...q, needTotal: true }], { ...options, throwOnFailure: true }); + // needTotal is api/asset's own flag for "report the number of matches"; a caller asks by calling this. + const response = await send(transport, [{ ...q, needTotal: true } as QueryBody], { ...options, throwOnFailure: true }); const rows = response.queryResult.results[0] ?? []; const reported = (response.queryResult as { resultMetaData?: { total?: unknown }[] }).resultMetaData?.[0]?.total; const total = typeof reported === "number" ? reported : null; diff --git a/src/wire/index.ts b/src/wire/index.ts index 7bb92a3..1b507a5 100644 --- a/src/wire/index.ts +++ b/src/wire/index.ts @@ -12,5 +12,5 @@ export * as attachment from "./attachment"; export * as select from "./select"; export * as fields from "./fields"; export type { AssetDocument, AssetsDocument, ReadParams, ReadResult } from "./rest1"; -export type { AssetApiResponse, Command, CommandBody, CommandValue, CreateBody, ExecuteBody, QueryBody, UpdateBody, CommandFailure, CommandError, OidTokens, SendOptions } from "./assetApi"; +export type { AssetApiResponse, Command, CommandBody, CommandValue, CreateBody, ExecuteBody, QueryBody, UpdateBody, CommandFailure, CommandError, OidTokens, ReadOptions, RowContext, SendOptions } from "./assetApi"; export type { Localizations, LocalizeOptions } from "./loc2"; diff --git a/src/wire/rest1.ts b/src/wire/rest1.ts index e32a338..a8ece13 100644 --- a/src/wire/rest1.ts +++ b/src/wire/rest1.ts @@ -38,7 +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"; +import type { Query, QueryBody } from "./assetApi"; export { momentless }; @@ -55,12 +55,8 @@ export interface AssetsDocument { _type: "Assets" | "History"; total?: number; p export interface ReadParams { /** Attributes to select, as a query's `select`; a type-qualified name (Story.Number) reaches a subtype's attribute from a base type. */ select?: string[]; - /** @deprecated rest-1's own spelling of `select`; kept for one alpha. */ - sel?: string[]; /** Filter terms, as a query's `filter`, joined with ';' (AND). */ filter?: string[]; - /** @deprecated rest-1's own spelling of `filter`; kept for one alpha. */ - where?: string[]; /** The filter context: { $oids: [...] } — sent in rest-1's spelling, $name=a,b|$other=c. */ with?: Record; find?: string; @@ -115,8 +111,8 @@ export function fromAssetDocument(doc: AssetDocument, /** The query string rest-1 wants, from the model's parameters. */ export function toQuery(params: ReadParams): Record { return { - sel: (params.select ?? params.sel)?.join(","), - where: (params.filter ?? params.where)?.length ? (params.filter ?? params.where)!.join(";") : undefined, + sel: params.select?.join(","), + where: params.filter?.length ? params.filter.join(";") : undefined, with: params.with ? Object.entries(params.with).map(([k, v]) => `${k}=${[].concat(v as never).join(",")}`).join("|") : undefined, find: params.find, findin: params.findin?.join(","), @@ -239,11 +235,14 @@ const listOf = (value: string | string[]): string[] => (typeof value === "string * 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 + * already is a QueryBody comes back equal; one written with a page is + * typed as a read takes it (`Query`). 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 & { page: NonNullable }): Query; +export function normalizeQuery(query: LooseQuery): QueryBody; 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; diff --git a/test/integration/attachments.test.ts b/test/integration/attachments.test.ts index c630c11..73769b6 100644 --- a/test/integration/attachments.test.ts +++ b/test/integration/attachments.test.ts @@ -51,7 +51,7 @@ describeInstance("attachments (live)", () => { 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 counting = new AgilityApiClient({ baseUrl: instance!.url }, { transport: { request: (o) => { calls.push(o.path); return t.request(o); } }, types: client.schema.cache }); const got = await counting.attachments.get(a._oid, { inline: true }); expect(calls).toEqual(["/query.v1"]); expect(decode(got.bytes)).toBe("inline read\n"); diff --git a/test/integration/client.test.ts b/test/integration/client.test.ts index 81a90ea..dc91a8a 100644 --- a/test/integration/client.test.ts +++ b/test/integration/client.test.ts @@ -81,7 +81,7 @@ describeInstance("rest-1 operate, template and fields (live)", () => { const client = new AgilityApiClient({ baseUrl: instance!.url }, { transport: instance!.transport }); it("copy answers the new story's OID, which api/asset's execute does not; the copy is then deleted", async () => { - const created = await client.assets.send([{ AssetType: "Story", Name: fixtureName("copy source"), Scope: "Scope:0" }], { throwOnFailure: true }); + const created = await client.send([{ AssetType: "Story", Name: fixtureName("copy source"), Scope: "Scope:0" }], { throwOnFailure: true }); const source = created.created[0]!; const made: string[] = [source]; try { @@ -91,13 +91,13 @@ describeInstance("rest-1 operate, template and fields (live)", () => { expect(copy).not.toBe(source); const row = await client.get(copy, ["Name"]); expect(row?.Name).toMatch(/^Copy Of sdk-integration/); - const viaBulk = await client.assets.send([{ from: source, execute: "Copy" }], { throwOnFailure: true }); + const viaBulk = await client.send([{ from: source, execute: "Copy" }], { throwOnFailure: true }); expect(viaBulk.created).toEqual([]); // the control: api/asset reports only the operated source expect(viaBulk.operated).toEqual([source]); const strays = await client.query({ from: "Story", select: ["Name"], filter: ["Name=$n"], with: { $n: `Copy Of ${created.created.length ? (await client.get(source, ["Name"]))!.Name : ""}` }, page: { size: 5, start: 0 } }); made.push(...strays.map((s) => s._oid).filter((o) => !made.includes(o))); } finally { - await client.assets.send(made.map((oid) => ({ from: oid, execute: "Delete" }))); + await client.send(made.map((oid) => ({ from: oid, execute: "Delete" }))); } }, 60_000); diff --git a/test/integration/customFields.test.ts b/test/integration/customFields.test.ts index cddc329..ab5f380 100644 --- a/test/integration/customFields.test.ts +++ b/test/integration/customFields.test.ts @@ -42,7 +42,7 @@ describeLocalInstance("custom fields (live, via the classic UI gadget)", () => { it("a Story's custom values, written through api/asset, read back as number and boolean through the client — and as strings without the schema", async () => { const client = new AgilityApiClient({ baseUrl: instance!.url }, { transport: t }); const numToken = customTokenOf(numeric), flagToken = customTokenOf(flag); - const res = await client.assets.send([ + const res = await client.send([ { "@s": { AssetType: "Story", Name: fixtureName("custom fields"), Scope: { _oid: "Scope:0" }, [numToken]: 7, [flagToken]: true } }, { from: "@s", select: ["Name", numToken, flagToken] } ]); diff --git a/test/integration/queryV1.test.ts b/test/integration/queryV1.test.ts index 58d0e11..598a772 100644 --- a/test/integration/queryV1.test.ts +++ b/test/integration/queryV1.test.ts @@ -13,7 +13,7 @@ describeInstance("queryV1 (live)", () => { const q = { from: "Story", select: ["Name", "Number", "Estimate", "IsClosed", "Scope", "Owners", { from: "Status", select: ["Name"] }], sort: ["ID"], page: { size: 3, start: 0 } }; it("the same query through query.v1 and api/asset translates to the same rows", async () => { - const [viaQueryV1, viaAssets] = await Promise.all([client.query(q), client.assets.query(q)]); + const [viaQueryV1, viaAssets] = await Promise.all([client.query(q), client.queryPage(q).then((p) => p.rows)]); expect(viaQueryV1.length).toBeGreaterThan(0); expect(viaQueryV1).toEqual(viaAssets); }); diff --git a/test/integration/rest1.test.ts b/test/integration/rest1.test.ts index ea9bdd8..7671e28 100644 --- a/test/integration/rest1.test.ts +++ b/test/integration/rest1.test.ts @@ -12,8 +12,8 @@ describeInstance("rest1 (live)", () => { it("a cross-type BaseAsset read with type-qualified Number sels comes back keyed by the plain name, with the real total, AssetState by name, and relation display columns folded onto Refs", async () => { const { rows, total } = await rest1.list(t, "BaseAsset", { - where: ["AssetType='Story','Defect'"], - sel: ["AssetType", "Name", "AssetState", "Story.Number", "Defect.Number", "Workitem.Owners", "PrimaryWorkitem.Status"], + filter: ["AssetType='Story','Defect'"], + select: ["AssetType", "Name", "AssetState", "Story.Number", "Defect.Number", "Workitem.Owners", "PrimaryWorkitem.Status"], sort: ["-ChangeDateUTC"], page: { size: 3, start: 0 }, deleted: false, @@ -32,23 +32,23 @@ describeInstance("rest1 (live)", () => { }); it("find narrows to names and descriptions; a nonexistent term returns nothing — the expect-zero control", async () => { - const hit = await rest1.list(t, "Story", { sel: ["Name"], find: "order", findin: ["Name", "Description"], page: { size: 2, start: 0 }, needTotal: true }); + const hit = await rest1.list(t, "Story", { select: ["Name"], find: "order", findin: ["Name", "Description"], page: { size: 2, start: 0 }, needTotal: true }); expect(hit.rows.length).toBeGreaterThan(0); expect(hit.total).toBeGreaterThan(0); - const none = await rest1.list(t, "Story", { sel: ["Name"], find: "zzqqxxnothing", findin: ["Name", "Description"], page: { size: 2, start: 0 }, needTotal: true }); + const none = await rest1.list(t, "Story", { select: ["Name"], find: "zzqqxxnothing", findin: ["Name", "Description"], page: { size: 2, start: 0 }, needTotal: true }); expect(none.rows).toEqual([]); expect(none.total).toBe(0); }); it("get reads one asset with its relations as Refs, and history reads the same asset one moment per row", async () => { - const { rows: [any] } = await rest1.list(t, "Story", { sel: ["Name"], page: { size: 1, start: 0 } }); + const { rows: [any] } = await rest1.list(t, "Story", { select: ["Name"], page: { size: 1, start: 0 } }); expect(any).toBeDefined(); const one = await rest1.get(t, any!._oid, ["Name", "Scope", "Owners", "Super"]); expect(one._oid).toBe(any!._oid); expect(one.Name).toBe(any!.Name); expect(one.Scope).toMatchObject({ _oid: expect.stringMatching(/^Scope:\d+$/) }); expect(typeof one.Scope?.Name).toBe("string"); // rest-1 adds Scope.Name beside a selected Scope; folded onto the Ref - const moments = await rest1.history(t, any!._oid, { sel: ["Name", "ChangeDate"], page: { size: 3, start: 0 } }); + const moments = await rest1.history(t, any!._oid, { select: ["Name", "ChangeDate"], page: { size: 3, start: 0 } }); expect(moments.rows.length).toBeGreaterThan(0); for (const m of moments.rows) expect(m._oid).toMatch(new RegExp(`^${any!._oid}:\\d+$`)); }); diff --git a/test/integration/schema.test.ts b/test/integration/schema.test.ts index b657fc4..b2f9989 100644 --- a/test/integration/schema.test.ts +++ b/test/integration/schema.test.ts @@ -47,7 +47,7 @@ describeInstance("schema (live)", () => { it("through the client, api/asset rows arrive in the model's shape: numbers, booleans, one Ref for a sub-selected single relation, numbers for aggregates", async () => { const client = new AgilityApiClient({ baseUrl: instance!.url }, { transport: t }); - const rows = await client.assets.query({ + const { rows } = await client.queryPage({ from: "Story", select: ["Name", "Estimate", "IsClosed", "IsReadOnly", "AssetState", { from: "Status", select: ["Name"] }, { from: "Owners", select: ["Name", "IsInactive"] }, "Scope", "Owners.@Count", "Children:Task.@Count"], filter: ["ID=$story"], diff --git a/test/unit/assetApi.test.ts b/test/unit/assetApi.test.ts index 717aa42..85e8013 100644 --- a/test/unit/assetApi.test.ts +++ b/test/unit/assetApi.test.ts @@ -112,7 +112,7 @@ describe("assetApi: command failures", () => { const e = err as CommandFailureError; expect(e.message).toBe("Violation'Required'Scope"); expect(e.status).toBe(200); - expect(e.code).toBe("CommandFailure"); + expect(e.code).toBe("COMMAND_FAILURE"); expect(e.failures).toEqual([{ index: 1, message: "Violation'Required'Scope", violation: { rule: "Required", attribute: null, tag: null } }]); expect(e.failures[0]!.echoed).toEqual({ "@0f3c": { AssetType: "Story" } }); expect(e.failures[0]).not.toHaveProperty("stackTrace"); diff --git a/test/unit/attachment.test.ts b/test/unit/attachment.test.ts index fa57c6d..e513f05 100644 --- a/test/unit/attachment.test.ts +++ b/test/unit/attachment.test.ts @@ -138,8 +138,8 @@ describe("attachments service", () => { it("the client exposes attachments and embedded images, with URLs on its own base", () => { const client = new AgilityApiClient({ baseUrl: "https://agility.example.com/MyInstance/" }, { transport: fake() }); - expect(client.attachments.url("Attachment:5")).toBe("https://agility.example.com/MyInstance/attachment.img/5"); - expect(client.embeddedImages.url(12)).toBe("https://agility.example.com/MyInstance/embedded.img/12"); + expect(client.urls.attachment("Attachment:5")).toBe("https://agility.example.com/MyInstance/attachment.img/5"); + expect(client.urls.embeddedImage(12)).toBe("https://agility.example.com/MyInstance/embedded.img/12"); }); }); diff --git a/test/unit/cjs.test.ts b/test/unit/cjs.test.ts index 6cd95ba..577c002 100644 --- a/test/unit/cjs.test.ts +++ b/test/unit/cjs.test.ts @@ -34,7 +34,7 @@ afterAll(() => { if (dir) rmSync(dir, { recursive: true, force: true }); }); const CONSUMER = String.raw` const assert = require("node:assert/strict"); const sdk = require("@versionone/agility-sdk"); -for (const name of ["AgilityApiClient", "createFetchTransport", "ApiError", "CommandFailureError", "assetApi", "rest1", "meta", "loc2", "Schema", "parseOid", "momentless"]) { +for (const name of ["AgilityApiClient", "createFetchTransport", "ApiError", "CommandFailureError", "TypeCache", "Schema", "parseOid", "momentless", "normalizeQuery"]) { assert.ok(sdk[name], "missing export " + name); } const json = (body) => new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } }); @@ -50,14 +50,18 @@ const fetchImpl = async (url) => { const transport = sdk.createFetchTransport({ baseUrl: "https://v1.example/inst", accessToken: "t", fetchImpl }); const client = new sdk.AgilityApiClient({ baseUrl: "https://v1.example/inst" }, { transport }); assert.deepEqual(await client.localize(["Plural'Story"]), { "Plural'Story": "Backlog Items" }); - const err = await client.assets.send([{ AssetType: "Story", Name: "x" }], { throwOnFailure: true }).catch((e) => e); + const err = await client.send([{ AssetType: "Story", Name: "x" }], { throwOnFailure: true }).catch((e) => e); 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); + for (const name of ["assetApi", "queryV1", "rest1", "meta", "loc2", "attachment", "fields", "select"]) { + assert.ok(wire[name], "missing wire module " + name); + assert.equal(sdk[name], undefined, "the root no longer exports the wire module " + name); + } + assert.equal(wire.assetApi.CommandFailureError, sdk.CommandFailureError); 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" }]); diff --git a/test/unit/client.test.ts b/test/unit/client.test.ts index 2431673..db30cd0 100644 --- a/test/unit/client.test.ts +++ b/test/unit/client.test.ts @@ -43,16 +43,16 @@ describe("client: reads", () => { it("get reads one asset by OID through query.v1 (the OID is the `from`), null when nothing has it; the OID loses its moment", async () => { const t = fake(() => [[wireStory]]); - const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, schema: schema() }); + const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: schema().cache }); const row = await client.get("Story:1055:777", ["Name"]); expect(row).toMatchObject({ _oid: "Story:1055", Name: "Sample: Logon" }); expect(t.calls[0]!.body).toEqual([{ from: "Story:1055", select: ["Name"], page: { size: 1, start: 0 } }]); - expect(await new AgilityApiClient({ baseUrl: "https://x" }, { transport: fake(() => [[]]), schema: schema() }).get("Story:9")).toBeNull(); + expect(await new AgilityApiClient({ baseUrl: "https://x" }, { transport: fake(() => [[]]), types: schema().cache }).get("Story:9")).toBeNull(); }); it("queryPage goes to api/asset with needTotal and answers rows, total and more", async () => { const t = fake(() => envelope({ queryResult: { results: [[wireStory, wireStory]], resultMetaData: [{ total: 5 }], count: 1 } })); - const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, schema: schema() }); + const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: schema().cache }); const page = await client.queryPage({ from: "Story", select: ["Estimate"], page: { size: 2, start: 2 } }); expect(t.calls[0]).toMatchObject({ path: "/api/asset", method: "POST" }); expect((t.calls[0]!.body as unknown[])[0]).toMatchObject({ needTotal: true }); @@ -63,7 +63,7 @@ describe("client: reads", () => { it("pages walks query.v1 page by page, stops at a short page, and never reads past the limit; all collects the rows", async () => { const rows = Array.from({ length: 7 }, (_, i) => ({ _oid: `Story:${i}`, Name: `s${i}` })); const t = fake((o) => { const q = (o.body as { page: { size: number; start: number } }[])[0]!; return [rows.slice(q.page.start, q.page.start + q.page.size)]; }); - const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, schema: schema() }); + const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: schema().cache }); const seen: number[] = []; for await (const page of client.pages({ from: "Story", select: ["Name"], page: { size: 3, start: 0 } })) seen.push(page.length); expect(seen).toEqual([3, 3, 1]); @@ -71,23 +71,22 @@ describe("client: reads", () => { const capped = await client.all({ from: "Story", select: ["Name"], page: { size: 3, start: 0 } }, { limit: 4 }); expect(capped.map((r) => r._oid)).toEqual(["Story:0", "Story:1", "Story:2", "Story:3"]); expect(t.calls.slice(3).map((c) => (c.body as { page: unknown }[])[0]!.page)).toEqual([{ size: 3, start: 0 }, { size: 1, start: 3 }]); - await expect(client.all({ from: "Story", select: ["Name"] })).rejects.toBeInstanceOf(UsageError); + await expect(client.all({ from: "Story", select: ["Name"] } as never)).rejects.toBeInstanceOf(UsageError); }); it("me asks for the member whose IsSelf is true", async () => { const t = fake(() => [[{ _oid: "Member:1000", Name: "SDK Test Account", Username: "sdk-test-account", Nickname: "SDK", Email: "" }]]); - const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, schema: schema() }); + const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: schema().cache }); const me = await client.me(); expect(me).toMatchObject({ _oid: "Member:1000", Username: "sdk-test-account" }); expect((t.calls[0]!.body as unknown[])[0]).toMatchObject({ from: "Member", filter: ["IsSelf='true'"], page: { size: 1, start: 0 } }); - await expect(new AgilityApiClient({ baseUrl: "https://x" }, { transport: fake(() => [[]]), schema: schema() }).me()).rejects.toMatchObject({ kind: "notFound" }); + await expect(new AgilityApiClient({ baseUrl: "https://x" }, { transport: fake(() => [[]]), types: schema().cache }).me()).rejects.toMatchObject({ kind: "notFound" }); }); - it("data.list takes a query's spelling (select, filter) and sends rest-1's (sel, where); the old names still work", async () => { + it("data.list takes a query's spelling (select, filter) and sends rest-1's (sel, where)", async () => { const t = fake(() => ({ _type: "Assets", pageSize: 2, pageStart: 0, Assets: [] })); const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t }); await client.data.list("Story", { select: ["Name"], filter: ["AssetState='Closed'"], deleted: true, page: { size: 2, start: 0 } }); - await client.data.list("Story", { sel: ["Name"], where: ["AssetState='Closed'"], page: { size: 2, start: 0 } }); for (const call of t.calls) expect(call).toMatchObject({ method: "GET", path: "/rest-1.v1/Data/Story", query: expect.objectContaining({ sel: "Name", where: "AssetState='Closed'", page: "2,0" }) }); expect(t.calls[0]!.query).toMatchObject({ deleted: "true" }); }); @@ -100,15 +99,15 @@ describe("client: writes", () => { commandFailures: { commands: [{ "@0f3c": { AssetType: "Story" }, error: { message: "Violation'Required'AttributeDefinition'Scope'Story", sourceCommandIndex: 1 } }], count: 1 }, queryResult: { results: [[wireStory]], resultMetaData: [], count: 1 } })); - const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, schema: schema() }); - const outcome = await client.assets.send([{ AssetType: "Story", Name: "a", Scope: "Scope:0" }, { AssetType: "Story" }, { from: "Story", select: ["Estimate"], page: { size: 1, start: 0 } }]); + const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: schema().cache }); + const outcome = await client.send([{ AssetType: "Story", Name: "a", Scope: "Scope:0" }, { AssetType: "Story" }, { from: "Story", select: ["Estimate"], page: { size: 1, start: 0 } }]); expect(outcome.created).toEqual(["Story:5"]); expect(outcome.requestId).toBe("r"); expect(outcome.failures).toEqual([expect.objectContaining({ index: 1, violation: { rule: "Required", attribute: "Story.Scope", tag: "AttributeDefinition'Scope'Story" } })]); expect(outcome.queryResults).toEqual([[expect.objectContaining({ Estimate: 2 })]]); expect(outcome).not.toHaveProperty("assetsCreated"); - const failing = new AgilityApiClient({ baseUrl: "https://x" }, { transport: fake(() => envelope({ assetsCreated: { oidTokens: ["Story:5:10"], count: 1 }, commandFailures: { commands: [{ error: { message: "Violation'Required'AttributeDefinition'Scope'Story", sourceCommandIndex: 1 } }], count: 1 } })), schema: schema() }); - const err = (await failing.assets.send([{ AssetType: "Story", Name: "a", Scope: "Scope:0" }, { AssetType: "Story" }], { throwOnFailure: true }).catch((e: unknown) => e)) as CommandFailureError; + const failing = new AgilityApiClient({ baseUrl: "https://x" }, { transport: fake(() => envelope({ assetsCreated: { oidTokens: ["Story:5:10"], count: 1 }, commandFailures: { commands: [{ error: { message: "Violation'Required'AttributeDefinition'Scope'Story", sourceCommandIndex: 1 } }], count: 1 } })), types: schema().cache }); + const err = (await failing.send([{ AssetType: "Story", Name: "a", Scope: "Scope:0" }, { AssetType: "Story" }], { throwOnFailure: true }).catch((e: unknown) => e)) as CommandFailureError; expect(err).toBeInstanceOf(CommandFailureError); expect(err.kind).toBe("commandFailure"); expect(err.outcome.created).toEqual(["Story:5"]); @@ -123,14 +122,13 @@ describe("client: urls", () => { expect(() => client.urls.asset("hello")).toThrow(UsageError); expect(client.urls.attachment("Attachment:9")).toBe("https://agility.example.com/MyInstance/attachment.img/9"); expect(client.urls.embeddedImage(12)).toBe("https://agility.example.com/MyInstance/embedded.img/12"); - expect(client.attachments.url(9)).toBe(client.urls.attachment(9)); }); }); describe("client: data.operate, copy, data.template", () => { it("copy answers the copy's OID through rest-1; template reads New/", async () => { const t = fake((o) => (o.path.startsWith("/rest-1.v1/New/") ? { _type: "Asset", href: "", id: "", Attributes: { Scope: { _type: "Relation", name: "Scope", act: "set", value: { _type: "Asset", href: "", idref: "Scope:0" } } } } : { _type: "Asset", href: "", id: "Story:9:1" })); - const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, schema: schema() }); + const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: schema().cache }); expect(await client.copy("Story:1")).toBe("Story:9"); expect(await client.data.operate("Story:1", "Inactivate")).toEqual({ oid: "Story:9", moment: "1" }); const tpl = await client.data.template("Story", { ctx: "Scope:0" }); diff --git a/test/unit/errors.test.ts b/test/unit/errors.test.ts index ea2cdb7..6dca1f9 100644 --- a/test/unit/errors.test.ts +++ b/test/unit/errors.test.ts @@ -19,7 +19,7 @@ describe("error kinds", () => { expect(kindOf(0, "NETWORK_ERROR")).toBe("transient"); expect(kindOf(0, "ABORTED")).toBe("aborted"); expect(kindOf(200, "BAD_RESPONSE")).toBe("protocol"); - expect(kindOf(200, "CommandFailure")).toBe("commandFailure"); + expect(kindOf(200, "COMMAND_FAILURE")).toBe("commandFailure"); expect(kindOf(400, "QUERY_REJECTED")).toBe("invalid"); expect(kindOf(404, "NOT_FOUND")).toBe("notFound"); expect(kindOf(413, "TOO_LARGE")).toBe("invalid"); diff --git a/test/unit/fields.test.ts b/test/unit/fields.test.ts index 3819eed..7cc21ed 100644 --- a/test/unit/fields.test.ts +++ b/test/unit/fields.test.ts @@ -44,7 +44,7 @@ describe("fields service", () => { it("describe joins meta's required, visibleFields and the scope's scheme into one answer", async () => { const t = fake((o) => (o.path.startsWith("/api/visibleFields") ? visibleAnswer : { requestId: "r", queryResult: { results: [[{ _oid: "Scope:0", Scheme: [{ _oid: "Scheme:1000", ImportantFields: ["Story.Owners", "Defect.Resolution", "Workitem.Estimate"], IsRequiredAtClose: "True" }] }]], resultMetaData: [], count: 1 } })); - const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, schema: schema() }); + const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: schema().cache }); const f = await client.fields.describe("Story", "Scope:0:7"); expect(f).toEqual({ type: "Story", scope: "Scope:0", scheme: "Scheme:1000", required: ["Name", "Scope"], visible: visibleAnswer[0]!.fields, important: ["Estimate", "Owners"], requiredAtClose: true }); const body = (t.calls.find((c) => c.path === "/api/asset")!.body as unknown[])[0]; diff --git a/test/unit/layers.test.ts b/test/unit/layers.test.ts index e2b0e2f..2034ebc 100644 --- a/test/unit/layers.test.ts +++ b/test/unit/layers.test.ts @@ -61,7 +61,8 @@ describe("layers", () => { // bare word Attributes is meta.v1's own name for a type's attribute map // and belongs in the metamodel types. for (const word of ["oidTokens", "commandFailures", "queryResult", "previewOnly", "\"Attribute\"", "resultMetaData", "pageStart"]) { - if (text.includes(word)) leaks.push(`${relative(src, file)} mentions ${word}`); + // As a whole word: the model's Outcome has `queryResults`, which is not the envelope's `queryResult`. + if (new RegExp(`(? { it("client.query loads the types its queries touch and translates through the client's schema", async () => { const t = fakeTransport([[wireStory]]); - const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, schema }); + const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: schema.cache }); const [row] = await client.query(storyQuery); expect(row).toMatchObject({ Estimate: 2, IsClosed: true }); expect(t.calls.map((c) => c.path)).toEqual(["/query.v1"]); diff --git a/test/unit/rest1.test.ts b/test/unit/rest1.test.ts index c88bafd..577e7f5 100644 --- a/test/unit/rest1.test.ts +++ b/test/unit/rest1.test.ts @@ -49,7 +49,7 @@ describe("rest1: translation", () => { }); it("spells the query string the way rest-1 wants: sel and findin comma-joined, where ';'-joined, with in $name=a,b|… form, page size-first", () => { - expect(toQuery({ sel: ["Name", "Story.Number"], where: ["AssetType='Story'", "AssetState!='Closed'"], with: { $oids: ["Story:1", "Story:2"], $url: "u" }, find: "order", findin: ["Name", "Description"], sort: ["-ChangeDateUTC"], page: { size: 20, start: 40 }, deleted: false, needTotal: true })) + expect(toQuery({ select: ["Name", "Story.Number"], filter: ["AssetType='Story'", "AssetState!='Closed'"], with: { $oids: ["Story:1", "Story:2"], $url: "u" }, find: "order", findin: ["Name", "Description"], sort: ["-ChangeDateUTC"], page: { size: 20, start: 40 }, deleted: false, needTotal: true })) .toEqual({ sel: "Name,Story.Number", where: "AssetType='Story';AssetState!='Closed'", with: "$oids=Story:1,Story:2|$url=u", find: "order", findin: "Name,Description", sort: "-ChangeDateUTC", page: "20,40", deleted: "false", needTotal: "true", asof: undefined }); }); }); @@ -58,7 +58,7 @@ describe("rest1: calls", () => { it("list reads Data/ with the query, translates every row, and surfaces total only when the server sent one; a read without a page is refused", async () => { const envelope: AssetsDocument = { _type: "Assets", total: 54, pageSize: 1, pageStart: 0, Assets: [storyDoc] }; const t = fakeTransport(envelope); - const { rows, total, pageSize } = await list(t, "Story", { sel: ["Name"], page: { size: 1, start: 0 }, needTotal: true }); + const { rows, total, pageSize } = await list(t, "Story", { select: ["Name"], page: { size: 1, start: 0 }, needTotal: true }); expect(t.calls[0]).toMatchObject({ method: "GET", path: "/rest-1.v1/Data/Story", responseType: "json" }); expect(t.calls[0]!.query).toMatchObject({ sel: "Name", page: "1,0", needTotal: "true" }); expect(rows[0]!.Owners).toHaveLength(2); @@ -67,7 +67,7 @@ describe("rest1: calls", () => { const noTotal = fakeTransport({ _type: "Assets", pageSize: 1, pageStart: 0, Assets: [] }); expect((await list(noTotal, "Story", { page: { size: 1, start: 0 } })).total).toBeNull(); const unpaged = fakeTransport(); - await expect(list(unpaged, "Story", { sel: ["Name"] } as never)).rejects.toThrow(/without a page/); + await expect(list(unpaged, "Story", { select: ["Name"] } as never)).rejects.toThrow(/without a page/); expect(unpaged.calls).toHaveLength(0); }); @@ -76,7 +76,7 @@ describe("rest1: calls", () => { const one = await get(t, "Story:2104:99", ["Name", "Owners"]); expect(t.calls[0]).toMatchObject({ path: "/rest-1.v1/Data/Story/2104", query: { sel: "Name,Owners" } }); expect(one._oid).toBe("Story:2104"); - const moments = await history(t, "Story:2104", { sel: ["Name"], page: { size: 2, start: 0 } }); + const moments = await history(t, "Story:2104", { select: ["Name"], page: { size: 2, start: 0 } }); expect(t.calls[1]!.path).toBe("/rest-1.v1/Hist/Story/2104"); expect(moments.rows.map((r) => r._oid)).toEqual(["Story:2104:2797", "Story:2104:2650"]); }); diff --git a/test/unit/testing.test.ts b/test/unit/testing.test.ts index 0050bae..8ce9452 100644 --- a/test/unit/testing.test.ts +++ b/test/unit/testing.test.ts @@ -19,7 +19,7 @@ describe("FakeAgilityClient", () => { const fake = new FakeAgilityClient(); expect(fake).toBeInstanceOf(AgilityApiClient); expectTypeOf(fake).toMatchTypeOf(); - await expect(fake.query({ from: "Story" })).rejects.toThrow(/without a page/); + await expect(fake.query({ from: "Story" } as never)).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"); }); @@ -60,13 +60,13 @@ describe("FakeAgilityClient", () => { 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([ + const outcome = await fake.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"]); + expect((await fake.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); @@ -74,17 +74,17 @@ describe("FakeAgilityClient", () => { 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" }]); + const outcome = await fake.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); + await expect(fake.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"]); + expect((await fake.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" }); + await expect(fake.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 () => { @@ -99,10 +99,10 @@ describe("FakeAgilityClient", () => { 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 } }]); + const outcome = await fake.send([{ "@story": { AssetType: "Story", Name: "new", Scope: "Scope:0" } }, { from: "@story", select: ["Number"], page: { size: 1, start: 0 } }]); expect(outcome.created).toEqual(["Story:1000"]); expect(outcome.queryResults).toEqual([[{ _oid: "Story:1000", Number: "S-01001", Name: "template" }]]); - 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"/); + await expect(new FakeAgilityClient().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 () => { @@ -130,6 +130,7 @@ describe("FakeAgilityClient", () => { 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); + expect(fake.requests.map((r) => r.path)).toEqual(["/query.v1"]); // the type load is the client's plumbing, not the test's subject }); it("an aborted signal ends a read as ABORTED, like the fetch transport", async () => { diff --git a/test/unit/translate.test.ts b/test/unit/translate.test.ts index d9729eb..fa16591 100644 --- a/test/unit/translate.test.ts +++ b/test/unit/translate.test.ts @@ -3,7 +3,7 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; import { AgilityApiClient } from "../../src/client"; import type { RequestOptions, Transport } from "../../src/core/transport"; -import { Schema } from "../../src/services/schema"; +import { Schema, TypeCache } from "../../src/services/schema"; import type { Story } from "../../src/types/assets/Story"; import { fromWireRow, send, type AssetApiResponse } from "../../src/wire/assetApi"; import { toMetamodel, type MetamodelDocument } from "../../src/wire/meta"; @@ -131,13 +131,13 @@ describe("translate: through send and the client", () => { const metaDoc = JSON.parse(readFileSync(join(__dirname, "..", "..", "metamodel.json"), "utf8")) as MetamodelDocument; const t = fakeTransport(metaDoc.AssetTypes.Story, metaDoc.AssetTypes.StoryStatus, envelope([[liveRow]])); const client = new AgilityApiClient({ baseUrl: "http://x" }, { transport: t }); - const [row] = await client.assets.query({ from: "Story", select: ["Estimate", { from: "Status", select: ["Name"] }], page: { size: 1, start: 0 } }); + const { rows: [row] } = await client.queryPage({ from: "Story", select: ["Estimate", { from: "Status", select: ["Name"] }], page: { size: 1, start: 0 } }); expect(t.calls.map((c) => c.path)).toEqual(["/meta.v1/Story", "/meta.v1/StoryStatus", "/api/asset"]); expect(row!.Estimate).toBe(5); expect(row!.Status).toEqual({ _oid: "StoryStatus:2191", Name: "Accepted", Order: 3 }); // A seeded client fetches no meta at all. - const seeded = new AgilityApiClient({ baseUrl: "http://x" }, { transport: fakeTransport(envelope([[liveRow]])), metamodel }); - const [again] = await seeded.assets.query({ from: "Story", select: ["Estimate"], page: { size: 1, start: 0 } }); + const seeded = new AgilityApiClient({ baseUrl: "http://x" }, { transport: fakeTransport(envelope([[liveRow]])), types: TypeCache.fromMetamodel(metamodel) }); + const { rows: [again] } = await seeded.queryPage({ from: "Story", select: ["Estimate"], page: { size: 1, start: 0 } }); expect(again!.IsClosed).toBe(true); }); }); diff --git a/test/unit/transportAuth.test.ts b/test/unit/transportAuth.test.ts index 040a2d6..d56cb2f 100644 --- a/test/unit/transportAuth.test.ts +++ b/test/unit/transportAuth.test.ts @@ -87,12 +87,12 @@ describe("transport for real callers", () => { expect(idle).not.toHaveBeenCalled(); }); - it("client.withSignal ties every request to the signal and shares the schema", async () => { + it("client.withSignal ties every request to the signal and shares the loaded types", async () => { const transport = { request: vi.fn().mockResolvedValue({ Story: "Story" }) }; const base = new AgilityApiClient({ baseUrl: "https://x" }, { transport }); const controller = new AbortController(); const scoped = base.withSignal(controller.signal); - expect(scoped.schema).toBe(base.schema); + expect(scoped.schema.cache).toBe(base.schema.cache); await scoped.localize(["Story"]); expect(transport.request.mock.calls[0]![0].signal).toBe(controller.signal); // The original client is untouched. diff --git a/test/unit/typeCache.test.ts b/test/unit/typeCache.test.ts index 8d39153..b39df52 100644 --- a/test/unit/typeCache.test.ts +++ b/test/unit/typeCache.test.ts @@ -28,8 +28,8 @@ describe("TypeCache: one instance's types shared across clients with different c const types = new TypeCache(); const alice = new AgilityApiClient({ baseUrl: "https://x" }, { transport: userTransport("alice", log), types }); const bob = new AgilityApiClient({ baseUrl: "https://x" }, { transport: userTransport("bob", log), types }); - await alice.assets.query({ from: "Story", select: ["Estimate"], page: { size: 1, start: 0 } }); - await bob.assets.query({ from: "Story", select: ["Estimate", { from: "Status", select: ["Name"] }], page: { size: 1, start: 0 } }); + await alice.queryPage({ from: "Story", select: ["Estimate"], page: { size: 1, start: 0 } }); + await bob.queryPage({ from: "Story", select: ["Estimate", { from: "Status", select: ["Name"] }], page: { size: 1, start: 0 } }); expect(log.filter((l) => l.includes("meta.v1"))).toEqual(["alice /meta.v1/Story", "bob /meta.v1/StoryStatus"]); expect(alice.schema.cache).toBe(types); expect(bob.schema.assetType("StoryStatus")).toBeDefined(); @@ -49,7 +49,7 @@ describe("TypeCache: one instance's types shared across clients with different c const log: string[] = []; const types = TypeCache.fromMetamodel(toMetamodel(metamodel)); const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: userTransport("carol", log), types }); - await client.assets.query({ from: "Story", select: ["Estimate", { from: "Status", select: ["Name"] }], page: { size: 1, start: 0 } }); + await client.queryPage({ from: "Story", select: ["Estimate", { from: "Status", select: ["Name"] }], page: { size: 1, start: 0 } }); expect(log).toEqual(["carol /api/asset"]); }); }); diff --git a/test/unit/typedQuery.test.ts b/test/unit/typedQuery.test.ts index 48a4355..9de2390 100644 --- a/test/unit/typedQuery.test.ts +++ b/test/unit/typedQuery.test.ts @@ -1,11 +1,12 @@ import { describe, expect, expectTypeOf, it, vi } from "vitest"; import { AgilityApiClient } from "../../src/client"; +import { ApiError } from "../../src/core/errors"; import type { Transport } from "../../src/core/transport"; import { Schema } from "../../src/services/schema"; import type { Asset, AttributeValue, Ref } from "../../src/types/asset"; import type { Story } from "../../src/types/assets/Story"; import type { StoryStatus } from "../../src/types/assets/StoryStatus"; -import type { QueryBody } from "../../src/wire/assetApi"; +import type { Query } from "../../src/types/command"; /** * What the types say about a query (src/types/query.ts). The assertions @@ -13,8 +14,9 @@ import type { QueryBody } from "../../src/wire/assetApi"; * time the fake answers nothing of interest. */ const request = vi.fn(async (o: { path: string }) => (o.path === "/api/asset" ? { queryResult: { results: [[{ _oid: "Story:1", Name: "n" }]], resultMetaData: [{ total: 1 }] } } : [[{ _oid: "Story:1", Name: "n" }]])); -const t: Transport = { request: request as unknown as Transport["request"] }; -const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, schema: Schema.fromMetamodel({ Version: "0", AssetTypes: {} }) }); +// No type is known to this instance (meta.v1 answers 404), so rows pass through and the scripted answers go to the queries. +const t: Transport = { request: (async (o: { path: string }) => { if (o.path.startsWith("/meta.v1/")) throw new ApiError("Not Found", 404); return request(o); }) as unknown as Transport["request"] }; +const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: Schema.fromMetamodel({ Version: "0", AssetTypes: {} }).cache }); describe("typed queries", () => { it("a literal from and select type the rows by what was selected; an unselected key is a compile error", async () => { @@ -73,7 +75,7 @@ describe("typed queries", () => { const loose = await client.query({ from, select, page: { size: 1, start: 0 } }); expectTypeOf(loose[0]!._oid).toEqualTypeOf(); expectTypeOf(loose[0]!.Anything).toEqualTypeOf(); - const body: QueryBody = { from: "Story", select: ["Name", { from: "Status", select: ["Name"] }], page: { size: 1, start: 0 } }; + const body: Query = { from: "Story", select: ["Name", { from: "Status", select: ["Name"] }], page: { size: 1, start: 0 } }; const typed = await client.query(body); expectTypeOf(typed).toEqualTypeOf(); // A type the model does not know, and any path, are still accepted. From c2f9fac9a49fb7ac7867f2513063ea792006c8b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:15:59 +0000 Subject: [PATCH 02/17] alpha.8 (2 of 3): the guard compares Moments, and a conflict is said out loud sendGuarded and batch.run guard each asset with where { ID, Moment } + filter RetireDateUTC='' instead of a ChangeDate literal. A Moment alone selects the asset as it was and guards nothing; with the filter it matches only while that version is current. Proved live (test/integration/guard.test.ts, issue #51): current applies, stale matches nothing for a query, a preview and a send, a resend applies nothing, operations and closed assets guard the same way, a deleted asset matches nothing, and Moment travels as a `with` variable, so the one value spliced into filter text is gone. - A command that matched lists its asset even when it changed no value, so "in neither modified nor operated, and no failure for it" is a conflict, and a no-op is a success. `skipped` becomes `conflicts` and no longer includes failed commands; with throwOnFailure a conflict throws ConflictError (kind "conflict"). - sendGuarded's result is the Outcome plus touched, conflicts and details (projected, sent, stamps): one shape to read after any send. - sendGuarded takes `moments`: guard on the version a caller read earlier. - Both terms always travel together and the moment is checked to be digits: RetireDateUTC='' without a Moment, and a non-numeric Moment, are server errors. - batch.run takes guard: true | false with no default. Receipts are `receipt: 2` with stamps, changedAt (readable) and stopped; a stored `receipt: 1` is refused by batch.reversible with ReceiptVersionError (code RECEIPT_VERSION) unless forced, which checks nothing. isReceipt tells them apart. - Each unguardable reason has a code; batch.run finds the fatal one by code, not by its wording. - The blind spot is documented and tested live: a child added to an asset makes no new version of it. Spec 000 section 6 describes the guard as it now is. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 50 ++++++++ README.md | 6 +- specs/000-layers.md | 38 ++++-- src/client.ts | 26 ++-- src/core/errors.ts | 6 +- src/index.ts | 8 +- src/services/batch.ts | 122 ++++++++++++++----- src/services/guard.ts | 214 ++++++++++++++++++++++----------- test/integration/batch.test.ts | 35 ++++-- test/integration/guard.test.ts | 123 +++++++++++++------ test/unit/batch.test.ts | 112 +++++++++++------ test/unit/errors.test.ts | 2 +- test/unit/guard.test.ts | 77 ++++++++---- 13 files changed, 573 insertions(+), 246 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2129d04..03d015d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,8 +50,58 @@ Each entry has the line a consumer follows to migrate. what to branch on. Migration: a comparison with the old code string changes; one on `kind` or `instanceof CommandFailureError` does not. +- **The guard compares Moments, and a conflict is said out loud.** + `sendGuarded` and `batch.run` guard each asset on its `Moment` together + with `RetireDateUTC=''` (an exact compare-and-set; the evidence is on + issue #51), where they compared a `ChangeDate` literal. What changes for + a caller: + - `sendGuarded`'s result is flat: the `Outcome`'s own fields + (`created`, `modified`, `operated`, `failures`, `queryResults`, + `requestId`) plus `touched`, `conflicts` and `details`. Migration: + `res.outcome.modified` → `res.modified`; `res.skipped` → + `res.conflicts`; `res.projected` / `res.sent` / `res.stamps` → + `res.details.projected` / `.sent` / `.stamps`. + - `conflicts` holds only the assets whose command matched nothing + (changed since they were read, or gone). An asset whose command + failed is in `failures` and no longer also listed as skipped; a + command that matched and changed no value is a success. + - With `throwOnFailure`, a conflict throws a `ConflictError` (`kind: + "conflict"`, code `CONFLICT`) carrying the result. Migration: a + caller that passes `throwOnFailure` and wants conflicts returned + catches it, or stops passing the option. + - Stamps are Moments (digits), not timestamps: `details.stamps`, + `Receipt.stamps`, `Receipt.after`, and `was` / `now` in + `batch.reversible`'s `drifted`. For a readable time use + `Receipt.changedAt[oid]`, `before[oid].ChangeDate`, and + `drifted[i].wasChangedAt` / `nowChangedAt`. +- **`batch.run` takes `guard: true | false` and has no default** (it + defaulted to true). Migration: `client.batch.run(commands)` → + `client.batch.run(commands, { guard: true })`. +- **Receipts are `receipt: 2`**: `skipped` → `conflicts`; new `stamps`, + `changedAt` and `stopped`. **A stored `receipt: 1` cannot be checked + for drift**: `batch.reversible` throws a `ReceiptVersionError` (`kind: + "usage"`, code `RECEIPT_VERSION`) for it. Migration for a holder of old + receipts: reverse one with `{ force: true }`, which sends its reverse + without checking whether anyone changed the assets since; or run the + batch again and keep the new receipt. `isReceipt(value)` tells a + current receipt from anything else before calling. +- **An unguardable reason has a `code`** (`aliasedWrite`, + `bareAliasFrom`, `inlineCreate`, `noMoment`). Migration: branch on + `reason.code`, not on the words of `reason.reason`. + +### Added + +- **`sendGuarded(commands, { moments })`**: guard an asset on the moment + the caller read earlier (select `Moment` with the row a person is + shown), so a change made since they saw it is a conflict. +- `Receipt.stopped` says why nothing was sent: `"nothing"`, `"dryRun"` or + `"declined"`. +- `ErrorKind` gains `"conflict"`. + ### Changed +- The guard's blind spot is documented: a change that makes no new + version of an asset (a child added to it) is invisible to it. - `FakeAgilityClient.requests` leaves out the client's own unscripted meta.v1 type loads: it lists what the code under test asked for. - The `Ref` type's doc said a dotted path lands on the Ref; it does not. diff --git a/README.md b/README.md index 934d021..8212cf0 100644 --- a/README.md +++ b/README.md @@ -44,8 +44,8 @@ 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 (by the type: an unpaged read does not compile); 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 (`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 - - `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. `preview` - the projection. `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 + - `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. `preview` - the projection. `sendGuarded` - a batch as a compare-and-set on each asset's Moment (read just before, or passed in as the one a person saw); an asset someone changed in between comes back in `conflicts`, untouched. It cannot see a change that makes no new version of the asset, such as a child added to it + - `batch.run(commands, { guard })` / `batch.reversible` - preview, snapshot, (confirm,) send (guarded or not: `guard` has no default), 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, 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 @@ -54,7 +54,7 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `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) - `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 +- Errors: everything thrown is an `ApiError` with a `kind` (`auth`, `forbidden`, `notFound`, `invalid`, `transient`, `aborted`, `commandFailure`, `conflict`, `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 })`); `TypeCache.fromMetamodel(metamodel)` seeds one so nothing is loaded - `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 - 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 diff --git a/specs/000-layers.md b/specs/000-layers.md index 470ead9..03b72ba 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -212,24 +212,36 @@ answer (thrown for reads and with throwOnFailure); a disagreement with no such failure is an error of its own. The guard (`services/guard`) is what makes a write batch safe to resend: -each per-asset command of the server's projection is sent scoped to its -ID and the ChangeDate read just before, so a stale or repeated command -matches nothing. ChangeDate goes in the filter as a literal — the one -exception to "values travel as `with` variables", because a ChangeDate -variable never compares equal — after a strict timestamp check. Moment is -not a stamp: a filter on an earlier Moment selects the asset as it was then. -A guarded batch with no creates is sent idempotent; a plain one never is. -Two commands on one asset are sent in passes: the second goes only if the -first applied, guarded on the ChangeDate read just after it (a shared -pre-batch stamp would make the second match nothing). A reverse batch -reactivates a closed asset before deleting it, since Agility refuses to -delete a closed asset. +each per-asset command of the server's projection is sent scoped to the +asset at the Moment read just before (`where { ID, Moment }`) and to that +version still being the current one (`filter RetireDateUTC=''`), so a stale +or repeated command matches nothing. The two terms always travel together: +a Moment alone selects the asset as it was then, and a write scoped by it +lands on the current asset; the filter alone is a server error. Both values +are `with` variables, like every value. A command that matched lists its +asset in the response even when it changed no value, so an asset the +response does not list, and that no failure names, matched nothing: a +**conflict** (`conflicts`, or a `ConflictError` with `throwOnFailure`), +never a success and never confused with a no-op. A caller may supply the +moment it read earlier, with the row a person is looking at; the guard then +compares against what they saw. What the guard cannot see is a change that +makes no new version of the asset (a child added to it): it protects an +asset's own attributes. A guarded batch with no creates is sent +idempotent; a plain one never is. Two commands on one asset are sent in +passes: the second goes only if the first applied, guarded on the Moment +read just after it (the response does not say the new moment, and a shared +pre-batch stamp would make the second match nothing). `batch.run` takes +`guard: true | false` with no default: which one a batch wants is the +caller's decision. A receipt records Moments (`receipt: 2`); one from +before that cannot be checked for drift and is refused unless forced. A +reverse batch reactivates a closed asset before deleting it, since Agility +refuses to delete a closed asset. ## 7. One error, one kind Everything the SDK throws is an `ApiError` (`src/core/errors.ts`), and every `ApiError` has a `kind`: `auth`, `forbidden`, `notFound`, `invalid`, -`transient`, `aborted`, `commandFailure`, `protocol`, `usage` or +`transient`, `aborted`, `commandFailure`, `conflict`, `protocol`, `usage` or `unknown`. `status` and `code` say what happened; `kind` says what to do. A mistake the SDK catches before any request (an unpaged read, an empty batch, a bad OID token) is a `UsageError` (`kind: "usage"`, `status: 0`), diff --git a/src/client.ts b/src/client.ts index 1f0afee..2385224 100644 --- a/src/client.ts +++ b/src/client.ts @@ -309,11 +309,18 @@ export class AgilityApiClient { /** * Send as a compare-and-set: each asset is changed only if nobody has - * changed it since the preview read it; the rest come back `skipped`. - * Throws UnguardableError, before any request, for shapes it cannot - * cover. + * changed it since it was read. The result is a plain send's Outcome + * plus `conflicts`: the assets whose command matched nothing, because + * someone changed them (or they are gone); nothing was applied to those. + * By default the moment is read just before the send; pass `moments` + * to guard on the version a person saw earlier (select `Moment` with the + * row you show, keep it, pass it here). With `throwOnFailure` a failed + * command throws a CommandFailureError and a conflict a ConflictError + * (kind "conflict"). Throws UnguardableError, before any write, for + * shapes it cannot cover. What it cannot see: a change that makes no new + * version of the asset, such as a child added to it. */ - async sendGuarded(commands: assetApi.Command[], options?: Pick): Promise> { + async sendGuarded(commands: assetApi.Command[], options?: Omit): Promise> { await this.schema.ensureFor(commands); return guard.sendGuarded(this.transport, commands, { ...options, lookup: this.schema }); } @@ -330,13 +337,14 @@ export class AgilityApiClient { /** * A batch with a record: preview, snapshot what it overwrites, (confirm,) - * send guarded, and a receipt with created/touched/skipped assets and a - * reverse batch. `reversible` drops from a receipt's reverse the assets - * changed since, unless forced. + * send — guarded or not, as `guard` says; it has no default — and a + * receipt with the created, touched and conflicting assets and a reverse + * batch. `reversible` drops from a receipt's reverse the assets changed + * since, unless forced. */ readonly batch = { - run: (commands: assetApi.Command[], options?: batch.BatchOptions) => batch.runBatch(this.transport, this.schema, commands, options), - reversible: (receipt: Pick, options?: { force?: boolean }) => batch.reversible(this.transport, receipt, options) + run: (commands: assetApi.Command[], options: batch.BatchOptions) => batch.runBatch(this.transport, this.schema, commands, options), + reversible: (receipt: Parameters[1], options?: { force?: boolean }) => batch.reversible(this.transport, receipt, options) }; /** diff --git a/src/core/errors.ts b/src/core/errors.ts index 4e8d4bd..2d2544a 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -10,12 +10,14 @@ * transient no answer, or a 5xx/408/429: the same request may succeed later * aborted the caller's signal ended it * commandFailure api/asset answered 200 with failed commands inside (CommandFailureError) + * conflict a guarded write found the asset changed since it was read (ConflictError): + * nothing was applied to it; read it again and decide * protocol the server answered something the SDK cannot read * usage a mistake caught before any request (UsageError): nothing was sent, so * do not blame the server — fix the call (status is 0 here) * unknown none of the above */ -export type ErrorKind = "auth" | "forbidden" | "notFound" | "invalid" | "transient" | "aborted" | "commandFailure" | "protocol" | "usage" | "unknown"; +export type ErrorKind = "auth" | "forbidden" | "notFound" | "invalid" | "transient" | "aborted" | "commandFailure" | "conflict" | "protocol" | "usage" | "unknown"; /** The kind an HTTP status and an SDK code imply. A code wins over a status. */ export function kindOf(status: number, code?: string): ErrorKind { @@ -27,6 +29,8 @@ export function kindOf(status: number, code?: string): ErrorKind { case "BAD_RESPONSE": return "protocol"; case "USAGE": return "usage"; case "COMMAND_FAILURE": return "commandFailure"; + case "CONFLICT": return "conflict"; + case "RECEIPT_VERSION": return "usage"; case "QUERY_REJECTED": case "TOO_LARGE": return "invalid"; case "NOT_FOUND": return "notFound"; diff --git a/src/index.ts b/src/index.ts index 6c50e1c..7581f4c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -38,7 +38,7 @@ export { AttachmentUploadError, INLINE_LIMIT } 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"; -export type { GuardedResult, Unguardable } from "./services/guard"; -export { BatchRecordError, BatchSendError, INVERSE, describe as describeBatch, namesOf, reverseOf, reversible, runBatch, snapshot } from "./services/batch"; -export type { BatchOptions, Described, NameLookupFailure, Named, Receipt, Reverse } from "./services/batch"; +export { ConflictError, UNGUARDABLE_TYPES, UnguardableError, guard, sendGuarded, stampsOf, touchedBy, unguardable } from "./services/guard"; +export type { GuardedOptions, GuardedResult, Unguardable, UnguardableCode } from "./services/guard"; +export { BatchRecordError, BatchSendError, ReceiptVersionError, isReceipt, INVERSE, describe as describeBatch, namesOf, reverseOf, reversible, runBatch, snapshot } from "./services/batch"; +export type { BatchOptions, Described, Drifted, NameLookupFailure, Named, Receipt, Reverse } from "./services/batch"; diff --git a/src/services/batch.ts b/src/services/batch.ts index 696f6e8..d258e64 100644 --- a/src/services/batch.ts +++ b/src/services/batch.ts @@ -29,7 +29,8 @@ import type { AssetTypeToken } from "../types/metamodel"; import { momentless, typeOfOid } from "../types/oid"; import * as assetApi from "../wire/assetApi"; import type { Command, CommandValue } from "../wire/assetApi"; -import { aliased, guard, GuardedPassError, passesOf, sendPasses, stampsOf, touchedBy, unguardable, UnguardableError } from "./guard"; +import { ApiError } from "../core/errors"; +import { aliased, conflictsOf, guard, GuardedPassError, oidOfSent, passesOf, sendPasses, touchedBy, unguardable, UnguardableError, UNGUARDABLE_TYPES } from "./guard"; import type { Schema } from "./schema"; /** OIDs per lookup query: bounded, never one giant filter. */ @@ -122,12 +123,12 @@ export async function namesOf(transport: Transport, schema: Schema, oids: Iterab return out; } -/** The values about to be overwritten: each update's named attributes, each execute's AssetState, and every touched asset's ChangeDate. */ +/** The values about to be overwritten: each update's named attributes, each execute's AssetState, and every touched asset's Moment (what the guard compares) and ChangeDate (the same instant, readable). Ideas types have neither and are not asked. */ export async function snapshot(transport: Transport, described: Described): Promise>> { const wanted = new Map>(); const want = (oid: Oid, attrs: string[]) => { const s = wanted.get(oid) ?? new Set(); attrs.forEach((a) => s.add(a)); wanted.set(oid, s); }; - for (const u of described.updates) want(u.oid, [...Object.keys(u.attributes), "ChangeDate"]); - for (const e of described.executes) want(e.oid, ["AssetState", "ChangeDate"]); + for (const u of described.updates) want(u.oid, [...Object.keys(u.attributes), "Moment", "ChangeDate"]); + for (const e of described.executes) want(e.oid, ["AssetState", "Moment", "ChangeDate"]); const before: Record> = {}; for (const [type, oids] of byType(wanted.keys())) { const select = [...new Set(oids.flatMap((o) => [...wanted.get(o)!]))]; @@ -267,7 +268,8 @@ export function reverseOf(described: Described, before: Record; snapshotAt?: string; - /** Before values per touched asset, ChangeDate included: what the guard compared and the reverse restores. */ + /** Before values per touched asset: what the reverse restores, with the asset's Moment and its ChangeDate (the same instant, readable) at the snapshot. */ before: Record>; - /** Was the batch sent? False for a preview, a declined confirm, or nothing to do. */ + /** Was the batch sent? False for a dry run, a declined confirm, or nothing to do: `stopped` says which. */ sent: boolean; + /** Why nothing was sent: the batch does nothing, `dryRun` was asked, or `confirm` answered false. Null when it was sent (or the send was attempted). */ + stopped: "nothing" | "dryRun" | "declined" | null; guarded: boolean; + /** The Moment each touched asset was guarded on (empty when not guarded). */ + stamps: Record; /** The batch as sent (the guarded projection, or the request as written). */ sentCommands?: Command[]; sentAt?: string; @@ -287,10 +293,17 @@ export interface Receipt { outcome?: assetApi.Outcome; created: ({ alias: string | null; type: string; oid: Oid } & Named)[]; touched: ({ oid: Oid } & Named)[]; - /** ChangeDate of everything the batch touched, just after it: the stamp a later reverse checks for drift. */ + /** Moment of everything the batch touched, just after it: the stamp a later reverse checks for drift. */ after: Record; - /** Touched assets the guard left alone: changed or gone since the snapshot. Not the ones whose command failed: those are in `failed`. */ - skipped: Oid[]; + /** ChangeDate of the same assets at the same read: `after`, readable, for a message. */ + changedAt: Record; + /** + * Touched assets whose guarded command matched nothing: changed by + * someone since the snapshot, or gone. Nothing was applied to them. Not + * the ones whose command failed (those are in `failed`), and not one + * whose command matched and changed no value (that is a success). + */ + conflicts: Oid[]; /** Touched assets whose command the server reports as failed (outcome.failures says why). */ failed: Oid[]; /** Per asset the batch closes (Inactivate, QuickClose): its open descendants at the snapshot, top down. */ @@ -329,8 +342,13 @@ export class BatchSendError extends WrappedError { } export interface BatchOptions { - /** Send as a compare-and-set (default). An unguardable batch then throws UnguardableError before any request; pass false to send it as written. */ - guard?: boolean; + /** + * Required, no default: true sends the batch as a compare-and-set (an + * unguardable batch then throws UnguardableError before any request); + * false sends it as written, overwriting whatever is there. Which one a + * batch wants is the caller's decision to make, every time. + */ + guard: boolean; /** Stop after the snapshot and send nothing: the receipt says what would happen. */ dryRun?: boolean; /** Asked after the snapshot, before the send, with the touched assets' names on the receipt; false sends nothing. */ @@ -340,11 +358,12 @@ export interface BatchOptions { const now = (): string => new Date().toISOString(); /** Preview, describe, name, snapshot, (confirm,) send, receipt. */ -export async function runBatch(transport: Transport, schema: Schema, commands: Command[], options: BatchOptions = {}): Promise { - const useGuard = options.guard ?? true; +export async function runBatch(transport: Transport, schema: Schema, commands: Command[], options: BatchOptions): Promise { + if (typeof options?.guard !== "boolean") throw new UsageError("batch.run needs `guard: true` (compare-and-set) or `guard: false` (send as written): there is no default"); + const useGuard = options.guard; if (!commands.length) throw new UsageError("the batch is empty"); const refused = unguardable(commands); - const fatal = refused.filter((r) => r.reason.includes("rejected by the server")); + const fatal = refused.filter((r) => r.code === "bareAliasFrom"); if (fatal.length || (useGuard && refused.length)) throw new UnguardableError(useGuard ? refused : fatal); const notes: string[] = []; @@ -355,16 +374,16 @@ export async function runBatch(transport: Transport, schema: Schema, commands: C const described = describe(commands, projected); const touched = touchedBy(projected); const names = await namesOf(transport, schema, touched, noteFailure); - const receipt: Receipt = { receipt: 1, request: commands, previewedAt, preview: projected, described, names: Object.fromEntries(names), before: {}, sent: false, guarded: false, created: [], touched: [], after: {}, skipped: [], failed: [], openDescendants: {}, cascaded: {}, reverse: { commands: [], notes: [] }, notes }; + const receipt: Receipt = { receipt: 2, request: commands, previewedAt, preview: projected, described, names: Object.fromEntries(names), before: {}, sent: false, stopped: null, guarded: false, stamps: {}, created: [], touched: [], after: {}, changedAt: {}, conflicts: [], failed: [], openDescendants: {}, cascaded: {}, reverse: { commands: [], notes: [] }, notes }; const nothing = !described.creates.length && !described.updates.length && !described.executes.length && !described.queries.length && !described.deferred.length; - if (nothing) return receipt; + if (nothing) return { ...receipt, stopped: "nothing" }; for (const d of described.deferred) notes.push(`command ${d.index} (${d.alias}): an aliased ${d.kind}, which preview does not expand; sent as written, not snapshotted, not reversible`); receipt.snapshotAt = now(); receipt.before = await snapshot(transport, described); const closing = described.executes.filter((e) => CASCADING.has(e.op)).map((e) => e.oid); if (closing.length) receipt.openDescendants = await openDescendantsOf(transport, schema, closing); - if (options.dryRun) return receipt; - if (options.confirm && !(await options.confirm(receipt))) return receipt; + if (options.dryRun) return { ...receipt, stopped: "dryRun" }; + if (options.confirm && !(await options.confirm(receipt))) return { ...receipt, stopped: "declined" }; let unstamped: Oid[] = []; receipt.guarded = useGuard; @@ -374,7 +393,8 @@ export async function runBatch(transport: Transport, schema: Schema, commands: C if (useGuard) { // Guarded pass by pass: a second command on the same asset (Reactivate // then Delete in a reverse) goes only if the first applied (guard.ts). - const stamps = Object.fromEntries(Object.entries(receipt.before).flatMap(([oid, v]) => (typeof v.ChangeDate === "string" ? [[oid, v.ChangeDate]] : []))); + const stamps = Object.fromEntries(Object.entries(receipt.before).flatMap(([oid, v]) => (v.Moment != null ? [[oid, String(v.Moment)]] : []))); + receipt.stamps = stamps; receipt.sentCommands = guard(passesOf(projected)[0]!, stamps).commands; // what the first pass sends; replaced below by everything sent const result = await sendPasses(transport, projected, stamps); ({ outcome: done, unstamped } = result); @@ -403,13 +423,8 @@ export async function runBatch(transport: Transport, schema: Schema, commands: C // A failed command names its asset in what was sent: the guard's // with.$oid, or the from of a per-asset command sent as written. const sentAs = receipt.sentCommands ?? []; - const oidOfSent = (i: number | null): Oid | null => { - const body = i === null ? undefined : (sentAs[i] ? bodyOf(sentAs[i]!) : undefined); - const id = (body?.with as { $oid?: unknown } | undefined)?.$oid ?? body?.from; - return typeof id === "string" && id.includes(":") ? momentless(id) : null; - }; - receipt.failed = [...new Set(done.failures.map((f) => oidOfSent(f.index)).filter((oid): oid is Oid => !!oid && touched.includes(oid) && !hit.includes(oid)))]; - receipt.skipped = useGuard ? [...new Set([...unstamped, ...touched.filter((oid) => !hit.includes(oid) && !receipt.failed.includes(oid))])] : []; + receipt.failed = [...new Set(done.failures.map((f) => (f.index === null ? null : oidOfSent(sentAs[f.index]))).filter((oid): oid is Oid => !!oid && touched.includes(oid) && !hit.includes(oid)))]; + receipt.conflicts = useGuard ? conflictsOf(touched, done, sentAs, unstamped) : []; // What each type can do, from the definitions already loaded (or loadable): // an unknown answer keeps the command, as before. for (const type of new Set([...done.created, ...hit].map((oid) => typeOfOid(momentless(oid))))) await schema.load(type).catch(() => null); @@ -434,7 +449,9 @@ export async function runBatch(transport: Transport, schema: Schema, commands: C receipt.touched = receipt.touched.map((t) => (names.has(t.oid) ? t : { ...t, ...(more.get(t.oid) ?? unnamed) })); // The cascade's descendants too: a later reverse reopens them, and checks them for changes first. const all = [...new Set([...done.created, ...hit, ...Object.values(receipt.cascaded).flat()])]; - receipt.after = all.length ? await stampsOf(transport, all) : {}; + const versions = all.length ? await versionsOf(transport, all) : {}; + receipt.after = Object.fromEntries(Object.entries(versions).map(([oid, v]) => [oid, v.moment])); + receipt.changedAt = Object.fromEntries(Object.entries(versions).flatMap(([oid, v]) => (v.changedAt ? [[oid, v.changedAt]] : []))); } catch (error) { throw new BatchRecordError(error, receipt); } @@ -456,20 +473,59 @@ async function statesOf(transport: Transport, oids: Oid[]): Promise state === "Closed" || state === "128"; +/** Each asset's current Moment and ChangeDate (the same instant, readable), one bounded query per type and chunk. An asset that no longer exists, or of a type with no Moment, is absent. */ +async function versionsOf(transport: Transport, oids: Oid[]): Promise> { + const out: Record = {}; + for (const [type, list] of byType(oids)) { + if (UNGUARDABLE_TYPES.includes(type)) continue; + for (const part of chunks(list)) { + const rows = await assetApi.query(transport, { from: type, select: ["Moment", "ChangeDate"], filter: ["ID=$oids"], with: { $oids: part }, page: { size: part.length, start: 0 } }); + for (const r of rows) if (r.Moment != null) out[momentless(r._oid)] = { moment: String(r.Moment), changedAt: r.ChangeDate == null ? null : String(r.ChangeDate) }; + } + } + return out; +} + /** - * A receipt's reverse batch, minus the assets someone changed since the - * batch (their ChangeDate is no longer the one recorded just after it), + * A receipt in a format this version cannot check for drift: `receipt: 1` + * (before 1.0.0-alpha.8) recorded ChangeDates, and the guard now compares + * Moments. Its reverse can still be sent with `force`, which checks + * nothing; or run the batch again and keep the new receipt. + */ +export class ReceiptVersionError extends ApiError { + constructor(readonly receiptVersion: unknown, readonly targets: Oid[]) { + super(`this receipt is in format ${JSON.stringify(receiptVersion)}, from before 1.0.0-alpha.8: it recorded ChangeDates, and assets are now checked by Moment, so it cannot be checked for changes made since. Reverse it with force (no check: later changes are overwritten), or run the batch again and keep the new receipt.`, 0, "RECEIPT_VERSION", { receiptVersion, targets }, "usage"); + this.name = "ReceiptVersionError"; + } +} + +/** Is this value a receipt this version reads (`receipt: 2`)? For a receipt read back from a file. */ +export const isReceipt = (value: unknown): value is Receipt => !!value && typeof value === "object" && (value as { receipt?: unknown }).receipt === 2 && typeof (value as Receipt).reverse === "object"; + +/** An asset a reverse leaves alone because someone changed it since the batch: its Moment then and now (null: gone), and the same as readable times when known. */ +export interface Drifted { oid: Oid; was: string; now: string | null; wasChangedAt: string | null; nowChangedAt: string | null } + +/** + * A receipt's reverse batch, minus the assets someone changed since + * the batch (their Moment is no longer the one recorded just after it), * unless `force`. Send what it returns with runBatch like any batch. * + * A receipt from before 1.0.0-alpha.8 (`receipt: 1`) cannot be checked and + * throws a ReceiptVersionError (code RECEIPT_VERSION) unless `force`, which + * then checks nothing. + * * Agility refuses to Delete a closed asset (Violation'AssetCannotDeleteClosed), * so a Delete of an asset that is closed now gets a Reactivate just before * it: two commands on one asset, which runBatch sends in two guarded passes * (the Delete only if the Reactivate applied). `reactivated` lists them. */ -export async function reversible(transport: Transport, receipt: Pick, options: { force?: boolean } = {}): Promise<{ commands: Command[]; drifted: { oid: Oid; was: string; now: string | null }[]; reactivated: Oid[] }> { +export async function reversible(transport: Transport, receipt: Pick & { receipt?: unknown; changedAt?: Record }, options: { force?: boolean } = {}): Promise<{ commands: Command[]; drifted: Drifted[]; reactivated: Oid[] }> { const targets = receipt.reverse.commands.map((c) => momentless(String(bodyOf(c).from))); - const now = await stampsOf(transport, targets.filter((oid) => receipt.after[oid] !== undefined)); - const drifted = targets.flatMap((oid) => (receipt.after[oid] !== undefined && now[oid] !== receipt.after[oid] ? [{ oid, was: receipt.after[oid]!, now: now[oid] ?? null }] : [])); + const current = receipt.receipt === 2; + if (!current && !options.force) throw new ReceiptVersionError(receipt.receipt, targets); + // An old receipt's stamps are not Moments: with force there is nothing to compare, and nothing is. + const now = current ? await versionsOf(transport, targets.filter((oid) => receipt.after[oid] !== undefined)) : {}; + const drifted: Drifted[] = current ? targets.flatMap((oid) => (receipt.after[oid] !== undefined && now[oid]?.moment !== receipt.after[oid] ? [{ oid, was: receipt.after[oid]!, now: now[oid]?.moment ?? null, wasChangedAt: receipt.changedAt?.[oid] ?? null, nowChangedAt: now[oid]?.changedAt ?? null }] : [])) : []; const skip = new Set(options.force ? [] : drifted.map((d) => d.oid)); const kept = receipt.reverse.commands.filter((c) => !skip.has(momentless(String(bodyOf(c).from)))); const deletes = kept.flatMap((c) => (bodyOf(c).execute === "Delete" ? [momentless(String(bodyOf(c).from))] : [])); diff --git a/src/services/guard.ts b/src/services/guard.ts index 19c9658..7e40067 100644 --- a/src/services/guard.ts +++ b/src/services/guard.ts @@ -1,36 +1,51 @@ /** * The guard: an api/asset batch sent as a compare-and-set, so a change only - * lands on an asset nobody else has changed since it was read. Ported from - * the CLI consumer's batch `guarded()`, with a different stamp. + * lands on an asset nobody else has changed since it was read. * * How: preview the batch (the server's projection expands every query- * scoped update and execute into one command per asset), read each touched - * asset's ChangeDate, and send each per-asset command as a query-scoped one - * filtered on its ID and that ChangeDate. An asset changed in between has a - * newer ChangeDate, matches nothing, and is left alone; the response's - * modified/operated lists say which assets the batch actually touched, so - * the rest are `skipped`. + * asset's Moment (or take the one the caller read earlier, with the row a + * person is looking at), and send each per-asset command scoped to that + * version of the asset and to its still being the current one: * - * The stamp, settled live on 2026-11-04 (test/integration/guard.test.ts): - * - ChangeDate as a filter LITERAL is a true compare-and-set: the value - * just read matches, a stale one matches nothing, and resending the same - * guarded batch writes nothing the second time. - * - ChangeDate as a `with` VARIABLE never matches, not even the value just - * read back — so this is the one place a value is spliced into filter - * text. It is the server's own timestamp, checked against a strict date - * pattern first, so it cannot carry grammar. The ID stays a variable. - * - Moment is NOT a stamp: `Moment=` - * selects the asset as it was then (as-of), and an update scoped by it - * lands on the current asset. A Moment guard guards nothing. Proven for - * writes on 2026-11-11: an update filtered on a stale Moment previews as - * one command and applies, overwriting the change made in between - * ("why not Moment, on a write"; versionone/VersionOne.SDK.JavaScript#51). - * Every type has ChangeDate except the Ideas product's (Idea*), which keeps - * no history and cannot be guarded. + * { from: "Story", where: { ID: "$oid", Moment: "$moment" }, + * filter: ["RetireDateUTC=''"], with: { $oid, $moment }, update | execute } + * + * `Moment` in a query selects the asset AS IT WAS at that moment, so alone + * it guards nothing: an update scoped by a stale Moment lands on the + * current asset. Every version but the current one has a RetireDateUTC, so + * the filter keeps the version only while it is current. Together they are + * exact. Settled live on 2026-11-26 (test/integration/guard.test.ts, and + * issue #51 of this repository): + * - the current moment matches and applies; a stale one matches nothing + * (query, preview and send alike), and resending a command that applied + * applies nothing; + * - a moment in the future, or between two of the asset's versions, and a + * deleted asset's last moment, match nothing; a closed asset is guardable; + * - Moment travels as a `with` variable like any value. + * What the server does that shapes this module: + * - A command that MATCHED lists its asset in the response even when no + * value changed (and makes no new version). So an asset in neither + * modified nor operated, with no failure of its own, matched nothing: + * that is a conflict, and a no-op is never mistaken for one. + * - The response's OID tokens carry no moment, so a second command on + * the same asset needs the moment read again (the passes below). + * - `RetireDateUTC=''` WITHOUT a Moment, and a Moment that is not a + * number, are server errors (HTTP 500). Both terms are always sent + * together and the moment is checked to be digits first. + * + * The blind spot, which no version stamp can close: a change that makes no + * new version of the asset is invisible. Adding a child Task to a Story + * changes the Story's Children and leaves its Moment (and ChangeDate) as + * they were. The guard protects an asset's own attributes, not what other + * assets say about it. + * + * The Ideas product's types (Idea*) keep no history and have no Moment; + * nothing of theirs can be guarded. * * A guarded batch without creates is safe to send twice — an applied - * command has advanced the ChangeDate, so a resend matches nothing — and is - * sent marked idempotent (spec 000 §6). + * command has advanced the Moment, so a resend matches nothing — and is + * sent marked idempotent (spec 000 section 6). */ import { ApiError, UsageError, WrappedError } from "../core/errors"; import type { Transport } from "../core/transport"; @@ -40,14 +55,23 @@ import { momentless, typeOfOid } from "../types/oid"; import * as assetApi from "../wire/assetApi"; import type { Command, CommandValue, ExecuteBody } from "../wire/assetApi"; -/** OIDs per ChangeDate read: bounded, never one giant filter. */ +/** OIDs per Moment read: bounded, never one giant filter. */ export const CHUNK = 100; -/** Types with no ChangeDate (the Ideas product keeps no history): nothing of theirs can be guarded. */ +/** Types with no Moment (the Ideas product keeps no history): nothing of theirs can be guarded. */ export const UNGUARDABLE_TYPES: readonly AssetTypeToken[] = ["Idea", "IdeaChangeSet", "IdeaStatus", "IdeaComment", "IdeaCategory", "IdeaForum", "IdeaUser"]; -/** Why a command cannot be sent guarded, by its index in the batch. */ -export interface Unguardable { index: number; reason: string } +/** + * Why a command cannot be sent guarded: + * aliasedWrite an aliased update or execute: preview does not expand it + * bareAliasFrom a bare update or execute from an alias: the server rejects it, guarded or not + * inlineCreate an update that creates assets inline: the projection normalises the creates away + * noMoment an asset of a type that keeps no history (Idea*) + */ +export type UnguardableCode = "aliasedWrite" | "bareAliasFrom" | "inlineCreate" | "noMoment"; + +/** Why a command cannot be sent guarded, by its index in the batch (-1 for an asset the preview found). Branch on `code`; `reason` is for a person. */ +export interface Unguardable { index: number; code: UnguardableCode; reason: string } /** A batch the guard will not send, rather than send unguarded without saying so. */ export class UnguardableError extends UsageError { @@ -79,9 +103,9 @@ export function unguardable(commands: Command[]): Unguardable[] { const a = aliased(c); const body = bodyOf(c); const writes = "update" in body || "execute" in body; - if (a && writes) out.push({ index, reason: `${a.alias} is an aliased ${"update" in body ? "update" : "execute"}: preview does not expand it, so it cannot be read or guarded per asset` }); - else if (!a && writes && typeof body.from === "string" && body.from.startsWith("@")) out.push({ index, reason: `a bare update or execute from an alias (${body.from}) is rejected by the server; alias the command itself` }); - if (isObject(body.update) && Object.values(body.update).some(isCreateValue)) out.push({ index, reason: "an update that creates assets inline: the projection normalises the creates away" }); + if (a && writes) out.push({ index, code: "aliasedWrite", reason: `${a.alias} is an aliased ${"update" in body ? "update" : "execute"}: preview does not expand it, so it cannot be read or guarded per asset` }); + else if (!a && writes && typeof body.from === "string" && body.from.startsWith("@")) out.push({ index, code: "bareAliasFrom", reason: `a bare update or execute from an alias (${body.from}) is rejected by the server; alias the command itself` }); + if (isObject(body.update) && Object.values(body.update).some(isCreateValue)) out.push({ index, code: "inlineCreate", reason: "an update that creates assets inline: the projection normalises the creates away" }); }); return out; } @@ -100,10 +124,10 @@ export const touchedBy = (projected: Command[]): Oid[] => [...new Set(projected. // ---- the stamp ----------------------------------------------------------------- -/** A ChangeDate as the server writes it: 2026-11-04T16:49:40.12 (trailing zeros trimmed, no zone). */ -const STAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,7})?$/; +/** A Moment as the server writes it: digits. Anything else must never reach a query (the server answers a non-number with a 500). */ +const MOMENT = /^\d+$/; -/** Each asset's current ChangeDate, one bounded query per type and chunk. An asset that no longer exists is absent. */ +/** Each asset's current Moment, one bounded query per type and chunk. An asset that no longer exists is absent. */ export async function stampsOf(transport: Transport, oids: readonly Oid[]): Promise> { const byType = new Map(); for (const oid of new Set(oids.map(momentless))) { const t = typeOfOid(oid); byType.set(t, [...(byType.get(t) ?? []), oid]); } @@ -112,8 +136,8 @@ export async function stampsOf(transport: Transport, oids: readonly Oid[]): Prom if (UNGUARDABLE_TYPES.includes(type)) continue; for (let i = 0; i < list.length; i += CHUNK) { const part = list.slice(i, i + CHUNK); - const rows = await assetApi.query(transport, { from: type, select: ["ChangeDate"], filter: ["ID=$oids"], with: { $oids: part }, page: { size: part.length, start: 0 } }); - for (const r of rows) if (r.ChangeDate != null) out[momentless(r._oid)] = String(r.ChangeDate); + const rows = await assetApi.query(transport, { from: type, select: ["Moment"], filter: ["ID=$oids"], with: { $oids: part }, page: { size: part.length, start: 0 } }); + for (const r of rows) if (r.Moment != null) out[momentless(r._oid)] = String(r.Moment); } } return out; @@ -121,9 +145,10 @@ export async function stampsOf(transport: Transport, oids: readonly Oid[]): Prom /** * The batch to send: the projection, each per-asset update or execute - * rewritten as a query-scoped command on its ID and ChangeDate. Creates and - * queries pass through as the projection echoed them. An asset with no - * stamp (gone since the preview) is left out and reported as skipped. + * rewritten as a command on that asset at its moment, while that version + * is current. Creates and queries pass through as the projection echoed + * them. An asset with no stamp (gone since the preview) is left out and + * reported as a conflict. */ export function guard(projected: Command[], stamps: Readonly>): { commands: Command[]; unstamped: Oid[] } { const commands: Command[] = [], unstamped: Oid[] = []; @@ -132,9 +157,9 @@ export function guard(projected: Command[], stamps: Readonly if (!x) { commands.push(p); continue; } const stamp = stamps[x.oid]; if (stamp === undefined) { unstamped.push(x.oid); continue; } - if (!STAMP.test(stamp)) throw new ApiError(`${x.oid}: ChangeDate ${JSON.stringify(stamp)} is not a timestamp; refusing to put it in a filter`, 200, "BAD_RESPONSE", { oid: x.oid, stamp }); - // The literal is deliberate: as a `with` variable a ChangeDate never compares equal (see above). - const scope = { from: typeOfOid(x.oid), filter: ["ID=$oid", `ChangeDate='${stamp}'`], with: { $oid: x.oid } }; + if (!MOMENT.test(stamp)) throw new UsageError(`${x.oid}: ${JSON.stringify(stamp)} is not a Moment (digits); refusing to guard on it`, { oid: x.oid, stamp }); + // Both terms, always: the moment picks the version, the filter requires it to be the current one. + const scope = { from: typeOfOid(x.oid), where: { ID: "$oid", Moment: "$moment" }, filter: ["RetireDateUTC=''"], with: { $oid: x.oid, $moment: stamp } }; commands.push(x.update ? { ...scope, update: x.update } : { ...scope, execute: x.execute as ExecuteBody["execute"] }); } return { commands, unstamped }; @@ -146,9 +171,9 @@ export function guard(projected: Command[], stamps: Readonly * A projection split into passes: the k-th per-asset command for each asset * goes in pass k; creates and queries ride in pass 0. One pass is the usual * case. Two commands on one asset (a reverse batch's Reactivate then Delete, - * say) cannot share a pass: both would be stamped with the ChangeDate read + * say) cannot share a pass: both would be stamped with the Moment read * before the batch, the first would advance it, and the second would match - * nothing — silently skipped. + * nothing — a conflict nobody caused. */ export function passesOf(projected: Command[]): Command[][] { const seen = new Map(); @@ -173,10 +198,11 @@ export class GuardedPassError extends WrappedError { /** * Send a projection guarded, pass by pass. Pass 0 is guarded on `stamps` * (read before the batch). A later pass sends an asset's next command only - * if its previous one applied, guarded on the ChangeDate read again just - * after it — so the chain stays a compare-and-set, with one narrow window - * between our write and that read. An asset whose earlier command was - * skipped is skipped for the rest of the batch. Failure indexes are + * if its previous one applied, guarded on the Moment read again just + * after it (the response does not say the new moment) — so the chain stays + * a compare-and-set, with one narrow window between our write and that + * read. An asset whose earlier command matched nothing is left alone for + * the rest of the batch. Failure indexes are * positions in `sent` (all passes, in order). A send that fails in the * first pass throws as it would alone; in a later pass it throws a * GuardedPassError carrying what the earlier passes did. @@ -220,38 +246,86 @@ export async function sendPasses(transport: Transport // ---- the whole move -------------------------------------------------------------- -export interface GuardedResult { - /** What the batch did: created, modified, operated, failures, query rows. */ - outcome: assetApi.Outcome; - /** The server's projection the guard was built from. */ - projected: Command[]; - /** The batch as sent. */ - sent: Command[]; +/** The asset a sent command addresses: the guard's `with.$oid`, or the `from` of a command sent as written. */ +export function oidOfSent(command: Command | undefined): Oid | null { + const body = command ? bodyOf(command) : undefined; + const id = (body?.with as { $oid?: unknown } | undefined)?.$oid ?? body?.from; + return typeof id === "string" && id.includes(":") ? momentless(id) : null; +} + +/** + * What a guarded batch did: the Outcome of a plain send, plus what the + * guard knows. + */ +export type GuardedResult = assetApi.Outcome & { /** Every asset the projection would update or operate on. */ touched: Oid[]; - /** Each touched asset's ChangeDate when read: the stamp it was guarded on. */ - stamps: Record; /** - * Touched assets the batch left alone: changed or gone since they were - * read — or their command failed, which `outcome.failures` says. + * Touched assets whose command matched nothing: changed by someone since + * the moment they were guarded on, or gone. Nothing was applied to them. + * (An asset whose command matched and failed is in `failures`, not here; + * one whose command matched and changed no value is a success.) */ - skipped: Oid[]; + conflicts: Oid[]; + /** For a log or a receipt: the server's projection, the batch as sent, and the moment each asset was guarded on. */ + details: { projected: Command[]; sent: Command[]; stamps: Record }; +}; + +/** + * A guarded batch in which at least one asset had changed (or gone) since + * the moment it was guarded on. Thrown only when asked (`throwOnFailure`); + * `result` is the whole GuardedResult — what did apply is committed — and + * `conflicts` the assets nothing was applied to. Read the asset again and + * decide: this is "someone else got there first", not a refusal. + */ +export class ConflictError extends ApiError { + readonly conflicts: Oid[]; + readonly result: GuardedResult; + constructor(result: GuardedResult) { + super(`${result.conflicts.join(", ")} changed since ${result.conflicts.length === 1 ? "it was" : "they were"} read; nothing was applied to ${result.conflicts.length === 1 ? "it" : "them"}`, 200, "CONFLICT", result.conflicts, "conflict"); + this.name = "ConflictError"; + this.conflicts = result.conflicts; + this.result = result; + } +} + +export interface GuardedOptions extends Pick { + /** + * Moments the caller already holds, by OID: guard those assets on the + * version the caller saw, not on one read now. Select `Moment` with the + * row you show a person, keep it with what you drew, and pass it when + * they act: a change made in between is then a conflict. Assets not + * named here are read just before the send, as without this option. A + * moment for an asset the batch does not touch is ignored. + */ + moments?: Readonly>; } /** - * Preview, stamp, send guarded. Throws UnguardableError, before any request, - * for a batch the guard cannot cover; send such a batch with assetApi.send, - * knowingly. + * Preview, stamp, send guarded. Throws UnguardableError, before any write, + * for a batch the guard cannot cover (send such a batch with a plain send, + * knowingly). With `throwOnFailure`, a failed command throws a + * CommandFailureError and, when none failed, a conflict throws a + * ConflictError. */ -export async function sendGuarded(transport: Transport, commands: Command[], options: Pick = {}): Promise> { +export async function sendGuarded(transport: Transport, commands: Command[], options: GuardedOptions = {}): Promise> { const refused = unguardable(commands); if (refused.length) throw new UnguardableError(refused); const projected = await assetApi.preview(transport, commands); const touched = touchedBy(projected); const ideas = touched.filter((oid) => UNGUARDABLE_TYPES.includes(typeOfOid(oid))); - if (ideas.length) throw new UnguardableError(ideas.map((oid) => ({ index: -1, reason: `${oid}: ${typeOfOid(oid)} has no ChangeDate` }))); - const stamps = await stampsOf(transport, touched); - const { outcome, sent, unstamped } = await sendPasses(transport, projected, stamps, options); - const done = new Set([...outcome.modified, ...outcome.operated]); - return { outcome, projected, sent, touched, stamps, skipped: [...new Set([...unstamped, ...touched.filter((oid) => !done.has(oid))])] }; + if (ideas.length) throw new UnguardableError(ideas.map((oid) => ({ index: -1, code: "noMoment" as const, reason: `${oid}: ${typeOfOid(oid)} keeps no history and has no Moment` }))); + const given = Object.fromEntries(Object.entries(options.moments ?? {}).map(([oid, m]) => [momentless(oid), String(m)]).filter(([oid]) => touched.includes(oid!))); + const stamps: Record = { ...(await stampsOf(transport, touched.filter((oid) => !(oid in given)))), ...given }; + const { outcome, sent, unstamped } = await sendPasses(transport, projected, stamps, { lookup: options.lookup, throwOnFailure: options.throwOnFailure }); + const result: GuardedResult = { ...outcome, touched, conflicts: conflictsOf(touched, outcome, sent, unstamped), details: { projected, sent, stamps } }; + if (options.throwOnFailure && result.conflicts.length) throw new ConflictError(result); + return result; +} + +/** The touched assets a guarded send applied nothing to and reported no failure for: their command matched nothing. */ +export function conflictsOf(touched: readonly Oid[], outcome: assetApi.Outcome, sent: readonly Command[], unstamped: readonly Oid[]): Oid[] { + const hit = new Set([...outcome.modified, ...outcome.operated].map(momentless)); + const failed = new Set(outcome.failures.flatMap((f) => (f.index === null ? [] : [oidOfSent(sent[f.index])]))); + return [...new Set([...unstamped, ...touched.filter((oid) => !hit.has(oid) && !failed.has(oid))])]; } diff --git a/test/integration/batch.test.ts b/test/integration/batch.test.ts index 25b7218..b86fed9 100644 --- a/test/integration/batch.test.ts +++ b/test/integration/batch.test.ts @@ -34,22 +34,30 @@ describeInstance("batch (live)", () => { const receipt = await client.batch.run([ { from: "Story", filter: ["ID=$ids"], with: { $ids: [a, b] }, update: { Estimate: 5, Owners: { add: [{ _oid: me }] } } }, { "@t": { AssetType: "Task", Name: fixtureName("batch task"), Parent: { _oid: a } } } - ]); + ], { guard: true }); const task = receipt.created[0]!; created.push(task.oid); expect(receipt.sent && receipt.guarded).toBe(true); expect(receipt.outcome!.failures).toEqual([]); - expect(receipt.skipped).toEqual([]); + expect(receipt.conflicts).toEqual([]); expect(task).toMatchObject({ alias: "@t", type: "Task", number: expect.stringMatching(/-\d+$/) }); expect(receipt.touched.map((x) => x.oid).sort()).toEqual([a, b].sort()); expect(receipt.before[a]).toMatchObject({ Estimate: "1", Owners: [] }); expect(receipt.before[b]).toMatchObject({ Estimate: null, Owners: [] }); expect(Object.keys(receipt.after).sort()).toEqual([a, b, task.oid].sort()); + // Stamps are Moments: digits, guarded on the snapshot's, advanced by the batch; the readable time rides beside. + expect(receipt).toMatchObject({ receipt: 2, stopped: null }); + for (const oid of [a, b]) { + expect(receipt.stamps[oid]).toMatch(/^\d+$/); + expect(Number(receipt.after[oid])).toBeGreaterThan(Number(receipt.stamps[oid])); + expect(receipt.changedAt[oid]).toMatch(/^\d{4}-\d{2}-\d{2}T/); + } + expect(receipt.outcome!.requestId).toEqual(expect.any(String)); expect((await read(a)).Estimate).toBe("5"); const { commands, drifted } = await client.batch.reversible(receipt); expect(drifted).toEqual([]); - const undone = await client.batch.run(commands); + const undone = await client.batch.run(commands, { guard: true }); expect(undone.outcome!.failures).toEqual([]); expect(await read(a)).toMatchObject({ Estimate: "1", Owners: [] }); expect(await read(b)).toMatchObject({ Estimate: null, Owners: [] }); @@ -58,7 +66,7 @@ describeInstance("batch (live)", () => { }); it("a reverse skips an asset someone changed since the batch, unless forced", async () => { - const receipt = await client.batch.run([{ from: b, update: { Estimate: 2 } }]); + const receipt = await client.batch.run([{ from: b, update: { Estimate: 2 } }], { guard: true }); await assetApi.send(t, [{ from: b, update: { Estimate: 3 } }], { throwOnFailure: true }); // someone else const { commands, drifted } = await client.batch.reversible(receipt); expect(drifted.map((d) => d.oid)).toEqual([b]); @@ -75,12 +83,13 @@ describeInstance("batch (live)", () => { expect(receipt.outcome!.failures).toEqual([]); expect(receipt.described.deferred).toEqual([{ index: 0, alias: "@close", from: story, kind: "execute" }]); expect(receipt.touched).toEqual([expect.objectContaining({ oid: story, name: expect.stringContaining("batch aliased") })]); - expect(receipt.after[story]).toMatch(/^\d{4}-/); + expect(receipt.after[story]).toMatch(/^\d+$/); + expect(receipt.changedAt[story]).toMatch(/^\d{4}-/); const [row] = await assetApi.query<{ _oid: string; AssetState: string }>(t, { from: story, select: ["AssetState"], page: { size: 1, start: 0 } }); expect(row!.AssetState).toBe("Closed"); }); it("undoing a batch whose created asset was closed since reactivates it first, then deletes it (Agility refuses to delete a closed asset)", async () => { - const receipt = await client.batch.run([{ "@s": { AssetType: "Story", Name: fixtureName("batch undo closed"), Scope: { _oid: "Scope:0" } } }]); + const receipt = await client.batch.run([{ "@s": { AssetType: "Story", Name: fixtureName("batch undo closed"), Scope: { _oid: "Scope:0" } } }], { guard: true }); const story = receipt.created[0]!.oid; created.push(story); await assetApi.send(t, [{ from: story, execute: "QuickClose" }], { throwOnFailure: true }); @@ -88,9 +97,9 @@ describeInstance("batch (live)", () => { const undo = await client.batch.reversible(receipt, { force: true }); expect(undo.reactivated).toEqual([story]); expect(undo.commands).toEqual([{ from: story, execute: "Reactivate" }, { from: story, execute: "Delete" }]); - const reversed = await client.batch.run(undo.commands); + const reversed = await client.batch.run(undo.commands, { guard: true }); expect(reversed.outcome!.failures).toEqual([]); - expect(reversed.skipped).toEqual([]); + expect(reversed.conflicts).toEqual([]); expect(await assetApi.query(t, { from: "Story", select: ["Name"], filter: ["ID=$s"], with: { $s: story }, page: { size: 1, start: 0 } })).toEqual([]); }); @@ -109,7 +118,7 @@ describeInstance("batch (live)", () => { created.push(open, closedBefore); await assetApi.send(t, [{ from: closedBefore, execute: "QuickClose" }], { throwOnFailure: true }); - const receipt = await client.batch.run([{ from: story, execute: op }]); + const receipt = await client.batch.run([{ from: story, execute: op }], { guard: true }); expect(receipt.outcome!.failures).toEqual([]); expect(receipt.openDescendants).toEqual({ [story]: [open] }); expect(await stateOf(open)).toBe("Closed"); // the server's cascade, which the receipt must undo @@ -118,9 +127,9 @@ describeInstance("batch (live)", () => { const { commands, drifted } = await client.batch.reversible(receipt); expect(drifted).toEqual([]); - const undone = await client.batch.run(commands); + const undone = await client.batch.run(commands, { guard: true }); expect(undone.outcome!.failures).toEqual([]); - expect(undone.skipped).toEqual([]); + expect(undone.conflicts).toEqual([]); expect(await stateOf(story)).toBe("Active"); expect(await stateOf(open)).toBe("Active"); expect(await stateOf(closedBefore)).toBe("Closed"); @@ -131,13 +140,13 @@ describeInstance("batch (live)", () => { const receipt = await client.batch.run([ { "@c": { AssetType: "Conversation" } }, { "@e": { AssetType: "Expression", BelongsTo: "@c", Content: fixtureName("reverse conversation") } } - ]); + ], { guard: true }); expect(receipt.outcome!.failures).toEqual([]); const [conversation, expression] = [receipt.created[0]!.oid, receipt.created[1]!.oid]; expect(conversation).toMatch(/^Conversation:/); expect(receipt.reverse.commands).toEqual([{ from: expression, execute: "Delete" }]); expect(receipt.reverse.notes.join("\n")).toMatch(new RegExp(`${conversation}: Conversation has no Delete operation`)); - const undone = await client.batch.run((await client.batch.reversible(receipt)).commands); + const undone = await client.batch.run((await client.batch.reversible(receipt)).commands, { guard: true }); expect(undone.outcome!.failures).toEqual([]); expect(undone.failed).toEqual([]); expect(await assetApi.query(t, { from: "Expression", select: ["Content"], filter: ["ID=$e"], with: { $e: expression }, page: { size: 1, start: 0 } })).toEqual([]); diff --git a/test/integration/guard.test.ts b/test/integration/guard.test.ts index 1a39e55..31abd1f 100644 --- a/test/integration/guard.test.ts +++ b/test/integration/guard.test.ts @@ -1,16 +1,15 @@ import { afterAll, beforeAll, expect, it } from "vitest"; -import { sendGuarded } from "../../src/services/guard"; +import { ConflictError, sendGuarded } from "../../src/services/guard"; import { assetApi } from "../../src/wire"; import { describeInstance, fixtureName, instance } from "./instance"; /** - * The guard against a real instance. Brings its own two Stories (deleted - * afterwards by exact OID): one changed by "someone else" between the - * preview and the send, one not. What only the server can prove: that the - * projection's add/remove form for a scalar applies in a real update, that - * a ChangeDate literal is a true compare-and-set (and a Moment is not, for a - * query or for a write), and - * that a stale guard writes nothing. + * The guard against a real instance. Brings its own Stories (deleted + * afterwards by exact OID). What only the server can prove: that an + * asset's Moment together with RetireDateUTC='' is a true compare-and-set + * (and a Moment alone is not), that a stale guard writes nothing while a + * no-op that matched is a success, that a moment the caller read earlier + * guards against everything since, and what the guard cannot see. */ describeInstance("guard (live)", () => { const t = instance!.transport; @@ -28,59 +27,113 @@ describeInstance("guard (live)", () => { }); afterAll(async () => { for (const oid of created) await assetApi.send(t, [{ from: oid, execute: "Delete" }]); }); - it("an unchanged asset is updated; one changed after it was read is skipped and keeps the other writer's change", async () => { + it("an unchanged asset is updated; one changed after it was read is a conflict and keeps the other writer's change", async () => { // Simulate the race: wrap the transport so "someone else" edits b right after the Moments are read. let reads = 0; const racing = { request: async (o: Parameters[0]) => { const r = await t.request(o); const body = o.body as { select?: string[] }[] | undefined; - if (Array.isArray(body) && body[0]?.select?.[0] === "ChangeDate" && reads++ === 0) await assetApi.send(t, [{ from: b, update: { Estimate: 7 } }], { throwOnFailure: true }); + if (Array.isArray(body) && body[0]?.select?.[0] === "Moment" && reads++ === 0) await assetApi.send(t, [{ from: b, update: { Estimate: 7 } }], { throwOnFailure: true }); return r; } }; const res = await sendGuarded(racing, [{ from: "Story", filter: ["ID=$ids"], with: { $ids: [a, b] }, update: { Estimate: 5 } }]); expect(res.touched.sort()).toEqual([a, b].sort()); - expect(res.skipped).toEqual([b]); - expect(res.outcome.modified).toEqual([a]); + expect(res.conflicts).toEqual([b]); + expect(res.modified).toEqual([a]); + expect(res.failures).toEqual([]); expect(await estimate(a)).toBe("5"); expect(await estimate(b)).toBe("7"); }); - it("sending the same guarded batch twice applies once: the first send advances the ChangeDate the second was stamped with", async () => { + it("sending the same guarded batch twice applies once: the first send advances the Moment the second was stamped with", async () => { const first = await sendGuarded(t, [{ from: a, update: { Estimate: 8 } }]); - const second = await assetApi.send(t, first.sent); - expect(first.outcome.modified).toEqual([a]); + const second = await assetApi.send(t, first.details.sent); + expect(first.modified).toEqual([a]); + expect(first.conflicts).toEqual([]); + expect(first.requestId).toEqual(expect.any(String)); expect(second.assetsModified.count).toBe(0); expect(await estimate(a)).toBe("8"); }); - it("why not Moment: a filter on an earlier Moment of the asset selects it as it was then, so it cannot tell stale from current", async () => { - const [then] = await assetApi.query<{ _oid: string; Moment: string }>(t, { from: a, select: ["Moment"], page: { size: 1, start: 0 } }); - await assetApi.send(t, [{ from: a, update: { Estimate: 9 } }], { throwOnFailure: true }); - const asOf = await assetApi.query<{ _oid: string; Estimate: string }>(t, { from: "Story", select: ["Estimate"], filter: ["ID=$oid", "Moment=$m"], with: { $oid: a, $m: then!.Moment }, page: { size: 1, start: 0 } }); - expect(asOf).toHaveLength(1); // stale, yet it matches — - expect(asOf[0]!.Estimate).toBe("8"); // — as the asset was at that moment + it("a guarded update that changes nothing matched, so it is a success and not a conflict; sent again it is still a success", async () => { + const same = await estimate(a); + for (let i = 0; i < 2; i += 1) { + const res = await sendGuarded(t, [{ from: a, update: { Estimate: Number(same) } }]); + expect(res.modified).toEqual([a]); + expect(res.conflicts).toEqual([]); + } + expect(await estimate(a)).toBe(same); }); - it("why not Moment, on a write: an update filtered on a stale Moment previews as one command and applies, while a stale ChangeDate literal applies nothing", async () => { + it("a moment the caller read earlier guards against everything since: stale is a conflict (thrown when asked), current applies", async () => { + const [seen] = await assetApi.query<{ _oid: string; Moment: string }>(t, { from: b, select: ["Moment"], page: { size: 1, start: 0 } }); + await assetApi.send(t, [{ from: b, update: { Estimate: 11 } }], { throwOnFailure: true }); // someone else, after the row was shown + const stale = await sendGuarded(t, [{ from: b, update: { Estimate: 12 } }], { moments: { [b]: seen!.Moment } }); + expect(stale).toMatchObject({ modified: [], conflicts: [b], details: { stamps: { [b]: seen!.Moment } } }); + expect(await estimate(b)).toBe("11"); + const thrown = (await sendGuarded(t, [{ from: b, update: { Estimate: 12 } }], { moments: { [b]: seen!.Moment }, throwOnFailure: true }).catch((e: unknown) => e)) as ConflictError; + expect(thrown).toBeInstanceOf(ConflictError); + expect(thrown).toMatchObject({ kind: "conflict", conflicts: [b] }); + const [now] = await assetApi.query<{ _oid: string; Moment: string }>(t, { from: b, select: ["Moment"], page: { size: 1, start: 0 } }); + const fresh = await sendGuarded(t, [{ from: b, update: { Estimate: 12 } }], { moments: { [b]: now!.Moment }, throwOnFailure: true }); + expect(fresh).toMatchObject({ modified: [b], conflicts: [] }); + expect(await estimate(b)).toBe("12"); + }); + + it("operations are guarded the same way, a closed asset included; a deleted asset is a conflict", async () => { + const res = await assetApi.send(t, [{ AssetType: "Story", Name: fixtureName("guard ops"), Scope: { _oid: "Scope:0" } }], { throwOnFailure: true }); + const s = assetApi.momentless(res.assetsCreated.oidTokens[0]!); + created.push(s); + const [open] = await assetApi.query<{ _oid: string; Moment: string }>(t, { from: s, select: ["Moment"], page: { size: 1, start: 0 } }); + expect(await sendGuarded(t, [{ from: s, execute: "QuickClose" }])).toMatchObject({ operated: [s], conflicts: [] }); + // The moment from before the close is stale now: reactivating on it does nothing. + expect(await sendGuarded(t, [{ from: s, execute: "Reactivate" }], { moments: { [s]: open!.Moment } })).toMatchObject({ operated: [], conflicts: [s] }); + expect(await sendGuarded(t, [{ from: s, execute: "Reactivate" }])).toMatchObject({ operated: [s], conflicts: [] }); + const [last] = await assetApi.query<{ _oid: string; Moment: string }>(t, { from: s, select: ["Moment"], page: { size: 1, start: 0 } }); + await assetApi.send(t, [{ from: s, execute: "Delete" }], { throwOnFailure: true }); + // Guarded on its last moment before the delete, by a command that still names it: nothing matches. + const gone = await assetApi.send(t, [{ from: "Story", where: { ID: "$oid", Moment: "$moment" }, filter: ["RetireDateUTC=''"], with: { $oid: s, $moment: last!.Moment }, update: { Name: "x" } }]); + expect(gone.assetsModified.count).toBe(0); + expect(gone.commandFailures.count).toBe(0); + }); + + it("why both terms: a Moment alone selects the asset as it was, and a write scoped by it lands on the current asset; with RetireDateUTC='' a stale moment matches nothing", async () => { // Its own Story, so the result doesn't depend on what the tests above did to a and b. const res = await assetApi.send(t, [{ AssetType: "Story", Name: fixtureName("guard moment write"), Scope: { _oid: "Scope:0" }, Estimate: 1 }], { throwOnFailure: true }); const s = assetApi.momentless(res.assetsCreated.oidTokens[0]!); created.push(s); - const [before] = await assetApi.query<{ _oid: string; Moment: string; ChangeDate: string }>(t, { from: s, select: ["Moment", "ChangeDate"], page: { size: 1, start: 0 } }); + const [before] = await assetApi.query<{ _oid: string; Moment: string }>(t, { from: s, select: ["Moment"], page: { size: 1, start: 0 } }); await assetApi.send(t, [{ from: s, update: { Estimate: 2 } }], { throwOnFailure: true }); // "someone else" changes it - expect(await estimate(s)).toBe("2"); + const at = { from: "Story", where: { ID: "$oid", Moment: "$moment" }, with: { $oid: s, $moment: before!.Moment } }; - // Stale Moment, as a literal: the projection still has the asset, and the write lands on the current one. - const staleMoment = [{ from: "Story", filter: ["ID=$oid", `Moment='${before!.Moment}'`], with: { $oid: s }, update: { Estimate: 7 } }]; - expect(await assetApi.preview(t, staleMoment)).toHaveLength(1); - const sent = await assetApi.send(t, staleMoment); - expect(sent.assetsModified.oidTokens.map(assetApi.momentless)).toEqual([s]); - expect(await estimate(s)).toBe("7"); // the other writer's 2 is overwritten: Moment guards nothing - - // Stale ChangeDate, as a literal (what guard.ts sends): matches nothing, so nothing is applied. - const staleStamp = [{ from: "Story", filter: ["ID=$oid", `ChangeDate='${before!.ChangeDate}'`], with: { $oid: s }, update: { Estimate: 9 } }]; - expect(await assetApi.preview(t, staleStamp)).toEqual([]); - expect((await assetApi.send(t, staleStamp)).assetsModified.count).toBe(0); + // The control: the stale moment alone still selects a row — the old version — and its RetireDateUTC is set. + const asOf = await assetApi.query<{ _oid: string; Estimate: string; RetireDateUTC: string | null }>(t, { ...at, select: ["Estimate", "RetireDateUTC"], page: { size: 2, start: 0 } }); + expect(asOf).toHaveLength(1); + expect(asOf[0]!.Estimate).toBe("1"); + expect(asOf[0]!.RetireDateUTC).toEqual(expect.any(String)); + // With the filter: zero rows, an empty projection, nothing written. + const guarded = { ...at, filter: ["RetireDateUTC=''"] }; + expect(await assetApi.query(t, { ...guarded, select: ["Estimate"], page: { size: 2, start: 0 } })).toEqual([]); + expect(await assetApi.preview(t, [{ ...guarded, update: { Estimate: 9 } }])).toEqual([]); + expect((await assetApi.send(t, [{ ...guarded, update: { Estimate: 9 } }])).assetsModified.count).toBe(0); + expect(await estimate(s)).toBe("2"); + // Without it, the same stale moment previews as one command and overwrites the other writer's change. + expect(await assetApi.preview(t, [{ ...at, update: { Estimate: 7 } }])).toHaveLength(1); + expect((await assetApi.send(t, [{ ...at, update: { Estimate: 7 } }])).assetsModified.oidTokens.map(assetApi.momentless)).toEqual([s]); expect(await estimate(s)).toBe("7"); }); + + it("the blind spot: a child added to an asset makes no new version of it, so a guard on the earlier moment still applies", async () => { + const res = await assetApi.send(t, [{ AssetType: "Story", Name: fixtureName("guard blind spot"), Scope: { _oid: "Scope:0" }, Estimate: 1 }], { throwOnFailure: true }); + const s = assetApi.momentless(res.assetsCreated.oidTokens[0]!); + created.push(s); + const read = async () => (await assetApi.query<{ _oid: string; Moment: string; "Children.@Count": string }>(t, { from: s, select: ["Moment", "Children.@Count"], page: { size: 1, start: 0 } }))[0]!; + const before = await read(); + const task = await assetApi.send(t, [{ AssetType: "Task", Name: fixtureName("guard blind spot task"), Parent: s }], { throwOnFailure: true }); + created.unshift(assetApi.momentless(task.assetsCreated.oidTokens[0]!)); // deleted before its Story + const after = await read(); + expect([before["Children.@Count"], after["Children.@Count"]]).toEqual(["0", "1"]); + expect(after.Moment).toBe(before.Moment); + expect(await sendGuarded(t, [{ from: s, update: { Estimate: 2 } }], { moments: { [s]: before.Moment } })).toMatchObject({ modified: [s], conflicts: [] }); + }); }); diff --git a/test/unit/batch.test.ts b/test/unit/batch.test.ts index 3ee3582..1e704f3 100644 --- a/test/unit/batch.test.ts +++ b/test/unit/batch.test.ts @@ -2,7 +2,8 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; import { describe as group, expect, it, vi } from "vitest"; import type { RequestOptions, Transport } from "../../src/core/transport"; -import { BatchRecordError, BatchSendError, describe, reverseOf, reversible, runBatch, type Receipt } from "../../src/services/batch"; +import { UsageError } from "../../src/core/errors"; +import { BatchRecordError, BatchSendError, ReceiptVersionError, describe, isReceipt, reverseOf, reversible, runBatch, type Receipt } from "../../src/services/batch"; import { UnguardableError } from "../../src/services/guard"; import { Schema } from "../../src/services/schema"; import { toMetamodel, type MetamodelDocument } from "../../src/wire/meta"; @@ -43,15 +44,17 @@ const PREVIEW = [ { "@x": { oid: "Epic:9", execute: { op: "Inactivate", args: {} } } } ] as unknown as Command[]; const BEFORE: Record> = { - "Story:1": { _oid: "Story:1:100", Estimate: "3", Owners: [], ChangeDate: "2026-11-04T16:00:00.1" }, - "Story:2": { _oid: "Story:2", Estimate: null, Owners: [{ _oid: "Member:20" }], ChangeDate: "2026-11-04T16:00:00.2" }, - "Epic:9": { _oid: "Epic:9", AssetState: "Active", ChangeDate: "2026-11-04T16:00:00.3" } + "Story:1": { _oid: "Story:1:100", Estimate: "3", Owners: [], Moment: "100", ChangeDate: "2026-11-04T16:00:00.1" }, + "Story:2": { _oid: "Story:2", Estimate: null, Owners: [{ _oid: "Member:20" }], Moment: "200", ChangeDate: "2026-11-04T16:00:00.2" }, + "Epic:9": { _oid: "Epic:9", AssetState: "Active", Moment: "300", ChangeDate: "2026-11-04T16:00:00.3" } }; const NAMES: Record = { "Story:1": { Name: "One", Number: "S-1" }, "Story:2": { Name: "Two", Number: "S-2" }, "Epic:9": { Name: "Nine", Number: "E-9" }, "Task:50": { Name: "new task", Number: "TK-50" } }; -const AFTER: Record = { "Task:50": "2026-11-04T17:00:00.5", "Story:1": "2026-11-04T17:00:00.1", "Epic:9": "2026-11-04T17:00:00.3" }; +const AFTER: Record = { "Task:50": "505", "Story:1": "101", "Epic:9": "303" }; +const AFTER_AT: Record = { "Task:50": "2026-11-04T17:00:00.5", "Story:1": "2026-11-04T17:00:00.1", "Epic:9": "2026-11-04T17:00:00.3" }; +/** The read just after a send: each asset's Moment (the stamp) and ChangeDate (the same instant, readable). */ +const isVersionRead = (q: Q): boolean => q.select!.length === 2 && q.select![0] === "Moment" && q.select![1] === "ChangeDate"; const lookup = (q: Q) => q.with!.$oids!.map((oid) => { - if (q.select!.includes("Moment")) throw new Error("no Moment reads"); - if (q.select!.length === 1 && q.select![0] === "ChangeDate") return { _oid: oid, ChangeDate: AFTER[oid] }; + if (isVersionRead(q)) return { _oid: oid, Moment: AFTER[oid], ChangeDate: AFTER_AT[oid] }; if (q.select!.includes("Name") || q.select!.includes("Number")) return { _oid: oid, ...Object.fromEntries(q.select!.map((a) => [a, NAMES[oid]?.[a as "Name"]])) }; return BEFORE[oid]; }); @@ -64,21 +67,25 @@ group("batch", () => { expect(d.executes).toEqual([{ oid: "Epic:9", op: "Inactivate", args: {} }]); }); - it("runBatch: preview, name, snapshot, send guarded on the snapshot's ChangeDates, then a receipt — created with alias and number, touched, skipped, after-stamps, reverse", async () => { + it("runBatch: preview, name, snapshot, send guarded on the snapshot's Moments, then a receipt — created with alias and number, touched, conflicts, after-stamps, reverse", async () => { let sent: Command[] = []; // Story:2 changed after the snapshot: its guarded update matches nothing. const t = server({ preview: PREVIEW, lookup, send: (b) => { sent = b; return envelope({ assetsCreated: { oidTokens: ["Task:50"], count: 1 }, assetsModified: { oidTokens: ["Story:1:101"], count: 1 }, assetsOperatedOn: { oidTokens: ["Epic:9"], count: 1 } }); } }); const confirm = vi.fn((_r: Receipt) => true); - const r = await runBatch(t, schema, REQUEST, { confirm }); + const r = await runBatch(t, schema, REQUEST, { guard: true, confirm }); expect(confirm).toHaveBeenCalledOnce(); - expect(confirm.mock.calls[0]![0]!.before["Story:1"]).toEqual({ Estimate: "3", Owners: [], ChangeDate: "2026-11-04T16:00:00.1" }); - expect(sent[1]).toEqual({ from: "Story", filter: ["ID=$oid", "ChangeDate='2026-11-04T16:00:00.1'"], with: { $oid: "Story:1" }, update: { Estimate: { add: ["5"], remove: [] }, Owners: { add: ["Member:20"], remove: [] } } }); + expect(confirm.mock.calls[0]![0]!.before["Story:1"]).toEqual({ Estimate: "3", Owners: [], Moment: "100", ChangeDate: "2026-11-04T16:00:00.1" }); + expect(sent[1]).toEqual({ from: "Story", where: { ID: "$oid", Moment: "$moment" }, filter: ["RetireDateUTC=''"], with: { $oid: "Story:1", $moment: "100" }, update: { Estimate: { add: ["5"], remove: [] }, Owners: { add: ["Member:20"], remove: [] } } }); expect(t.calls.at(-3)!.idempotent).toBe(false); // the batch creates: never resent expect(r.sent && r.guarded).toBe(true); expect(r.created).toEqual([{ alias: "@t", type: "Task", oid: "Task:50", number: "TK-50", name: "new task" }]); expect(r.touched).toEqual([{ oid: "Story:1", number: "S-1", name: "One" }, { oid: "Epic:9", number: "E-9", name: "Nine" }]); - expect(r.skipped).toEqual(["Story:2"]); + expect(r.conflicts).toEqual(["Story:2"]); + expect(r).toMatchObject({ receipt: 2, stopped: null, stamps: { "Story:1": "100", "Story:2": "200", "Epic:9": "300" } }); expect(r.after).toEqual(AFTER); + expect(r.changedAt).toEqual(AFTER_AT); + expect(isReceipt(JSON.parse(JSON.stringify(r)))).toBe(true); + expect(isReceipt({ receipt: 1, reverse: { commands: [], notes: [] } })).toBe(false); expect(r.reverse.commands).toEqual([ { from: "Story:1", update: { Estimate: "3", Owners: { add: [], remove: ["Member:20"] } } }, { from: "Epic:9", execute: "Reactivate" }, @@ -97,16 +104,16 @@ group("batch", () => { expect(r.notes.slice(1)).toEqual(["Epic:9: Split has no known inverse (was Active)"]); }); - it("an asset whose command failed is failed, not also skipped as changed since the snapshot (a CLI consumer finding)", async () => { + it("an asset whose command failed is failed, not also a conflict (a CLI consumer finding)", async () => { const preview = [{ "@x": { oid: "Conversation:12", execute: { op: "Delete", args: {} } } }, { "@y": { oid: "Epic:9", execute: { op: "Inactivate", args: {} } } }] as unknown as Command[]; const t = server({ preview, - lookup: (q) => q.with!.$oids!.map((oid) => (q.select!.includes("Name") ? { _oid: oid } : q.select!.includes("Children") ? { _oid: oid, Children: [] } : { _oid: oid, AssetState: "Active", ChangeDate: "2026-11-11T09:00:00.1" })), + lookup: (q) => q.with!.$oids!.map((oid) => (q.select!.includes("Name") ? { _oid: oid } : q.select!.includes("Children") ? { _oid: oid, Children: [] } : { _oid: oid, AssetState: "Active", Moment: "7", ChangeDate: "2026-11-11T09:00:00.1" })), send: () => envelope({ assetsOperatedOn: { oidTokens: [], count: 0 }, commandFailures: { commands: [{ error: { sourceCommandIndex: 0, message: "Unknown Operation 'Conversation.Delete'" } }], count: 1 } }) }); - const r = await runBatch(t, schema, [{ from: "Conversation:12", execute: "Delete" }, { from: "Epic:9", execute: "Inactivate" }]); + const r = await runBatch(t, schema, [{ from: "Conversation:12", execute: "Delete" }, { from: "Epic:9", execute: "Inactivate" }], { guard: true }); expect(r.failed).toEqual(["Conversation:12"]); - expect(r.skipped).toEqual(["Epic:9"]); // matched nothing: changed since the snapshot + expect(r.conflicts).toEqual(["Epic:9"]); // matched nothing: changed since the snapshot }); it("reverseOf leaves out an operation the type does not have, by meta's Operations, and says so: a created Conversation is not deleted (a CLI consumer finding)", () => { @@ -145,13 +152,13 @@ group("batch", () => { const sel = q.select!; if (sel.length === 1 && sel[0] === "Children") return { _oid: oid, Children: children[oid]!.map((c) => ({ _oid: c })) }; if (sel.length === 1 && sel[0] === "AssetState") return { _oid: oid, AssetState: state[oid] }; - if (sel.length === 1 && sel[0] === "ChangeDate") return { _oid: oid, ChangeDate: `2026-11-11T10:00:00.${oid.length}` }; + if (isVersionRead(q)) return { _oid: oid, Moment: `9${oid.length}`, ChangeDate: `2026-11-11T10:00:00.${oid.length}` }; if (sel.includes("Name")) return { _oid: oid, Name: oid, Number: oid }; - return { _oid: oid, AssetState: state[oid], ChangeDate: "2026-11-11T09:00:00.1" }; + return { _oid: oid, AssetState: state[oid], Moment: "8", ChangeDate: "2026-11-11T09:00:00.1" }; }), send: () => { state = { ...state, "Epic:9": "Closed", "Story:1": "Closed", "Task:5": "Closed" }; return envelope({ assetsOperatedOn: { oidTokens: ["Epic:9"], count: 1 } }); } }); - const r = await runBatch(t, schema, [{ from: "Epic:9", execute: "Inactivate" }]); + const r = await runBatch(t, schema, [{ from: "Epic:9", execute: "Inactivate" }], { guard: true }); expect(r.openDescendants).toEqual({ "Epic:9": ["Story:1", "Task:5"] }); // Task:6 was closed already: not the cascade's expect(r.cascaded).toEqual({ "Epic:9": ["Story:1", "Task:5"] }); expect(Object.keys(r.after).sort()).toEqual(["Epic:9", "Story:1", "Task:5"]); // so a later reverse can check them for drift @@ -162,16 +169,21 @@ group("batch", () => { ]); // A preview records the open descendants too, and sends nothing. state = { "Epic:9": "Active", "Story:1": "Active", "Task:5": "Active", "Task:6": "Closed" }; - expect((await runBatch(t, schema, [{ from: "Epic:9", execute: "Inactivate" }], { dryRun: true })).openDescendants).toEqual({ "Epic:9": ["Story:1", "Task:5"] }); + expect((await runBatch(t, schema, [{ from: "Epic:9", execute: "Inactivate" }], { guard: true, dryRun: true })).openDescendants).toEqual({ "Epic:9": ["Story:1", "Task:5"] }); }); - it("dryRun and a declined confirm send nothing; an unguardable batch is refused before any request unless guard is off", async () => { + it("dryRun and a declined confirm send nothing and say which; `guard` has no default; an unguardable batch is refused before any request unless guard is off", async () => { const t = server({ preview: PREVIEW, lookup, send: () => { throw new Error("must not send"); } }); - expect((await runBatch(t, schema, REQUEST, { dryRun: true })).sent).toBe(false); - expect((await runBatch(t, schema, REQUEST, { confirm: () => false })).sent).toBe(false); + expect(await runBatch(t, schema, REQUEST, { guard: true, dryRun: true })).toMatchObject({ sent: false, stopped: "dryRun" }); + expect(await runBatch(t, schema, REQUEST, { guard: true, confirm: () => false })).toMatchObject({ sent: false, stopped: "declined" }); + expect(await runBatch(server({ preview: [], lookup, send: () => envelope() }), schema, [{ from: "Story", filter: ["Number='S-0'"], update: { Estimate: 1 } }], { guard: true })).toMatchObject({ sent: false, stopped: "nothing" }); + const unasked = server({ preview: [], lookup, send: () => envelope() }); + await expect(runBatch(unasked, schema, REQUEST, {} as never)).rejects.toThrow(/guard: true.*guard: false.*no default/); + await expect(runBatch(unasked, schema, REQUEST, undefined as never)).rejects.toBeInstanceOf(UsageError); + expect(unasked.calls).toHaveLength(0); const aliasedUpdate: Command[] = [{ "@u": { from: "Story:1", update: { Name: "x" } } }]; const none = server({ preview: [], lookup, send: () => envelope() }); - await expect(runBatch(none, schema, aliasedUpdate)).rejects.toBeInstanceOf(UnguardableError); + await expect(runBatch(none, schema, aliasedUpdate, { guard: true })).rejects.toBeInstanceOf(UnguardableError); expect(none.calls).toHaveLength(0); expect((await runBatch(none, schema, aliasedUpdate, { guard: false })).guarded).toBe(false); await expect(runBatch(none, schema, [{ from: "@s", execute: "Delete" }], { guard: false })).rejects.toThrow(/rejected by the server/); @@ -179,7 +191,7 @@ group("batch", () => { it("a send that fails outright throws BatchSendError carrying the receipt up to the attempt", async () => { const t = server({ preview: PREVIEW, lookup, send: () => { throw new Error("socket hang up"); } }); - const e = (await runBatch(t, schema, REQUEST).catch((x: unknown) => x)) as BatchSendError; + const e = (await runBatch(t, schema, REQUEST, { guard: true }).catch((x: unknown) => x)) as BatchSendError; expect(e).toBeInstanceOf(BatchSendError); expect(e.receipt.sentCommands).toHaveLength(4); expect(e.receipt.before["Epic:9"]).toBeDefined(); @@ -190,13 +202,15 @@ group("batch", () => { // the CLI consumer's `apply` hit this: preview echoes aliased writes unexpanded, so nothing reads as per-asset work. const close: Command[] = [{ "@close": { from: "Story:20", execute: "QuickClose" } }]; let sent: Command[] | undefined; - const t = server({ preview: close, lookup: (q) => q.with!.$oids!.map((oid) => (q.select!.includes("Name") ? { _oid: oid, Name: "Twenty", Number: "S-20" } : { _oid: oid, ChangeDate: "2026-11-06T10:00:00.1" })), send: (body) => { sent = body; return envelope({ assetsOperatedOn: { oidTokens: ["Story:20:900"], count: 1 } }); } }); + const t = server({ preview: close, lookup: (q) => q.with!.$oids!.map((oid) => (q.select!.includes("Name") ? { _oid: oid, Name: "Twenty", Number: "S-20" } : { _oid: oid, Moment: "900", ChangeDate: "2026-11-06T10:00:00.1" })), send: (body) => { sent = body; return envelope({ assetsOperatedOn: { oidTokens: ["Story:20:900"], count: 1 } }); } }); const r = await runBatch(t, schema, close, { guard: false }); expect(sent).toEqual(close); expect(r.sent).toBe(true); expect(r.described.deferred).toEqual([{ index: 0, alias: "@close", from: "Story:20", kind: "execute" }]); expect(r.touched).toEqual([{ oid: "Story:20", number: "S-20", name: "Twenty" }]); // named after the send: preview never listed it - expect(r.after).toEqual({ "Story:20": "2026-11-06T10:00:00.1" }); + expect(r.after).toEqual({ "Story:20": "900" }); + expect(r.changedAt).toEqual({ "Story:20": "2026-11-06T10:00:00.1" }); + expect(r.conflicts).toEqual([]); // not guarded: nothing is compared, so nothing conflicts expect(r.notes.join("\n")).toMatch(/@close.*aliased execute.*not reversible/); expect(r.reverse.commands).toEqual([]); expect(r.reverse.notes.join("\n")).toMatch(/@close.*not reversed/); @@ -205,7 +219,7 @@ group("batch", () => { it("confirm sees the touched assets' names on the receipt, looked up once; a failed name lookup is a note, not a silence", async () => { const t = server({ preview: PREVIEW, lookup, send: () => envelope({ assetsCreated: { oidTokens: ["Task:50"], count: 1 }, assetsModified: { oidTokens: ["Story:1"], count: 1 }, assetsOperatedOn: { oidTokens: ["Epic:9"], count: 1 } }) }); let seen: Receipt["names"] | undefined; - const r = await runBatch(t, schema, REQUEST, { confirm: (receipt) => { seen = receipt.names; return true; } }); + const r = await runBatch(t, schema, REQUEST, { guard: true, confirm: (receipt) => { seen = receipt.names; return true; } }); expect(seen).toEqual({ "Story:1": { number: "S-1", name: "One" }, "Story:2": { number: "S-2", name: "Two" }, "Epic:9": { number: "E-9", name: "Nine" } }); const nameQueries = t.calls.filter((c) => (c.body as Q[])[0]?.select?.includes("Name") && (c.body as Q[])[0]?.with?.$oids?.some((o) => o.startsWith("Story"))); expect(nameQueries).toHaveLength(1); // not again after the send @@ -213,15 +227,15 @@ group("batch", () => { expect(r.notes).toEqual([]); const refusing = server({ preview: PREVIEW, lookup: (q) => { if (q.select!.includes("Name") && q.with!.$oids![0]!.startsWith("Epic")) throw new Error("Unknown AttributeDefinition: Epic.Name"); return lookup(q); }, send: () => envelope({ assetsOperatedOn: { oidTokens: ["Epic:9"], count: 1 } }) }); - const lookupFailed = (await runBatch(refusing, schema, REQUEST).catch((e: unknown) => e)) as Receipt; + const lookupFailed = (await runBatch(refusing, schema, REQUEST, { guard: true }).catch((e: unknown) => e)) as Receipt; expect(lookupFailed.sent).toBe(true); expect(lookupFailed.notes.some((n) => /could not look up Name for 1 Epic asset: .*Epic\.Name/.test(n))).toBe(true); }); it("a read-back that fails after the send throws BatchRecordError with the receipt: sent, outcome and reverse kept, after incomplete", async () => { - const afterFails = (q: Q) => { if (q.select!.length === 1 && q.select![0] === "ChangeDate") throw new Error("socket hang up"); return lookup(q); }; + const afterFails = (q: Q) => { if (isVersionRead(q)) throw new Error("socket hang up"); return lookup(q); }; const t = server({ preview: PREVIEW, lookup: afterFails, send: () => envelope({ assetsCreated: { oidTokens: ["Task:50"], count: 1 }, assetsModified: { oidTokens: ["Story:1"], count: 1 }, assetsOperatedOn: { oidTokens: ["Epic:9"], count: 1 } }) }); - const e = (await runBatch(t, schema, REQUEST).catch((x: unknown) => x)) as BatchRecordError; + const e = (await runBatch(t, schema, REQUEST, { guard: true }).catch((x: unknown) => x)) as BatchRecordError; expect(e).toBeInstanceOf(BatchRecordError); expect(e.message).toMatch(/sent and its outcome recorded.*receipt\.after is incomplete.*socket hang up/); expect(e.receipt.sent).toBe(true); @@ -232,23 +246,41 @@ group("batch", () => { }); it("reversible puts a Reactivate before deleting an asset that is closed now: Agility refuses to delete a closed asset", async () => { - const receipt = { after: { "Task:50": "2026-11-04T17:00:00.5", "Story:1": "2026-11-04T17:00:00.1" }, reverse: { notes: [], commands: [{ from: "Story:1", update: { Estimate: "3" } }, { from: "Task:50", execute: "Delete" }] as Command[] } }; - const t = server({ preview: [], lookup: (q) => q.with!.$oids!.map((oid) => (q.select![0] === "AssetState" ? { _oid: oid, AssetState: "Closed" } : { _oid: oid, ChangeDate: receipt.after[oid as "Task:50"] })), send: () => envelope() }); + const receipt = { receipt: 2 as const, after: { "Task:50": "505", "Story:1": "101" }, reverse: { notes: [], commands: [{ from: "Story:1", update: { Estimate: "3" } }, { from: "Task:50", execute: "Delete" }] as Command[] } }; + const t = server({ preview: [], lookup: (q) => q.with!.$oids!.map((oid) => (q.select![0] === "AssetState" ? { _oid: oid, AssetState: "Closed" } : { _oid: oid, Moment: receipt.after[oid as "Task:50"], ChangeDate: "2026-11-04T17:00:00.5" })), send: () => envelope() }); const r = await reversible(t, receipt); expect(r.reactivated).toEqual(["Task:50"]); expect(r.commands).toEqual([{ from: "Story:1", update: { Estimate: "3" } }, { from: "Task:50", execute: "Reactivate" }, { from: "Task:50", execute: "Delete" }]); // An open one is deleted as is. - const open = server({ preview: [], lookup: (q) => q.with!.$oids!.map((oid) => (q.select![0] === "AssetState" ? { _oid: oid, AssetState: "Active" } : { _oid: oid, ChangeDate: receipt.after[oid as "Task:50"] })), send: () => envelope() }); + const open = server({ preview: [], lookup: (q) => q.with!.$oids!.map((oid) => (q.select![0] === "AssetState" ? { _oid: oid, AssetState: "Active" } : { _oid: oid, Moment: receipt.after[oid as "Task:50"], ChangeDate: "2026-11-04T17:00:00.5" })), send: () => envelope() }); expect((await reversible(open, receipt)).reactivated).toEqual([]); }); - it("reversible drops assets changed since the batch (their ChangeDate is not the one recorded after it) unless forced", async () => { - const receipt = { after: { "Story:1": "2026-11-04T17:00:00.1", "Epic:9": "2026-11-04T17:00:00.3" }, reverse: { notes: [], commands: [{ from: "Story:1", update: { Estimate: "3" } }, { from: "Epic:9", execute: "Reactivate" }] as Command[] } }; - const now: Record = { "Story:1": "2026-11-04T18:00:00.9", "Epic:9": "2026-11-04T17:00:00.3" }; - const t = server({ preview: [], lookup: (q) => q.with!.$oids!.map((oid) => ({ _oid: oid, ChangeDate: now[oid] })), send: () => envelope() }); + it("reversible drops assets changed since the batch (their Moment is not the one recorded after it) unless forced, and says when each last changed", async () => { + const receipt = { receipt: 2 as const, after: { "Story:1": "101", "Epic:9": "303", "Task:5": "77" }, changedAt: { "Story:1": "2026-11-04T17:00:00.1" }, reverse: { notes: [], commands: [{ from: "Story:1", update: { Estimate: "3" } }, { from: "Epic:9", execute: "Reactivate" }, { from: "Task:5", execute: "Reactivate" }] as Command[] } }; + // Story:1 changed since; Epic:9 did not; Task:5 is gone. + const now: Record = { "Story:1": { Moment: "140", ChangeDate: "2026-11-04T18:00:00.9" }, "Epic:9": { Moment: "303", ChangeDate: "2026-11-04T17:00:00.3" } }; + const t = server({ preview: [], lookup: (q) => q.with!.$oids!.flatMap((oid) => (now[oid] ? [{ _oid: oid, ...now[oid] }] : [])), send: () => envelope() }); const r = await reversible(t, receipt); - expect(r.drifted).toEqual([{ oid: "Story:1", was: "2026-11-04T17:00:00.1", now: "2026-11-04T18:00:00.9" }]); + expect(r.drifted).toEqual([ + { oid: "Story:1", was: "101", now: "140", wasChangedAt: "2026-11-04T17:00:00.1", nowChangedAt: "2026-11-04T18:00:00.9" }, + { oid: "Task:5", was: "77", now: null, wasChangedAt: null, nowChangedAt: null } + ]); expect(r.commands).toEqual([{ from: "Epic:9", execute: "Reactivate" }]); - expect((await reversible(t, receipt, { force: true })).commands).toHaveLength(2); + expect((await reversible(t, receipt, { force: true })).commands).toHaveLength(3); + }); + + it("a receipt from before Moment stamps cannot be checked: reversible refuses it with a coded error naming the way out, and force reverses it without a check or a read", async () => { + // As stored by 1.0.0-alpha.7 and earlier: `receipt: 1`, ChangeDates in `after`. + const old = { receipt: 1, after: { "Story:1": "2026-11-04T17:00:00.1" }, reverse: { notes: [], commands: [{ from: "Story:1", update: { Estimate: "3" } }] as Command[] } }; + const t = server({ preview: [], lookup: () => { throw new Error("an old receipt reads nothing"); }, send: () => envelope() }); + const error = (await reversible(t, old).catch((e: unknown) => e)) as ReceiptVersionError; + expect(error).toBeInstanceOf(ReceiptVersionError); + expect(error).toMatchObject({ kind: "usage", code: "RECEIPT_VERSION", status: 0, receiptVersion: 1, targets: ["Story:1"] }); + expect(error.message).toMatch(/before 1\.0\.0-alpha\.8.*Reverse it with force.*or run the batch again/); + expect(await reversible(t, old, { force: true })).toEqual({ commands: old.reverse.commands, drifted: [], reactivated: [] }); + // A receipt with no version at all is treated the same. + await expect(reversible(t, { after: {}, reverse: old.reverse })).rejects.toBeInstanceOf(ReceiptVersionError); + expect(t.calls).toHaveLength(0); }); }); diff --git a/test/unit/errors.test.ts b/test/unit/errors.test.ts index 6dca1f9..e5d836f 100644 --- a/test/unit/errors.test.ts +++ b/test/unit/errors.test.ts @@ -41,7 +41,7 @@ describe("error kinds", () => { expect(e).toBeInstanceOf(ApiError); expect(e.kind).toBe("usage"); expect(e.status).toBe(0); - expect(new UnguardableError([{ index: 0, reason: "r" }])).toBeInstanceOf(UsageError); + expect(new UnguardableError([{ index: 0, code: "aliasedWrite", reason: "r" }])).toBeInstanceOf(UsageError); }); it("an error wrapped around another keeps the cause's kind and status, so the service errors still branch", () => { diff --git a/test/unit/guard.test.ts b/test/unit/guard.test.ts index e6f890a..2b29add 100644 --- a/test/unit/guard.test.ts +++ b/test/unit/guard.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest"; import type { RequestOptions, Transport } from "../../src/core/transport"; -import { UnguardableError, guard, passesOf, sendGuarded, sendPasses, touchedBy, unguardable } from "../../src/services/guard"; +import { ConflictError, UnguardableError, guard, passesOf, sendGuarded, sendPasses, touchedBy, unguardable } from "../../src/services/guard"; import type { Command } from "../../src/wire/assetApi"; const envelope = (over: Record = {}) => ({ @@ -24,60 +24,89 @@ const PROJECTED: Command[] = [ ]; describe("guard", () => { - it("rewrites each projected per-asset command as a query-scoped one on its ID (a variable) and ChangeDate (a literal — as a variable it never matches); creates pass through", () => { + it("rewrites each projected per-asset command as one on that asset at its Moment, while that version is current (both terms, always; both values as variables); creates pass through", () => { expect(touchedBy(PROJECTED)).toEqual(["Story:146020", "Story:146021"]); - const { commands, unstamped } = guard(PROJECTED, { "Story:146020": "2026-11-04T16:49:40.12", "Story:146021": "2026-11-04T16:49:39.893" }); + const { commands, unstamped } = guard(PROJECTED, { "Story:146020": "196330", "Story:146021": "196333" }); expect(unstamped).toEqual([]); expect(commands).toEqual([ - { from: "Story", filter: ["ID=$oid", "ChangeDate='2026-11-04T16:49:40.12'"], with: { $oid: "Story:146020" }, update: { Estimate: { add: ["2"], remove: [] }, Owners: { add: ["Member:20"], remove: [] } } }, - { from: "Story", filter: ["ID=$oid", "ChangeDate='2026-11-04T16:49:39.893'"], with: { $oid: "Story:146021" }, execute: { op: "Inactivate", args: {} } }, + { from: "Story", where: { ID: "$oid", Moment: "$moment" }, filter: ["RetireDateUTC=''"], with: { $oid: "Story:146020", $moment: "196330" }, update: { Estimate: { add: ["2"], remove: [] }, Owners: { add: ["Member:20"], remove: [] } } }, + { from: "Story", where: { ID: "$oid", Moment: "$moment" }, filter: ["RetireDateUTC=''"], with: { $oid: "Story:146021", $moment: "196333" }, execute: { op: "Inactivate", args: {} } }, { "@new": { AssetType: "Task", Name: "t", Parent: "Story:146020" } } ]); }); - it("an asset with no stamp (gone since the preview) is left out and reported, not sent unguarded; a stamp that is not a timestamp never reaches a filter", () => { - const { commands, unstamped } = guard(PROJECTED.slice(0, 2), { "Story:146021": "2026-11-04T16:49:39.893" }); + it("an asset with no stamp (gone since the preview) is left out and reported, not sent unguarded; a stamp that is not digits never reaches a query (the server answers one with a 500)", () => { + const { commands, unstamped } = guard(PROJECTED.slice(0, 2), { "Story:146021": "196333" }); expect(unstamped).toEqual(["Story:146020"]); expect(commands).toHaveLength(1); - expect(() => guard(PROJECTED.slice(0, 1), { "Story:146020": "2026-11-04' | ID!='x" })).toThrow(/not a timestamp/); + for (const bad of ["196330' | ID!='x", "", "abc", "2026-11-04T16:49:40.12"]) expect(() => guard(PROJECTED.slice(0, 1), { "Story:146020": bad })).toThrow(/is not a Moment/); + // Never one term without the other: RetireDateUTC='' with no Moment is a server error. + for (const c of commands) expect(c).toMatchObject({ where: { ID: "$oid", Moment: "$moment" }, filter: ["RetireDateUTC=''"] }); }); - it("names the shapes it cannot cover, by index: an aliased update or execute, a bare one from an alias, an update with inline creates", () => { + it("names the shapes it cannot cover, by index and by a code to branch on: an aliased update or execute, a bare one from an alias, an update with inline creates", () => { expect(unguardable([ { from: "Story", filter: ["Estimate>'3'"], update: { Estimate: 3 } }, { "@u": { from: "Story:1", update: { Name: "x" } } }, { from: "@s", execute: "Inactivate" }, { from: "Story:1", update: { Children: { add: [{ AssetType: "Task", Name: "t" }] } } } - ]).map((u) => u.index)).toEqual([1, 2, 3]); + ]).map((u) => [u.index, u.code])).toEqual([[1, "aliasedWrite"], [2, "bareAliasFrom"], [3, "inlineCreate"]]); }); - it("sendGuarded: preview, read ChangeDates, send guarded and marked idempotent (no creates); assets the response did not touch are skipped", async () => { + it("sendGuarded: preview, read Moments, send guarded and marked idempotent (no creates); the result is the Outcome plus the assets whose command matched nothing", async () => { const t = fakeTransport( PROJECTED.slice(0, 2), - envelope({ queryResult: { results: [[{ _oid: "Story:146020", ChangeDate: "2026-11-04T16:49:40.12" }, { _oid: "Story:146021", ChangeDate: "2026-11-04T16:49:39.893" }]], resultMetaData: [], count: 2 } }), + envelope({ queryResult: { results: [[{ _oid: "Story:146020", Moment: "196330" }, { _oid: "Story:146021", Moment: "196333" }]], resultMetaData: [], count: 2 } }), // Story:146021 changed in between: its guarded execute matched nothing. - envelope({ assetsModified: { oidTokens: ["Story:146020:193001"], count: 1 } }) + envelope({ assetsModified: { oidTokens: ["Story:146020"], count: 1 } }) ); const res = await sendGuarded(t, [{ from: "Story", filter: ["Number=$n"], with: { $n: ["S-1", "S-2"] }, update: { Estimate: 2 } }]); expect(t.calls.map((c) => c.query?.previewOnly ?? "send")).toEqual(["true", "send", "send"]); - expect(t.calls[1]!.body).toEqual([{ from: "Story", select: ["ChangeDate"], filter: ["ID=$oids"], with: { $oids: ["Story:146020", "Story:146021"] }, page: { size: 2, start: 0 } }]); + expect(t.calls[1]!.body).toEqual([{ from: "Story", select: ["Moment"], filter: ["ID=$oids"], with: { $oids: ["Story:146020", "Story:146021"] }, page: { size: 2, start: 0 } }]); expect(t.calls[2]!.idempotent).toBe(true); - expect(res.stamps).toEqual({ "Story:146020": "2026-11-04T16:49:40.12", "Story:146021": "2026-11-04T16:49:39.893" }); - expect(res.skipped).toEqual(["Story:146021"]); + expect(res.details.stamps).toEqual({ "Story:146020": "196330", "Story:146021": "196333" }); + expect(res).toMatchObject({ requestId: "r", modified: ["Story:146020"], operated: [], failures: [], touched: ["Story:146020", "Story:146021"], conflicts: ["Story:146021"] }); + expect(res.details.sent).toHaveLength(2); + }); + + it("a command that matched and failed is a failure, not a conflict; with throwOnFailure a conflict throws a ConflictError carrying the result", async () => { + const stamps = envelope({ queryResult: { results: [[{ _oid: "Story:146020", Moment: "196330" }, { _oid: "Story:146021", Moment: "196333" }]], resultMetaData: [], count: 2 } }); + const failing = fakeTransport(PROJECTED.slice(0, 2), stamps, envelope({ commandFailures: { count: 1, commands: [{ error: { message: "Violation'Invalid'AttributeDefinition'Status'Story", sourceCommandIndex: 1 } }] }, assetsModified: { oidTokens: ["Story:146020"], count: 1 } })); + const res = await sendGuarded(failing, [{ from: "Story", update: { Estimate: 2 } }]); + expect(res.conflicts).toEqual([]); + expect(res.failures).toHaveLength(1); + const conflicting = fakeTransport(PROJECTED.slice(0, 2), stamps, envelope({ assetsModified: { oidTokens: ["Story:146020"], count: 1 } })); + const error = (await sendGuarded(conflicting, [{ from: "Story", update: { Estimate: 2 } }], { throwOnFailure: true }).catch((e: unknown) => e)) as ConflictError; + expect(error).toBeInstanceOf(ConflictError); + expect(error).toMatchObject({ kind: "conflict", code: "CONFLICT", conflicts: ["Story:146021"], result: { modified: ["Story:146020"] } }); + expect(error.message).toBe("Story:146021 changed since it was read; nothing was applied to it"); + }); + + it("moments the caller holds are used as given and not read again; only the other assets' are read", async () => { + const t = fakeTransport(PROJECTED.slice(0, 2), envelope({ queryResult: { results: [[{ _oid: "Story:146021", Moment: "196333" }]], resultMetaData: [], count: 1 } }), envelope({ assetsModified: { oidTokens: ["Story:146020"], count: 1 }, assetsOperatedOn: { oidTokens: ["Story:146021"], count: 1 } })); + const res = await sendGuarded(t, [{ from: "Story", update: { Estimate: 2 } }], { moments: { "Story:146020:999": 196000, "Story:5": "1" } }); + expect((t.calls[1]!.body as { with: unknown }[])[0]!.with).toEqual({ $oids: ["Story:146021"] }); + expect(res.details.stamps).toEqual({ "Story:146020": "196000", "Story:146021": "196333" }); + expect((t.calls[2]!.body as { with: unknown }[])[0]!.with).toEqual({ $oid: "Story:146020", $moment: "196000" }); + expect(res.conflicts).toEqual([]); + // Every asset supplied: no read at all. + const none = fakeTransport(PROJECTED.slice(0, 1), envelope({ assetsModified: { oidTokens: ["Story:146020"], count: 1 } })); + await sendGuarded(none, [{ from: "Story:146020", update: { Estimate: 2 } }], { moments: { "Story:146020": "196330" } }); + expect(none.calls).toHaveLength(2); }); it("a guarded batch with a create is not marked idempotent — a resend would create twice", async () => { - const t = fakeTransport(PROJECTED, envelope({ queryResult: { results: [[{ _oid: "Story:146020", ChangeDate: "2026-11-04T16:49:40.12" }, { _oid: "Story:146021", ChangeDate: "2026-11-04T16:49:39.893" }]], resultMetaData: [], count: 2 } }), envelope()); + const t = fakeTransport(PROJECTED, envelope({ queryResult: { results: [[{ _oid: "Story:146020", Moment: "196330" }, { _oid: "Story:146021", Moment: "196333" }]], resultMetaData: [], count: 2 } }), envelope()); await sendGuarded(t, [{ from: "Story", update: { Estimate: 2 } }]); expect(t.calls[2]!.idempotent).toBe(false); }); - it("refuses an unguardable batch before any request, and anything of the Ideas product, which has no ChangeDate", async () => { + it("refuses an unguardable batch before any request, and anything of the Ideas product, which has no Moment", async () => { const none = fakeTransport(); await expect(sendGuarded(none, [{ "@u": { from: "Story:1", update: { Name: "x" } } }])).rejects.toBeInstanceOf(UnguardableError); expect(none.calls).toHaveLength(0); const ideas = fakeTransport([{ "@x": { oid: "Idea:7", update: { Name: { add: ["y"], remove: [] } } } }]); - await expect(sendGuarded(ideas, [{ from: "Idea:7", update: { Name: "y" } }])).rejects.toThrow(/Idea has no ChangeDate/); + await expect(sendGuarded(ideas, [{ from: "Idea:7", update: { Name: "y" } }])).rejects.toMatchObject({ reasons: [{ index: -1, code: "noMoment" }] }); expect(ideas.calls).toHaveLength(1); // the preview only }); }); @@ -93,24 +122,24 @@ describe("guard passes: two commands on one asset", () => { expect(passes[1]![0]).toEqual(P("Story:1", { execute: { op: "Delete", args: {} } })); }); - it("the second pass goes only for assets whose first command applied, guarded on the ChangeDate read just after it", async () => { + it("the second pass goes only for assets whose first command applied, guarded on the Moment read just after it", async () => { const sent: unknown[][] = []; const transport = { request: vi.fn(async (o: { body: unknown[] }) => { const body = o.body as Record[]; - if (body.length === 1 && (body[0]!.select as string[] | undefined)?.[0] === "ChangeDate") return env({ queryResult: { results: [[{ _oid: "Story:1", ChangeDate: "2026-11-07T12:00:00.5" }]], resultMetaData: [], count: 1 } }); + if (body.length === 1 && (body[0]!.select as string[] | undefined)?.[0] === "Moment") return env({ queryResult: { results: [[{ _oid: "Story:1", Moment: "501" }]], resultMetaData: [], count: 1 } }); sent.push(body); // Pass 1: Story:1 applies, Story:2 was changed by someone else and matches nothing. return sent.length === 1 ? env({ assetsOperatedOn: { oidTokens: ["Story:1:77"], count: 1 } }) : env({ assetsOperatedOn: { oidTokens: ["Story:1"], count: 1 } }); }) } as unknown as Parameters[0]; const projected = [P("Story:1", { execute: { op: "Reactivate", args: {} } }), P("Story:2", { execute: { op: "Reactivate", args: {} } }), P("Story:1", { execute: { op: "Delete", args: {} } }), P("Story:2", { execute: { op: "Delete", args: {} } })]; - const r = await sendPasses(transport, projected, { "Story:1": "2026-11-07T11:00:00.1", "Story:2": "2026-11-07T11:00:00.2" }); + const r = await sendPasses(transport, projected, { "Story:1": "101", "Story:2": "102" }); expect(sent).toHaveLength(2); - 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(sent[1]).toEqual([{ from: "Story", where: { ID: "$oid", Moment: "$moment" }, filter: ["RetireDateUTC=''"], with: { $oid: "Story:1", $moment: "501" }, 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" }); + const once = await sendPasses(transport, [P("Story:1", { execute: { op: "Reactivate", args: {} } })], { "Story:1": "101" }); expect(once.outcome.requestId).toBe("r"); }); }); From 4664a7a2fa16e4d458862d019f410397160bb7dc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:21:59 +0000 Subject: [PATCH 03/17] alpha.8 (3 of 3): one rule for rows, rest-1's reads named, the root trimmed to what a client user imports - Rows: a relation you select is a Ref, a path you select by name is at row[path], nothing arrives that you did not select, on every read path. rest-1's uninvited display columns are on the Refs only now; a dotted key stays when the path was selected, or when it has no Ref to fold onto. A live test reads one asset through query.v1, api/asset and rest-1 and compares the keys. Spec 000 section 2 and the README state the rule. - client.data.history / template / operate become client.history / template / operate; data.get goes; data.list stays public. rest-1 reads answer `more`, and a refused one is a QUERY_REJECTED with the server's sentences, as for query.v1 (fixture copied from a live refusal). - @versionone/agility-sdk/services holds the services as free functions, one namespace per module; the root keeps the client, the model, every error class and the pure helpers (unguardable, isReceipt, isAssetNumber, TypeCache, toBase64, fromBase64). Four entries, one flat dist/. - Row types: a sub-select is rows of the related type with what it selected (a Ref now carries its target type, at the type level only); a single relation is always nullable on a row; an explicit row type needs only `_oid`, so a consumer's own interface works. - An inline attachment read also answers `base64`. - README: a "which call for what" table. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 46 +++++++++++++++++++ README.md | 33 +++++++++++-- package.json | 10 ++++ specs/000-layers.md | 22 +++++++-- src/client.ts | 69 ++++++++++++++++++---------- src/index.ts | 13 ++++-- src/services/attachments.ts | 4 +- src/services/index.ts | 14 ++++++ src/types/asset.ts | 9 +++- src/types/query.ts | 35 ++++++++++++-- src/wire/queryV1.ts | 12 +++-- src/wire/rest1.ts | 44 ++++++++++++------ test/integration/attachments.test.ts | 1 + test/integration/client.test.ts | 37 +++++++++++++-- test/unit/cjs.test.ts | 13 ++++-- test/unit/client.test.ts | 4 +- test/unit/rest1.test.ts | 35 ++++++++++++-- test/unit/testing.test.ts | 2 +- test/unit/typedQuery.test.ts | 32 ++++++++++++- tsup.config.ts | 5 +- 20 files changed, 365 insertions(+), 75 deletions(-) create mode 100644 src/services/index.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 03d015d..1ecd477 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,8 +89,54 @@ Each entry has the line a consumer follows to migrate. `bareAliasFrom`, `inlineCreate`, `noMoment`). Migration: branch on `reason.code`, not on the words of `reason.reason`. +- **One rule for every row, on every read path**: a relation you select + is a Ref; a path you select by name is at `row[path]`; nothing arrives + that you did not select. query.v1 and api/asset rows already followed + it. On rest-1 (`client.data.list`, `client.history`) the display + columns the server adds beside a selected relation (`Owners.Name`, + `Owners.Nickname`) are now on the Refs only; their dotted keys are gone + from the row unless the path is in `select`. Migration: read + `row.Owners[i].Name`, or add `"Owners.Name"` to `select` to keep + `row["Owners.Name"]`. A dotted or type-qualified key with no Ref to + fold onto is kept as sent. +- **rest-1's other reads are on the client itself**: + `client.data.history` → `client.history`; `client.data.template` → + `client.template`; `client.data.operate` → `client.operate`. + `client.data.get` is gone (`client.get` reads one asset). + `client.data.list` stays where it is. +- **The services as free functions are at + `@versionone/agility-sdk/services`**, one namespace per module + (`guard`, `batch`, `resolve`, `schema`, `attachments`, `fields`). The + root no longer exports `sendGuarded`, `guard`, `stampsOf`, `touchedBy`, + `UNGUARDABLE_TYPES`, `runBatch`, `reversible`, `reverseOf`, `snapshot`, + `describeBatch`, `namesOf`, `INVERSE`, `resolveNumbers`, `resolveRef`, + `NUMBER_ROOTS`, `RESOLVE_CHUNK`, `importantName`, nor `Schema` as a + value (its type stays). Migration: `import { guard } from + "@versionone/agility-sdk/services"` and call `guard.sendGuarded(…)`; + or use the client's method, which is the same thing. The root keeps + the client, the model, every error class, `unguardable`, `isReceipt`, + `isAssetNumber`, `TypeCache` and the helpers below. +- **A refused rest-1 read is a `QUERY_REJECTED`** like a refused + query.v1 read: `details` is the exceptions (`{ type, message }[]`) and + `message` their sentences, led by rest-1's own ("Invalid WHERE + parameter; …"). It was a plain `ApiError` with the whole error document + as `details`. Migration: a formatter that special-cased rest-1 can + print `message` for both. +- **Row types**: a sub-select is typed as rows of the related type with + what it selected (it was typed as bare Refs, which was wrong), and a + single relation is always `| null` on a row, also where the metamodel + calls it required (the asset it pointed at may be gone). Migration: a + cast that worked around the old sub-select type can go; code that read + a required single relation without a null check gets a compile error + and needs the check. + ### Added +- A read's explicit row type can be the caller's own: `client.query(…)` + needs only `_oid` on `Card`, not the SDK's `Asset`. +- `ReadResult.more` on rest-1 reads, as on `queryPage`. +- `toBase64` / `fromBase64` on the root; an inline attachment read also + answers `base64`, the content as it arrived. - **`sendGuarded(commands, { moments })`**: guard an asset on the moment the caller read earlier (select `Moment` with the row a person is shown), so a change made since they saw it is a conflict. diff --git a/README.md b/README.md index 8212cf0..ae93ab4 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,32 @@ npm test ## Public API +### Which call for what + +| You want | Call | Notes | +| --- | --- | --- | +| Rows | `client.query(q)` / `client.queries([q, …])` | The default read. Read-only endpoint, resent once like a GET. No total. | +| One asset | `client.get(oid, select)` | Null when nothing has that OID. | +| Rows and how many there are | `client.queryPage(q)` | `{ rows, total, more }`. | +| Everything, page by page | `client.pages(q, { limit })` / `client.all(q, { limit })` | Bounded: default limit 1000. | +| Text search across types, a total, deleted assets | `client.data.list(type, params)` | rest-1: `find` / `findin`, `Story.Number` from `BaseAsset`, `deleted: true`. | +| An asset's past versions | `client.history(oid, params)` | One row per version; `_oid` carries the moment. | +| Who am I | `client.me()` | The member the credentials belong to. | +| Numbers a person typed | `client.resolve.numbers([...])` / `client.resolve.ref(spec)` | One request for any mix of types. | +| Write | `client.send(commands)` | Unguarded: writes whatever is there. Answers an `Outcome`. | +| Write only if nobody changed it | `client.sendGuarded(commands, { moments? })` | `conflicts` lists what was left alone. | +| Write with a record and an undo | `client.batch.run(commands, { guard })` then `client.batch.reversible(receipt)` | `guard` has no default. | +| Copy an asset, or run an operation for its result | `client.copy(oid)` / `client.operate(oid, op)` | | +| Defaults for a new asset | `client.template(type, { ctx })` | Nothing is created. | +| What a form needs | `client.fields.describe(type, scope)` | Required, visible and important attributes. | +| Files | `client.attachments.*`, `client.embeddedImages.*` | | +| A link for a person | `client.urls.asset(oidOrNumber)` | | +| Labels in the instance's words | `client.localize(tags)` | | + +Every row follows one rule, whichever call read it: **a relation you select is a Ref (`{ _oid }`); a path you select by name is at `row[path]` (`row["Status.Name"]`); nothing arrives that you did not select.** Select both `Owners` and `Owners.Name` and you get the Refs and, beside them, a parallel array at `"Owners.Name"`. To get attributes on the related rows themselves, use a sub-select: `{ from: "Owners", select: ["Name"] }` gives `row.Owners[i].Name`. (rest-1 also puts the display attributes it sends unasked on the Refs of a relation you selected.) + +### Reference + Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `AgilityApiClient` - the client. One query body everywhere; the client picks the endpoint: @@ -49,15 +75,16 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `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, 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 + - `copy(oid)` - the Copy operation, answering the copy's OID (api/asset performs it but never says what it made); `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) + - `data.list` / `history` / `template` - rest-1 reads: text search and 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) - `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`, `conflict`, `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 })`); `TypeCache.fromMetamodel(metamodel)` seeds one so nothing is loaded - `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 - 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/services` - the services as free functions over a `Transport` (`guard`, `batch`, `resolve`, `schema`, `attachments`, `fields`), for a caller that composes one differently; the client's methods are the same things - `@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. ## Testing code that uses the SDK @@ -90,7 +117,7 @@ API reference: https://docs.digital.ai/agility-api/ ## Installing an unreleased 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. The package's entries (`index`, `wire`, `services`, `testing`) and the chunks they share are all in one flat `dist/` directory, so a copy of `dist/` is a working copy. ## Releasing diff --git a/package.json b/package.json index 7fc5ba9..d2f54ed 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,16 @@ "default": "./dist/wire.cjs" } }, + "./services": { + "import": { + "types": "./dist/services.d.ts", + "default": "./dist/services.js" + }, + "require": { + "types": "./dist/services.d.cts", + "default": "./dist/services.cjs" + } + }, "./testing": { "import": { "types": "./dist/testing.d.ts", diff --git a/specs/000-layers.md b/specs/000-layers.md index 03b72ba..f95d462 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -48,6 +48,16 @@ pulled through) in a create, in an update, and in a query result alike. in `Attributes` and rendering `AssetState` as a number — is translated in that endpoint's wire module, once, on the way in and on the way out. +One rule for a row, on every read path (query.v1, api/asset, rest-1): +**a relation you select is a Ref; a path you select by name is at +`row[path]`; nothing arrives that you did not select.** A sub-select is +how to ask for attributes on the related rows. rest-1 sends display +columns beside a selected relation unasked; its wire module folds them +onto the Refs and drops their keys from the row unless the path was +selected, and keeps a dotted key that has no Ref to fold onto. An +integration test reads one asset through all three paths and compares +the keys. + Corollaries: - Envelope types live **inside the wire module that owns them** @@ -157,11 +167,15 @@ 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 +## 5a. Four 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 +The package has four entries: the root (the client, the model, the errors +and what a client user imports), `/wire` (the wire modules, for +passthroughs and transport authors), `/services` (the services as free +functions over a Transport; their request sequences are internal) and +`/testing`. All of them, and the chunks they share, are built into one +flat `dist/` directory: a consumer that vendors the package copies that +directory. 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. diff --git a/src/client.ts b/src/client.ts index 2385224..e3c31d5 100644 --- a/src/client.ts +++ b/src/client.ts @@ -38,7 +38,7 @@ 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 { +export interface Page { rows: Row[]; /** The number of matches across all pages; null when the server did not report one. */ total: number | null; @@ -84,8 +84,8 @@ const ME_SELECT = ["Name", "Username", "Nickname", "Email"]; * construction, so a request can be resent like a GET — but its shape has * nowhere to put a total; api/asset reports one (`needTotal`) beside the * rows, which is why `queryPage` goes there and `query` does not. rest-1 - * sits behind `data` for what neither does: deleted assets, history, a - * new asset's template, an operation's result. Writes: `send`, + * serves what neither does: `data.list` (text search across types, + * deleted assets), `history`, `template`, `operate`. Writes: `send`, * `sendGuarded`, `batch.run`, `copy`. Services: `resolve`, * `fields`, `attachments`, `embeddedImages`, `schema`, `localize`, `urls`. */ @@ -135,7 +135,7 @@ export class AgilityApiClient { * empty result. */ query>(q: Q & assetApi.Query): Promise[]>; - query(q: assetApi.Query): Promise; + query(q: assetApi.Query): Promise; async query(q: assetApi.Query): Promise { bounded([q]); await this.schema.ensureFor([q]); @@ -144,7 +144,7 @@ export class AgilityApiClient { /** Several queries in one request; one array of rows per query, in order. */ queries(qs: Qs): Promise>; - queries(qs: assetApi.Query[]): Promise; + queries(qs: assetApi.Query[]): Promise; async queries(qs: readonly assetApi.Query[]): Promise { bounded(qs); await this.schema.ensureFor(qs); @@ -157,7 +157,7 @@ export class AgilityApiClient { * exists.) */ get> | assetApi.QueryBody)[]>(oid: O, select: S): Promise, S> | null>; - get(oid: Oid, select?: assetApi.QueryBody["select"]): Promise; + get(oid: Oid, select?: assetApi.QueryBody["select"]): Promise; async get(oid: Oid, select?: assetApi.QueryBody["select"]): Promise { const rows = await this.query({ from: momentless(oid), ...(select ? { select } : {}), page: { size: 1, start: 0 } }); return rows[0] ?? null; @@ -169,7 +169,7 @@ export class AgilityApiClient { * when the server did not say; `more` is then whether the page was full. */ queryPage>(q: Q & assetApi.Query): Promise>>; - queryPage(q: assetApi.Query): Promise>; + queryPage(q: assetApi.Query): Promise>; async queryPage(q: assetApi.Query): Promise { bounded([q]); await this.schema.ensureFor([q]); @@ -184,7 +184,7 @@ export class AgilityApiClient { * transient failure like any GET. */ pages>(q: Q & assetApi.Query, options?: PagesOptions): AsyncGenerator[], void, undefined>; - pages(q: assetApi.Query, options?: PagesOptions): AsyncGenerator; + pages(q: assetApi.Query, options?: PagesOptions): AsyncGenerator; async *pages(q: assetApi.Query, options: PagesOptions = {}): AsyncGenerator { bounded([q]); const limit = options.limit ?? DEFAULT_LIMIT; @@ -202,7 +202,7 @@ export class AgilityApiClient { /** Every row of the query up to `limit` (default 1000), read page by page. */ all>(q: Q & assetApi.Query, options?: PagesOptions): Promise[]>; - all(q: assetApi.Query, options?: PagesOptions): Promise; + all(q: assetApi.Query, options?: PagesOptions): Promise; async all(q: assetApi.Query, options: PagesOptions = {}): Promise { const out: Asset[] = []; for await (const page of this.pages(q, options)) out.push(...page); @@ -250,24 +250,47 @@ export class AgilityApiClient { } /** - * rest-1.v1, for what the other endpoints cannot do: deleted assets - * (`deleted: true`), one asset by OID without a page, history (one row - * per moment), a new asset's template (`template`: what the type's - * initializer fills in for a context — a Timebox's next name and dates, - * a Story's carry-over from a Request), and an operation's result - * (`operate`: api/asset performs a Copy but never says what it made; - * rest-1 answers the new OID). Parameters are spelled as a query's - * (`select`, `filter`). + * rest-1's list read, for what the other reads cannot do: full-text + * `find` / `findin` across types with one order and a total, a + * type-qualified select from a base type (`Story.Number` on BaseAsset), + * and deleted assets (`deleted: true`). Parameters are spelled as a + * query's (`select`, `filter`), and rows follow the rule every read + * follows: a relation you select is a Ref, a path you select by name is + * at `row[path]`, and nothing arrives that you did not select. For + * everything else use `query` / `queryPage`. */ readonly data = { - list: (type: string, params: rest1.ReadParams) => rest1.list(this.transport, type, params), - get: (oid: string, select?: string[]) => rest1.get(this.transport, oid, select), - history: (target: string, params: rest1.ReadParams) => rest1.history(this.transport, target, params), - template: (type: F, options?: { ctx?: Oid }) => rest1.template>(this.transport, type, options), - operate: (oid: Oid, op: string) => rest1.operate(this.transport, oid, op) + list: (type: string, params: rest1.ReadParams) => rest1.list(this.transport, type, params) }; - /** Copy an asset (the server's Copy operation) and answer the copy's OID: the one thing api/asset's `execute: "Copy"` does not say. */ + /** + * An asset's history: one row per version, newest paging as asked, each + * row's `_oid` carrying its moment (`Story:1234:5678`). `target` is an + * OID token, or an asset type for the history of every asset of it. + */ + history(target: string, params: rest1.ReadParams): Promise> { + return rest1.history(this.transport, target, params); + } + + /** + * A new asset's template: what the type's initializer would fill in for + * a context (a Timebox's next name and dates in a schedule's scope, a + * Story's carry-over from a Request). Nothing is created. + */ + template(type: F, options?: { ctx?: Oid }): Promise>> { + return rest1.template>(this.transport, type, options); + } + + /** + * Run an operation for its result: the asset the server answered with + * and its new moment. `send` with an `execute` performs the same + * operations but does not say what a Copy made; this does. Never resent. + */ + operate(oid: Oid, op: string): Promise { + return rest1.operate(this.transport, oid, op); + } + + /** Copy an asset (the server's Copy operation) and answer the copy's OID. */ async copy(oid: Oid): Promise { return (await rest1.operate(this.transport, oid, "Copy")).oid; } diff --git a/src/index.ts b/src/index.ts index 7581f4c..ef1384a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -32,13 +32,16 @@ export { importantName } from "./services/fields"; // The wire modules themselves (assetApi, queryV1, rest1, meta, loc2, attachment, fields, select) and the // endpoints' envelope types are at "@versionone/agility-sdk/wire". -// Services: what to do. -export { Schema, TypeCache } from "./services/schema"; +// Services: their errors, the types of what they answer, and the few pure helpers a client user reaches for. +// The services themselves, as free functions over a Transport, are at "@versionone/agility-sdk/services". +export { TypeCache } from "./services/schema"; +export type { Schema } from "./services/schema"; export { AttachmentUploadError, INLINE_LIMIT } 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 { fromBase64, toBase64 } from "./wire/attachment"; +export { isAssetNumber } from "./services/resolve"; export type { Resolution, ResolvedAsset } from "./services/resolve"; -export { ConflictError, UNGUARDABLE_TYPES, UnguardableError, guard, sendGuarded, stampsOf, touchedBy, unguardable } from "./services/guard"; +export { ConflictError, GuardedPassError, UnguardableError, unguardable } from "./services/guard"; export type { GuardedOptions, GuardedResult, Unguardable, UnguardableCode } from "./services/guard"; -export { BatchRecordError, BatchSendError, ReceiptVersionError, isReceipt, INVERSE, describe as describeBatch, namesOf, reverseOf, reversible, runBatch, snapshot } from "./services/batch"; +export { BatchRecordError, BatchSendError, ReceiptVersionError, isReceipt } from "./services/batch"; export type { BatchOptions, Described, Drifted, NameLookupFailure, Named, Receipt, Reverse } from "./services/batch"; diff --git a/src/services/attachments.ts b/src/services/attachments.ts index 370dda5..6b50378 100644 --- a/src/services/attachments.ts +++ b/src/services/attachments.ts @@ -128,6 +128,8 @@ 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; + /** The content as Base64, on an inline read only: it is how the content arrived, so a caller that wants Base64 need not encode the bytes again. */ + base64?: string; } /** @@ -140,7 +142,7 @@ export async function get(transport: Transport, id: Oid | string | number, optio 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 }; + return { ...infoOf(rest), bytes: fromBase64(content), servedContentType: null, base64: content }; } const meta = await info(transport, id); if (!meta) throw new ApiError(`attachment ${numericId(id)}: not found`, 404, "NOT_FOUND"); diff --git a/src/services/index.ts b/src/services/index.ts new file mode 100644 index 0000000..72118df --- /dev/null +++ b/src/services/index.ts @@ -0,0 +1,14 @@ +/** + * The services as free functions over a Transport, one namespace per + * module: what the client's methods are built from. The client is the way + * in for almost everyone; this path is for a caller that composes a + * service differently (its own preview step, a schema it manages itself). + * Their request sequences are internal: they may change between releases + * in ways the client's methods do not. + */ +export * as attachments from "./attachments"; +export * as batch from "./batch"; +export * as fields from "./fields"; +export * as guard from "./guard"; +export * as resolve from "./resolve"; +export * as schema from "./schema"; diff --git a/src/types/asset.ts b/src/types/asset.ts index 39e5bb8..4d14d74 100644 --- a/src/types/asset.ts +++ b/src/types/asset.ts @@ -45,7 +45,14 @@ export function assetStateOf(value: unknown): AssetStateValue | string | null { * not folded onto the Ref: it arrives under its own key, `row["Owners.Name"]`, * like everything a query selects. */ -export type Ref = { _oid: Oid } & Partial>; +export type Ref = { _oid: Oid } & Partial> & { readonly [refTarget]?: T }; + +/** + * Types only: the key under which a Ref remembers which asset type it + * points at, so a sub-select can be typed by the related type. Nothing has + * this property at run time, and a plain `{ _oid }` is still a Ref. + */ +export declare const refTarget: unique symbol; /** The value types an attribute can carry in the model. */ export type AttributeValue = string | number | boolean | null | Ref | Ref[]; diff --git a/src/types/query.ts b/src/types/query.ts index a9067c6..0165113 100644 --- a/src/types/query.ts +++ b/src/types/query.ts @@ -12,7 +12,7 @@ * unknown keys, as before. The model is one product version's metamodel; * an instance may know more, and the types say "unknown", never "no". */ -import type { Asset } from "./asset"; +import type { Asset, refTarget } from "./asset"; import type { AssetTypeMap, AssetTypeName, ConcreteAssetTypeName } from "./assets/index"; import type { List } from "./assets/List"; @@ -53,11 +53,36 @@ export type SelectPath = /** The key a select entry puts on the row: the path itself, or a sub-select's `from`. */ export type SelectKey = E extends string ? E : E extends { from: infer F extends string } ? F : never; -/** The value a selected key carries on rows of T: the attribute's type when the key is one, a number for an aggregate, unknown for a path the model cannot follow. */ -export type SelectValue = K extends keyof T ? T[K] : K extends `${string}.@${string}` ? number : unknown; +/** + * The value a selected key carries on rows of T: the attribute's type when + * the key is one, a number for an aggregate, unknown for a path the model + * cannot follow. A single relation is always `| null`, even one the + * metamodel calls required: the asset it pointed at may have been deleted + * (a Conversation's Topic, live 2026-11-26). + */ +export type SelectValue = K extends keyof T ? (T[K] extends { _oid: string } ? T[K] | null : T[K]) : K extends `${string}.@${string}` ? number : unknown; + +/** The asset type behind a relation attribute's value (`Ref[]`, `Ref | null`), or Asset when it is not one. */ +type Related = NonNullable extends readonly (infer R)[] ? Target : Target>; +type Target = R extends { readonly [refTarget]?: infer X } ? (NonNullable extends Asset ? NonNullable : Asset) : Asset; + +/** + * What a sub-select `{ from: K, select: S }` puts on rows of T: rows of + * the related type with exactly S selected — a list for a multi-value + * relation, and one row or null for a single one (a single relation can + * be unset on a row whatever the metamodel says is required: the asset it + * pointed at may be gone). A `from` the model cannot follow (a path, a + * downcast, a filter) is rows of unknown shape. + */ +type SubSelected = K extends keyof T + ? NonNullable extends readonly unknown[] ? Selected, S>[] : Selected, S> | null + : Asset[] | Asset | null; + +/** The value one select entry puts on rows of T. */ +type EntryValue = E extends string ? SelectValue : E extends { from: infer K; select: infer S } ? SubSelected : E extends { from: infer K } ? SubSelected : unknown; -/** Rows of T with exactly the entries of S selected (plus `_oid`, always sent). */ -export type Selected = S extends readonly (infer E)[] ? Asset & { [K in SelectKey]: SelectValue } : Asset; +/** Rows of T with exactly the entries of S selected (plus `_oid`, always sent), sub-selects followed into the related type. */ +export type Selected = S extends readonly (infer E)[] ? Asset & { [K in SelectKey]: EntryValue> } : Asset; /** The row type of a query body: what its `from` reads, narrowed to its `select`; just `_oid` when nothing is selected. */ export type RowOf = Q extends { from: infer F extends string; select: infer S } ? Selected, S> : Asset; diff --git a/src/wire/queryV1.ts b/src/wire/queryV1.ts index d6e80e0..3b83c44 100644 --- a/src/wire/queryV1.ts +++ b/src/wire/queryV1.ts @@ -31,15 +31,19 @@ import { fromTypeOf } from "./select"; export interface QueryRejection { type: string | null; message: string } /** - * The error query.v1 sends for a query it refused: the exceptions' + * The error for a read the server refused, whichever endpoint refused it + * (query.v1 and rest-1 answer a 400 in the same document shape): the exceptions' * messages joined as the message, and `details` the exceptions alone * ({ type, message }[]) — not the whole error document, so a caller that * prints details prints what matters. */ -function rejected(error: ApiError): ApiError { - const details = error.details as { exceptions?: { type?: unknown; message?: unknown }[] } | undefined; +export function rejected(error: ApiError): ApiError { + const details = error.details as { error?: unknown; exceptions?: { type?: unknown; message?: unknown }[] } | undefined; const rejections: QueryRejection[] = (details?.exceptions ?? []).filter((e) => e && typeof e.message === "string" && e.message).map((e) => ({ type: typeof e.type === "string" ? e.type : null, message: e.message as string })); - return rejections.length ? new ApiError(rejections.map((r) => r.message).join("; "), error.status, "QUERY_REJECTED", rejections) : error; + if (!rejections.length) return error; + // rest-1 names what it refused in `error` ("Invalid WHERE parameter"); query.v1 says only "Bad Request", which adds nothing. + const lead = typeof details?.error === "string" && details.error && details.error !== "Bad Request" ? [details.error] : []; + return new ApiError([...lead, ...rejections.map((r) => r.message)].join("; "), error.status, "QUERY_REJECTED", rejections); } /** diff --git a/src/wire/rest1.ts b/src/wire/rest1.ts index a8ece13..212c4ea 100644 --- a/src/wire/rest1.ts +++ b/src/wire/rest1.ts @@ -39,6 +39,7 @@ import type { Transport } from "../core/transport"; import { assetStateOf, type Asset, type Oid, type Ref } from "../types/asset"; import { momentless } from "../types/oid"; import type { Query, QueryBody } from "./assetApi"; +import { rejected } from "./queryV1"; export { momentless }; @@ -75,14 +76,19 @@ export interface ReadParams { const toRef = (doc: AssetRefDocument): Ref => ({ _oid: momentless(doc.idref) }); /** - * One rest-1 asset as the model carries it. Relations become Refs; the - * display columns rest-1 adds beside a selected relation (Owners.Name) are - * folded onto those Refs by position, and kept under their dotted key too - * for a caller that asked for them by name; AssetState becomes its name; - * everything else is the value as sent. The row's own _oid keeps its - * moment only on a history read (it is the moment that identifies the row). + * One rest-1 asset as the model carries it. Relations become Refs; + * AssetState becomes its name; everything else is the value as sent. The + * row's own _oid keeps its moment only on a history read (it is the moment + * that identifies the row). + * + * rest-1 adds display columns beside a selected relation without being + * asked (Owners.Name, Owners.Nickname). They are folded onto the Refs by + * position, and the row follows the rule every read follows — it has the + * keys that were selected and no others: a dotted key stays only when it + * is in `select` (the caller asked for that path by name), or when it has + * no Ref to fold onto (it is then all there is of that value). */ -export function fromAssetDocument(doc: AssetDocument, { history = false } = {}): Row { +export function fromAssetDocument(doc: AssetDocument, { history = false, select }: { history?: boolean; select?: readonly string[] } = {}): Row { const out: Record = { _oid: history ? doc.id : momentless(doc.id) }; const attrs = doc.Attributes ?? {}; for (const [key, a] of Object.entries(attrs)) { @@ -102,8 +108,11 @@ export function fromAssetDocument(doc: AssetDocument, if (attr.includes(".")) continue; // deeper paths stay as columns only const target = out[rel]; const values = a.value; - if (Array.isArray(target) && Array.isArray(values)) target.forEach((ref, i) => { if (ref && typeof ref === "object") (ref as Record)[attr] = values[i]; }); - else if (target && typeof target === "object" && !Array.isArray(target) && !Array.isArray(a.value)) (target as Record)[attr] = a.value; + let folded = false; + if (Array.isArray(target) && Array.isArray(values)) { target.forEach((ref, i) => { if (ref && typeof ref === "object") (ref as Record)[attr] = values[i]; }); folded = true; } + else if (target && typeof target === "object" && !Array.isArray(target) && !Array.isArray(a.value)) { (target as Record)[attr] = a.value; folded = true; } + // On the Ref now. The dotted key goes unless the caller selected that path by name. + if (folded && !select?.includes(key)) delete out[key]; } return out as Row; } @@ -126,12 +135,21 @@ export function toQuery(params: ReadParams): Record // ---- the calls ------------------------------------------------------------- -export interface ReadResult { rows: Row[]; total: number | null; pageSize: number; pageStart: number } +/** One page of a rest-1 read: the rows, the total when asked for with `needTotal` (null otherwise), and whether more pages follow (as `Page.more`: exact with a total, else whether this page came back full). */ +export interface ReadResult { rows: Row[]; total: number | null; more: boolean; pageSize: number; pageStart: number } async function read(transport: Transport, path: string, params: ReadParams, history: boolean): Promise> { if (!params.page) throw new UsageError(`rest-1 read of ${path} without a page: every read must be bounded`); - const doc = await transport.request({ method: "GET", path, query: toQuery(params), responseType: "json" }); - return { rows: (doc.Assets ?? []).map((a) => fromAssetDocument(a, { history })), total: typeof doc.total === "number" && doc.total >= 0 ? doc.total : null, pageSize: doc.pageSize, pageStart: doc.pageStart }; + let doc: AssetsDocument; + try { + doc = await transport.request({ method: "GET", path, query: toQuery(params), responseType: "json" }); + } catch (error) { + // A read rest-1 refused (a bad filter, an unknown attribute) reads like one query.v1 refused. + throw error instanceof ApiError && error.status === 400 ? rejected(error) : error; + } + const rows = (doc.Assets ?? []).map((a) => fromAssetDocument(a, { history, select: params.select })); + const total = typeof doc.total === "number" && doc.total >= 0 ? doc.total : null; + return { rows, total, more: total === null ? rows.length === params.page.size : params.page.start + rows.length < total, pageSize: doc.pageSize, pageStart: doc.pageStart }; } /** A bounded list read of a type. */ @@ -142,7 +160,7 @@ export const list = (transport: Transport, type: stri export async function get(transport: Transport, oid: Oid, select?: string[]): Promise { const [type, id] = momentless(oid).split(":"); const doc = await transport.request({ method: "GET", path: `/rest-1.v1/Data/${encodeURIComponent(type!)}/${encodeURIComponent(id!)}`, query: { sel: select?.join(",") }, responseType: "json" }); - return fromAssetDocument(doc); + return fromAssetDocument(doc, { select }); } /** diff --git a/test/integration/attachments.test.ts b/test/integration/attachments.test.ts index 73769b6..90511e6 100644 --- a/test/integration/attachments.test.ts +++ b/test/integration/attachments.test.ts @@ -57,6 +57,7 @@ describeInstance("attachments (live)", () => { 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"); + expect(got.base64).toBe(btoa("inline read\n")); // as it arrived: no re-encoding for a caller that wants Base64 // 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. diff --git a/test/integration/client.test.ts b/test/integration/client.test.ts index dc91a8a..7798740 100644 --- a/test/integration/client.test.ts +++ b/test/integration/client.test.ts @@ -38,6 +38,37 @@ describeInstance("client reads (live)", () => { expect(await client.query(normalizeQuery({ from: "Member", sel: "Name", where: `ID='${me._oid}';IsSelf='false'`, page: "5,0" }))).toEqual([]); }); + it("the rows rule holds on every read path: a selected relation is a Ref, a path selected by name is at row[path], and no other key arrives", async () => { + const me = await client.me(); + const made = await client.send([{ AssetType: "Story", Name: fixtureName("rows rule"), Scope: { _oid: "Scope:0" }, Owners: [{ _oid: me._oid }] }], { throwOnFailure: true }); + const story = made.created[0]!; + try { + const select = ["Name", "Owners", "Owners.Name", "Scope.Name"]; + const keys = ["Name", "Owners", "Owners.Name", "Scope.Name", "_oid"]; + const viaQuery = (await client.query({ from: "Story", select, filter: ["ID=$id"], with: { $id: story }, page: { size: 1, start: 0 } }))[0]! as Record; + const viaPage = (await client.queryPage({ from: "Story", select, filter: ["ID=$id"], with: { $id: story }, page: { size: 1, start: 0 } })).rows[0]! as Record; + const viaRest = (await client.data.list("Story", { select, filter: [`ID='${story}'`], page: { size: 1, start: 0 } })).rows[0]! as unknown as Record; + for (const row of [viaQuery, viaPage, viaRest]) { + expect(Object.keys(row).sort()).toEqual(keys); + expect(row["Owners.Name"]).toEqual([me.Name]); // a parallel array beside the Refs + expect(typeof row["Scope.Name"]).toBe("string"); // its relation was not selected: the path is still there + expect((row.Owners as { _oid: string }[]).map((o) => o._oid)).toEqual([me._oid]); + } + // query.v1 and api/asset Refs are bare; rest-1 puts the display attributes it sends on the Ref as well. + expect(viaQuery.Owners).toEqual([{ _oid: me._oid }]); + expect(viaPage.Owners).toEqual([{ _oid: me._oid }]); + expect((viaRest.Owners as { Name: string }[])[0]!.Name).toBe(me.Name); + // rest-1 without the dotted path selected: its uninvited columns are on the Ref, not on the row. + const bare = (await client.data.list("Story", { select: ["Name", "Owners"], filter: [`ID='${story}'`], page: { size: 1, start: 0 } })).rows[0]! as unknown as Record; + expect(Object.keys(bare).sort()).toEqual(["Name", "Owners", "_oid"]); + // And a refused rest-1 read is a QUERY_REJECTED with sentences, like query.v1's. + await expect(client.data.list("Story", { filter: ["Nope=1"], page: { size: 1, start: 0 } })).rejects.toMatchObject({ kind: "invalid", code: "QUERY_REJECTED", message: expect.stringMatching(/^Invalid WHERE parameter; /) }); + await expect(client.query({ from: "Story", filter: ["Nope=1"], page: { size: 1, start: 0 } })).rejects.toMatchObject({ kind: "invalid", code: "QUERY_REJECTED" }); + } finally { + await client.send([{ from: story, execute: "Delete" }]); + } + }); + 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" }); @@ -102,13 +133,13 @@ describeInstance("rest-1 operate, template and fields (live)", () => { }, 60_000); it("template for a Timebox in a scope carries the initializer's suggestions; for a Story, the scope", async () => { - const timebox = await client.data.template("Timebox", { ctx: "Scope:0" }); + const timebox = await client.template("Timebox", { ctx: "Scope:0" }); expect(typeof timebox.Name).toBe("string"); expect(timebox.Schedule).toMatchObject({ _oid: expect.stringMatching(/^Schedule:\d+$/) }); expect(timebox.Owner).toMatchObject({ _oid: (await client.me())._oid }); - const story = await client.data.template("Story", { ctx: "Scope:0" }); + const story = await client.template("Story", { ctx: "Scope:0" }); expect(story).toEqual({ Scope: { _oid: "Scope:0" } }); - await expect(client.data.operate("Story:999999999", "NoSuchOp")).rejects.toMatchObject({ status: 400, kind: "invalid" }); + await expect(client.operate("Story:999999999", "NoSuchOp")).rejects.toMatchObject({ status: 400, kind: "invalid" }); }, 60_000); it("fields.describe answers required, visible and important attributes for a Story in Scope:0", async () => { diff --git a/test/unit/cjs.test.ts b/test/unit/cjs.test.ts index 577c002..643bd16 100644 --- a/test/unit/cjs.test.ts +++ b/test/unit/cjs.test.ts @@ -25,7 +25,7 @@ beforeAll(async () => { // absolute path (D:\\source\\…) matches nothing. Forward slashes work everywhere. 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 }); + await build({ config: false, entry: { index: entry("index.ts"), wire: entry("wire", "index.ts"), services: entry("services", "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 }); }); @@ -34,7 +34,7 @@ afterAll(() => { if (dir) rmSync(dir, { recursive: true, force: true }); }); const CONSUMER = String.raw` const assert = require("node:assert/strict"); const sdk = require("@versionone/agility-sdk"); -for (const name of ["AgilityApiClient", "createFetchTransport", "ApiError", "CommandFailureError", "TypeCache", "Schema", "parseOid", "momentless", "normalizeQuery"]) { +for (const name of ["AgilityApiClient", "createFetchTransport", "ApiError", "CommandFailureError", "TypeCache", "parseOid", "momentless", "normalizeQuery"]) { assert.ok(sdk[name], "missing export " + name); } const json = (body) => new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } }); @@ -62,6 +62,13 @@ const fetchImpl = async (url) => { assert.equal(sdk[name], undefined, "the root no longer exports the wire module " + name); } assert.equal(wire.assetApi.CommandFailureError, sdk.CommandFailureError); + const services = require("@versionone/agility-sdk/services"); + for (const name of ["attachments", "batch", "fields", "guard", "resolve", "schema"]) assert.ok(services[name], "missing service module " + name); + for (const name of ["sendGuarded", "runBatch", "resolveNumbers", "NUMBER_ROOTS", "stampsOf"]) assert.equal(sdk[name], undefined, "the root no longer exports the free function " + name); + assert.equal(services.guard.unguardable, sdk.unguardable); + assert.equal(services.guard.ConflictError, sdk.ConflictError); + assert.equal(services.schema.TypeCache, sdk.TypeCache); + assert.equal(sdk.toBase64(new Uint8Array([104, 105])), "aGk="); 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" }]); @@ -85,7 +92,7 @@ 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"]) { + for (const path of ["wire", "services", "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/client.test.ts b/test/unit/client.test.ts index db30cd0..598fea6 100644 --- a/test/unit/client.test.ts +++ b/test/unit/client.test.ts @@ -130,8 +130,8 @@ describe("client: data.operate, copy, data.template", () => { const t = fake((o) => (o.path.startsWith("/rest-1.v1/New/") ? { _type: "Asset", href: "", id: "", Attributes: { Scope: { _type: "Relation", name: "Scope", act: "set", value: { _type: "Asset", href: "", idref: "Scope:0" } } } } : { _type: "Asset", href: "", id: "Story:9:1" })); const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: schema().cache }); expect(await client.copy("Story:1")).toBe("Story:9"); - expect(await client.data.operate("Story:1", "Inactivate")).toEqual({ oid: "Story:9", moment: "1" }); - const tpl = await client.data.template("Story", { ctx: "Scope:0" }); + expect(await client.operate("Story:1", "Inactivate")).toEqual({ oid: "Story:9", moment: "1" }); + const tpl = await client.template("Story", { ctx: "Scope:0" }); expect(tpl.Scope).toEqual({ _oid: "Scope:0" }); }); }); diff --git a/test/unit/rest1.test.ts b/test/unit/rest1.test.ts index 577e7f5..93ed4bf 100644 --- a/test/unit/rest1.test.ts +++ b/test/unit/rest1.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vitest"; import type { RequestOptions, Transport } from "../../src/core/transport"; import type { Story } from "../../src/types/assets/Story"; -import { UsageError } from "../../src/core/errors"; +import { UsageError, apiErrorFromResponse } 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[] } { @@ -37,9 +37,36 @@ describe("rest1: translation", () => { expect(row.Super).toBeNull(); expect(row.Status).toEqual({ _oid: "StoryStatus:137", Name: "Accepted" }); expect(row.Owners).toEqual([{ _oid: "Member:1035", Name: "Alfred Smith", Nickname: "alfred" }, { _oid: "Member:20", Name: "Betty Builder", Nickname: "betty" }]); - // The dotted columns stay too, for a caller that selected them by name. - expect((row as unknown as Record)["Status.Name"]).toBe("Accepted"); - expect((row as unknown as Record)["Owners.Name"]).toEqual(["Alfred Smith", "Betty Builder"]); + // rest-1 sent those display columns uninvited: they are on the Refs, and the row has no key nobody selected. + expect(Object.keys(row).filter((k) => k.includes("."))).toEqual([]); + }); + + it("the rows rule on rest-1: a path selected by name keeps its key (a parallel array beside bare-looking Refs for a multi-value relation); one with no Ref to fold onto is kept as sent", () => { + const selected = fromAssetDocument(storyDoc, { select: ["Name", "Owners", "Owners.Name", "Status.Name"] }) as unknown as Record; + expect(selected["Owners.Name"]).toEqual(["Alfred Smith", "Betty Builder"]); + expect(selected["Status.Name"]).toBe("Accepted"); + expect(selected["Owners.Nickname"]).toBeUndefined(); // uninvited: on the Refs only + expect((selected.Owners as { Nickname: string }[]).map((o) => o.Nickname)).toEqual(["alfred", "betty"]); + // A dotted or type-qualified key whose relation is not in the row has nothing to fold onto: it is all there is of the value, so it stays. + const lone: AssetDocument = { _type: "Asset", href: "", id: "Story:1", Attributes: { "Scope.Name": { _type: "Attribute", name: "Scope.Name", value: "Release 1" }, "Story.Number": { _type: "Attribute", name: "Story.Number", value: "S-1" } } }; + expect(fromAssetDocument(lone)).toEqual({ _oid: "Story:1", "Scope.Name": "Release 1", "Story.Number": "S-1" }); + expect(fromAssetDocument(lone, { select: ["Name"] })).toEqual({ _oid: "Story:1", "Scope.Name": "Release 1", "Story.Number": "S-1" }); + }); + + it("a read rest-1 refuses is a QUERY_REJECTED with the server's sentences, like one query.v1 refuses; a page has `more`", async () => { + // rest-1's answer to where=Nope=1, verbatim (the API-testing instance, 2026-11-26). + const refusal = apiErrorFromResponse(400, { _type: "Error", error: "Invalid WHERE parameter", exceptions: [{ type: "FormatException", message: "Invalid QueryFilter2 token Nope=1" }, { type: "NoViableAltException", message: "Position 6: unexpected token: [\"1\",<24>,col=6]" }] }); + const t = { request: vi.fn(async () => { throw refusal; }) } as unknown as Transport; + await expect(list(t, "Story", { filter: ["Nope=1"], page: { size: 1, start: 0 } })).rejects.toMatchObject({ + kind: "invalid", code: "QUERY_REJECTED", status: 400, + message: "Invalid WHERE parameter; Invalid QueryFilter2 token Nope=1; Position 6: unexpected token: [\"1\",<24>,col=6]", + details: [{ type: "FormatException", message: "Invalid QueryFilter2 token Nope=1" }, { type: "NoViableAltException", message: "Position 6: unexpected token: [\"1\",<24>,col=6]" }] + }); + const page = (total: number | undefined, n: number) => fakeTransport({ _type: "Assets", total, pageSize: 2, pageStart: 0, Assets: Array.from({ length: n }, (_, i) => ({ _type: "Asset", href: "", id: `Story:${i}` })) }); + expect((await list(page(5, 2), "Story", { page: { size: 2, start: 0 }, needTotal: true })).more).toBe(true); + expect((await list(page(2, 2), "Story", { page: { size: 2, start: 0 }, needTotal: true })).more).toBe(false); + expect(await list(page(undefined, 2), "Story", { page: { size: 2, start: 0 } })).toMatchObject({ total: null, more: true }); + expect((await list(page(undefined, 1), "Story", { page: { size: 2, start: 0 } })).more).toBe(false); }); it("keeps the moment on a history row's _oid and strips it on a data row", () => { diff --git a/test/unit/testing.test.ts b/test/unit/testing.test.ts index 0e48f87..b8d633a 100644 --- a/test/unit/testing.test.ts +++ b/test/unit/testing.test.ts @@ -94,7 +94,7 @@ describe("FakeAgilityClient", () => { 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/); + await expect(fake.data.list("Story", { page: { size: 1, start: 0 } })).rejects.toThrow(/no answer scripted for GET \/rest-1\.v1\/Data\/Story/); }); it("a batch that creates and reads back through an alias answers the scripted row of that type under the created OID", async () => { diff --git a/test/unit/typedQuery.test.ts b/test/unit/typedQuery.test.ts index c050b6c..ac657c4 100644 --- a/test/unit/typedQuery.test.ts +++ b/test/unit/typedQuery.test.ts @@ -27,7 +27,12 @@ describe("typed queries", () => { expectTypeOf(rows[0]!.Status).toEqualTypeOf | null | undefined>(); expectTypeOf(rows[0]!["Status.Name"]).toEqualTypeOf(); expectTypeOf(rows[0]!["Owners.@Count"]).toEqualTypeOf(); - expectTypeOf(rows[0]!.Owners).toEqualTypeOf[]>(); + // A sub-select is rows of the related type with what it selected, not bare Refs. + type Owner = (typeof rows)[number]["Owners"][number]; + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + // @ts-expect-error Nickname was not selected in the sub-select + type _NotSelected = Owner["Nickname"]; // @ts-expect-error Nmae was not selected (and is not an attribute) rows[0]!.Nmae; expect(rows).toHaveLength(1); @@ -87,6 +92,31 @@ describe("typed queries", () => { }); }); +describe("typed sub-selects and a consumer's own row type", () => { + it("nested sub-selects type all the way down: a list for a multi-value relation, one row or null for a single one", async () => { + // The shape of a comment-thread read (a browser app consumer): relations of relations, each with its own select. + const rows = await client.all({ from: "Conversation", select: ["Topic", { from: "Participants", select: ["Name", "Nickname"] }, { from: "ContainedExpressions", select: ["Content", "IsDeletable", { from: "Author", select: ["Name", "IsInactive"] }, { from: "Mentions", select: ["Name"] }] }], page: { size: 1, start: 0 } }).catch(() => []); + type Row = (typeof rows)[number]; + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf["IsInactive"]>().toEqualTypeOf(); + expectTypeOf().toBeNullable(); + expectTypeOf().toEqualTypeOf(); + // A bare single relation can be null on a row even where the metamodel calls it required. + expectTypeOf().toBeNullable(); + }); + + it("a row type of the consumer's own, with no SDK type in it, can be named at the call", async () => { + interface Card { _oid: string; Name: string; Estimate: number | null } + const cards = await client.query({ from: "Story", select: ["Name", "Estimate"], page: { size: 1, start: 0 } }); + expectTypeOf(cards).toEqualTypeOf(); + const page = await client.queryPage({ from: "Story", select: ["Name"], page: { size: 1, start: 0 } }); + expectTypeOf(page.rows).toEqualTypeOf(); + expectTypeOf(await client.get("Story:1", ["Name"])).toEqualTypeOf(); + expectTypeOf(await client.all({ from: "Story", page: { size: 1, start: 0 } })).toEqualTypeOf(); + }); +}); + 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"); diff --git a/tsup.config.ts b/tsup.config.ts index c2b9b69..01938cc 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -2,10 +2,11 @@ import { defineConfig } from "tsup"; export default defineConfig({ // One entry per public import path: the root, `/wire` (the endpoints' own - // shapes) and `/testing` (FakeAgilityClient). Code they share is split + // shapes), `/services` (the services as free functions) and `/testing` + // (FakeAgilityClient). Every entry and chunk lands in one flat dist/. 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" }, + entry: { index: "src/index.ts", wire: "src/wire/index.ts", services: "src/services/index.ts", testing: "src/testing/index.ts" }, format: ["esm", "cjs"], splitting: true, dts: true, From 7df517c1e99e84bff6e155f0733b89d65ebe7b99 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:27:50 +0000 Subject: [PATCH 04/17] alpha.8: resolved assets as rows, resolve.refs, Outcome.unmatched, assetStateKind, fetch looked up per request - resolve.numbers / ref answer rows ({ _oid, AssetType, Number, Name, AssetState }); they were the last camelCase vocabulary in the SDK. - resolve.refs reads numbers and OID tokens mixed, in two requests at most, asking each OID's type only for the attributes it has. - Outcome.unmatched: updates and operations addressed to one asset by OID that did nothing and reported nothing. Live: an update of a deleted asset, and an operation on an asset that went with its parent, answer success with empty lists; an applied command, a no-op and a refused operation (which is a failure) are not flagged. - assetStateKind: a state's name or code as open / closed / template / deleted / other. - The fetch transport reads globalThis.fetch at each request, so a stub installed after the transport was made is the one called. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 18 +++++++++ README.md | 4 +- src/client.ts | 23 +++++++---- src/core/fetchTransport.ts | 4 +- src/index.ts | 2 +- src/services/resolve.ts | 69 ++++++++++++++++++++++++++------ src/types/asset.ts | 20 +++++++++ src/types/command.ts | 10 +++++ src/wire/assetApi.ts | 27 ++++++++++++- test/integration/client.test.ts | 25 ++++++++++++ test/integration/resolve.test.ts | 25 ++++++++++-- test/unit/client.test.ts | 43 +++++++++++++++++++- test/unit/resolve.test.ts | 12 +++--- test/unit/testing.test.ts | 4 +- 14 files changed, 245 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ecd477..aa1504f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -130,8 +130,26 @@ Each entry has the line a consumer follows to migrate. a required single relation without a null check gets a compile error and needs the check. +- **A resolved asset is a row**: `client.resolve.numbers` and `ref` + answer `{ _oid, AssetType, Number, Name, AssetState }`, the names every + row uses. Migration: `oid` → `_oid`; `type` → `AssetType`; `number` → + `Number`; `name` → `Name`; `assetState` → `AssetState`. + ### Added +- **`client.resolve.refs(specs)`**: numbers and OID tokens mixed, each + one read, in two requests at most; what names nothing is `missing`. +- **`Outcome.unmatched`**: the indexes of updates and operations + addressed to one asset by OID that did nothing and reported nothing, + because the asset is gone. The server answers such a command with + success; a caller that checked `operated.length === 0` by hand reads + this instead. (A command that applied without changing a value, and + one the server refused, are not in it.) +- `assetStateKind(value)`: an AssetState name or code as `"open"`, + `"closed"`, `"template"`, `"deleted"` or `"other"`. +- The fetch transport calls the global `fetch` as it is at each request + (it captured it when the transport was made), so a stub installed + later is used without passing `fetchImpl`. - A read's explicit row type can be the caller's own: `client.query(…)` needs only `_oid` on `Card`, not the SDK's `Asset`. - `ReadResult.more` on rest-1 reads, as on `queryPage`. diff --git a/README.md b/README.md index ae93ab4..0c6924b 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,8 @@ npm test | Text search across types, a total, deleted assets | `client.data.list(type, params)` | rest-1: `find` / `findin`, `Story.Number` from `BaseAsset`, `deleted: true`. | | An asset's past versions | `client.history(oid, params)` | One row per version; `_oid` carries the moment. | | Who am I | `client.me()` | The member the credentials belong to. | -| Numbers a person typed | `client.resolve.numbers([...])` / `client.resolve.ref(spec)` | One request for any mix of types. | -| Write | `client.send(commands)` | Unguarded: writes whatever is there. Answers an `Outcome`. | +| Numbers and OIDs a person typed | `client.resolve.numbers([...])` / `client.resolve.refs([...])` | Answered as rows. One request for numbers of any mix of types. | +| Write | `client.send(commands)` | Unguarded: writes whatever is there. Answers an `Outcome`; `unmatched` lists commands whose asset was gone. | | Write only if nobody changed it | `client.sendGuarded(commands, { moments? })` | `conflicts` lists what was left alone. | | Write with a record and an undo | `client.batch.run(commands, { guard })` then `client.batch.reversible(receipt)` | `guard` has no default. | | Copy an asset, or run an operation for its result | `client.copy(oid)` / `client.operate(oid, op)` | | diff --git a/src/client.ts b/src/client.ts index e3c31d5..1b3fbb4 100644 --- a/src/client.ts +++ b/src/client.ts @@ -316,13 +316,18 @@ export class AgilityApiClient { * violation), query rows per query command — and never the envelope. * The server commits per command and answers 200 either way, so a * failed command is in `failures`, or thrown as a CommandFailureError - * with `throwOnFailure` (the error carries the same Outcome). Not - * guarded: it writes whatever is there now. `sendGuarded` is the + * with `throwOnFailure` (the error carries the same Outcome). A command + * addressed to one asset by OID that did nothing and reported nothing + * (the asset is gone) is in `unmatched`: the server calls that a + * success. Not guarded: it writes + * whatever is there now. `sendGuarded` is the * compare-and-set. */ async send(commands: assetApi.Command[], options?: Omit): Promise> { await this.schema.ensureFor(commands); - return assetApi.outcomeOf(await assetApi.send(this.transport, commands, { ...options, lookup: this.schema })); + const outcome = assetApi.outcomeOf(await assetApi.send(this.transport, commands, { ...options, lookup: this.schema })); + outcome.unmatched = assetApi.unmatchedOf(commands, outcome); + return outcome; } /** The server's projection of a batch: one command per asset it would touch, nothing applied. */ @@ -349,13 +354,17 @@ export class AgilityApiClient { } /** - * Services: what a person types, turned into assets. Numbers resolve in - * one api/asset request across every number root; an OID token is taken - * as is. + * Services: what a person types, turned into assets, each answered as a + * row (`_oid`, `AssetType`, `Number`, `Name`, `AssetState`). Numbers + * resolve in one api/asset request across every number root; `ref` + * takes an OID token as given, without a request; `refs` reads a mixed + * list. */ readonly resolve = { numbers: (numbers: readonly string[]) => resolve.resolveNumbers(this.transport, numbers, { types: this.schema.cache }), - ref: (spec: string) => resolve.resolveRef(this.transport, spec, { types: this.schema.cache }) + ref: (spec: string) => resolve.resolveRef(this.transport, spec, { types: this.schema.cache }), + /** Numbers and OID tokens mixed, each one read (Number, Name, AssetState where its type has them): two requests at most. */ + refs: (specs: readonly string[]) => resolve.resolveRefs(this.transport, this.schema, specs, { types: this.schema.cache }) }; /** diff --git a/src/core/fetchTransport.ts b/src/core/fetchTransport.ts index fdf9599..148e817 100644 --- a/src/core/fetchTransport.ts +++ b/src/core/fetchTransport.ts @@ -144,7 +144,6 @@ function retryDelay(response: { status: number; headers: { get(name: string): st const retriable = (status: number): boolean => status === 429 || status >= 500; export function createFetchTransport(config: FetchTransportConfig): Transport { - const fetchImpl = config.fetchImpl ?? fetch; const timeoutMs = config.timeoutMs ?? 60_000; const retries = Math.max(0, config.retries ?? 1); const authorization = config.authorization ?? (config.accessToken ? `Bearer ${config.accessToken}` : undefined); @@ -180,7 +179,8 @@ export function createFetchTransport(config: FetchTransportConfig): Transport { try { const init: RequestInit = { method: options.method, headers, body, signal: controller.signal }; if (config.credentials) init.credentials = config.credentials; - response = await fetchImpl(url, init); + // Looked up at each request, not when the transport was made: whatever replaces the global fetch later (a test's stub, an instrumented fetch) is what gets called. + response = await (config.fetchImpl ?? globalThis.fetch)(url, init); } catch (error) { settle(); // The caller gave up: final, whatever attempt this was. diff --git a/src/index.ts b/src/index.ts index ef1384a..ed65160 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,7 +9,7 @@ export type { RequestBody, RequestOptions, ResponseType, Transport } from "./cor // The model: what things are. export type { Asset, AttributeValue, CustomAttributes, DateString, Oid, Ref, AssetStateValue } from "./types/asset"; -export { ASSET_STATE_CODES, assetStateOf } from "./types/asset"; +export { ASSET_STATE_CODES, assetStateKind, assetStateOf } from "./types/asset"; export { isOidToken, momentless, parseOid, toOid, typeOfOid } from "./types/oid"; export type { OidParts } from "./types/oid"; export type { AssetType, AttributeDefinition, AttributeLookup, AttributeType, AttributeTokenRef, AssetTypeToken, Metamodel } from "./types/metamodel"; diff --git a/src/services/resolve.ts b/src/services/resolve.ts index aae9d8b..57e7525 100644 --- a/src/services/resolve.ts +++ b/src/services/resolve.ts @@ -20,7 +20,7 @@ import { UsageError } from "../core/errors"; import type { Transport } from "../core/transport"; import { assetStateOf, type Asset, type AssetStateValue, type Oid } from "../types/asset"; -import type { TypeCache } from "./schema"; +import type { Schema, TypeCache } from "./schema"; import type { AssetTypeToken } from "../types/metamodel"; import { isOidToken, momentless, typeOfOid } from "../types/oid"; import * as assetApi from "../wire/assetApi"; @@ -62,19 +62,24 @@ export const isAssetNumber = (text: string): boolean => /^[A-Za-z]+-\d+$/.test(t /** How many numbers one request asks about: bounded, never one giant filter. */ export const CHUNK = 100; +/** + * A resolved asset: a row, under the names every row uses, with what + * resolving reads. `Number` is null for an asset that has none (or for an + * OID token taken as given by `ref`), `Name` and `AssetState` likewise. + */ export interface ResolvedAsset { - /** The number as the server spells it; null for a ref given as an OID token. */ - number: string | null; - oid: Oid; - type: AssetTypeToken; - name: string | null; - assetState: AssetStateValue | null; + _oid: Oid; + AssetType: AssetTypeToken; + /** The number as the server spells it. */ + Number: string | null; + Name: string | null; + AssetState: AssetStateValue | null; } export interface Resolution { - /** In the order the numbers were asked for, one per distinct number found. */ + /** In the order asked for, one per distinct number (or OID) found. */ found: ResolvedAsset[]; - /** Numbers no root knows, as they were asked for. */ + /** What nothing answered to, as it was asked for. */ missing: string[]; } @@ -131,7 +136,7 @@ export async function resolveNumbers(transport: Transport, numbers: readonly str for (const r of await askRoots(transport, asked.slice(i, i + CHUNK), options.types)) { if (!r.Number || byNumber.has(r.Number.toUpperCase())) continue; const oid = momentless(r._oid); - byNumber.set(r.Number.toUpperCase(), { number: r.Number, oid, type: typeOfOid(oid), name: r.Name ?? null, assetState: assetStateOf(r.AssetState) as AssetStateValue | null }); + byNumber.set(r.Number.toUpperCase(), { _oid: oid, AssetType: typeOfOid(oid), Number: r.Number, Name: r.Name ?? null, AssetState: assetStateOf(r.AssetState) as AssetStateValue | null }); } } return { @@ -142,12 +147,50 @@ export async function resolveNumbers(transport: Transport, numbers: readonly str /** * One asset by whichever shape the person has: an OID token (Story:1234 — - * used as is, no request, so `number` and `name` are null) or a number - * (resolved; null when no root knows it). Anything else is a TypeError. + * used as is, no request, so `Number`, `Name` and `AssetState` are null) or + * a number (resolved; null when no root knows it). Anything else is a + * UsageError. `resolveRefs` reads OID tokens too. */ export async function resolveRef(transport: Transport, spec: string, options: { types?: TypeCache } = {}): Promise { const text = spec.trim(); - if (isOidToken(text)) { const oid = momentless(text); return { number: null, oid, type: typeOfOid(oid), name: null, assetState: null }; } + if (isOidToken(text)) { const oid = momentless(text); return { _oid: oid, AssetType: typeOfOid(oid), Number: null, Name: null, AssetState: null }; } if (isAssetNumber(text)) return (await resolveNumbers(transport, [text], options)).found[0] ?? null; throw new UsageError(`"${spec}" is neither an asset number (S-1234) nor an OID token (Story:1234)`); } + +/** + * Several refs at once, numbers and OID tokens mixed, as a message or a + * command line mentions them: every one is read, so each answer carries its + * Number, Name and AssetState where its type has them, and one that names + * nothing is `missing`. Two requests at most, however many refs: one for + * the numbers (every number root asked at once), one for the OID tokens + * (one query per asset type among them). `schema` says which of the three + * attributes each OID's type has; an unknown select would fail the query. + */ +export async function resolveRefs(transport: Transport, schema: Schema, specs: readonly string[], options: { types?: TypeCache } = {}): Promise { + const asked = [...new Map(specs.map((s) => [s.trim().toUpperCase(), s.trim()])).values()]; + const invalid = asked.filter((s) => !isOidToken(s) && !isAssetNumber(s)); + if (invalid.length) throw new UsageError(`neither asset numbers (S-1234) nor OID tokens (Story:1234): ${invalid.join(", ")}`); + const numbers = asked.filter((s) => !isOidToken(s)); + const byNumber = new Map((numbers.length ? (await resolveNumbers(transport, numbers, options)).found : []).map((r) => [r.Number!.toUpperCase(), r])); + const oids = [...new Set(asked.filter(isOidToken).map(momentless))]; + const byType = new Map(); + for (const oid of oids) byType.set(typeOfOid(oid), [...(byType.get(typeOfOid(oid)) ?? []), oid]); + const queries: assetApi.QueryBody[] = []; + for (const [type, list] of byType) { + // A type the instance does not have has no assets: its OIDs are simply missing. + if (!(await schema.load(type))) continue; + for (let i = 0; i < list.length; i += CHUNK) { + const part = list.slice(i, i + CHUNK); + queries.push({ from: type, select: ["Number", "Name", "AssetState"].filter((a) => schema.attribute(type, a)), filter: ["ID=$oids"], with: { $oids: part }, page: { size: part.length, start: 0 } }); + } + } + const byOid = new Map(); + for (const r of (queries.length ? await assetApi.queries(transport, queries) : []).flat()) { + const oid = momentless(r._oid); + byOid.set(oid, { _oid: oid, AssetType: typeOfOid(oid), Number: r.Number ?? null, Name: r.Name ?? null, AssetState: assetStateOf(r.AssetState) as AssetStateValue | null }); + } + const isOid = (spec: string): boolean => isOidToken(spec); + const answer = (spec: string): ResolvedAsset | undefined => (isOid(spec) ? byOid.get(momentless(spec)) : byNumber.get(spec.toUpperCase())); + return { found: asked.flatMap((s) => answer(s) ?? []), missing: asked.filter((s) => !answer(s)) }; +} diff --git a/src/types/asset.ts b/src/types/asset.ts index 4d14d74..1cc973d 100644 --- a/src/types/asset.ts +++ b/src/types/asset.ts @@ -73,3 +73,23 @@ export interface CustomAttributes { export interface Asset extends CustomAttributes { _oid: Oid; } + +/** + * What an AssetState means for someone deciding what to do with the asset: + * "open" (Future, Active), "closed" (Closed), "template" (Template), + * "deleted" (Dead, Deleted), or "other" for the server's two rare states + * (OldBrokenDownStory, Deprecated) and anything unknown. Takes a name or a + * code, as assetStateOf does; null for no value. + */ +export function assetStateKind(value: unknown): "open" | "closed" | "template" | "deleted" | "other" | null { + switch (assetStateOf(value)) { + case null: return null; + case "Future": + case "Active": return "open"; + case "Closed": return "closed"; + case "Template": return "template"; + case "Dead": + case "Deleted": return "deleted"; + default: return "other"; + } +} diff --git a/src/types/command.ts b/src/types/command.ts index 38517f9..85389ce 100644 --- a/src/types/command.ts +++ b/src/types/command.ts @@ -131,6 +131,16 @@ export interface Outcome { failures: CommandFailureDetail[]; /** One slot per query, in request order; null where the query failed. */ queryResults: (Row[] | null)[]; + /** + * Indexes, in the batch as sent, of updates and operations addressed to + * one asset by its OID (`from: "Story:1"`) that matched nothing: the + * asset is not in `modified` / `operated` and no failure names the + * command. The server answers such a command with success and silence — + * the asset is gone. (An operation its type does not have is a failure, + * not this.) Empty for a command scoped by a query, where matching + * nothing is an answer, and for a guarded send, which says `conflicts`. + */ + unmatched: number[]; durationSeconds: number | null; } diff --git a/src/wire/assetApi.ts b/src/wire/assetApi.ts index de93eb2..982def0 100644 --- a/src/wire/assetApi.ts +++ b/src/wire/assetApi.ts @@ -27,7 +27,7 @@ import { ApiError, UsageError } from "../core/errors"; import type { Transport } from "../core/transport"; import type { Asset, Oid, Ref } from "../types/asset"; -import { parseViolation, type Command, type CommandFailureDetail, type CommandValue, type Outcome, type QueryBody } from "../types/command"; +import { parseViolation, type Command, type CommandFailureDetail, type CommandValue, type ExecuteBody, type Outcome, type QueryBody, type UpdateBody } from "../types/command"; import type { AssetTypeToken, AttributeLookup, AttributeTokenRef, AttributeType } from "../types/metamodel"; import { momentless } from "../types/oid"; import { fromTypeOf, resolvePath, type PathResolution } from "./select"; @@ -200,12 +200,13 @@ export function outcomeOf(response: AssetApiResponse< operated: (response.assetsOperatedOn?.oidTokens ?? []).map(momentless), failures: failuresOf(response), queryResults: response.queryResult?.results ?? [], + unmatched: [], durationSeconds: typeof response.durationSeconds === "number" ? response.durationSeconds : null }; } /** An outcome with nothing in it, to merge several sends into. */ -export const emptyOutcome = (): Outcome => ({ requestId: null, created: [], modified: [], operated: [], failures: [], queryResults: [], durationSeconds: null }); +export const emptyOutcome = (): Outcome => ({ requestId: null, created: [], modified: [], operated: [], failures: [], queryResults: [], unmatched: [], durationSeconds: null }); /** * Add one send's outcome to another's, for a batch sent in several @@ -223,6 +224,28 @@ export function mergeOutcome(into: Outcome, done return into; } +/** + * The commands of a batch that addressed one asset by OID and matched + * nothing (see Outcome.unmatched). An update that matched is in `modified` + * even when it changed no value, and an operation that ran is in + * `operated`, so absence from both with no failure is "nothing was there to + * act on". Aliased commands are left out: an alias's target is not known + * from the request. + */ +export function unmatchedOf(commands: readonly Command[], outcome: Pick): number[] { + const failed = new Set(outcome.failures.map((f) => f.index)); + // A failure the server could not place may be any command: claim nothing. + if (failed.has(null)) return []; + const modified = new Set(outcome.modified.map(momentless)), operated = new Set(outcome.operated.map(momentless)); + return commands.flatMap((c, index) => { + const body = c as Partial; + if (typeof body.from !== "string" || !/^[A-Za-z][A-Za-z0-9_]*:\d+(:\d+)?$/.test(body.from) || failed.has(index)) return []; + if ("update" in body) return modified.has(momentless(body.from)) ? [] : [index]; + if ("execute" in body) return operated.has(momentless(body.from)) ? [] : [index]; + return []; + }); +} + /** * A batch in which at least one command failed. api/asset answers 200 and * commits per command, so this is not an HTTP failure and not all-or- diff --git a/test/integration/client.test.ts b/test/integration/client.test.ts index 7798740..46149fb 100644 --- a/test/integration/client.test.ts +++ b/test/integration/client.test.ts @@ -69,6 +69,31 @@ describeInstance("client reads (live)", () => { } }); + it("a command addressed to one asset that is gone did nothing and is in `unmatched` (the server calls it a success); one that applied, a no-op and a refused one are not", async () => { + const me = await client.me(); + const made = await client.send([ + { "@c": { AssetType: "Conversation" } }, + { AssetType: "Expression", Author: me._oid, AuthoredAt: new Date().toISOString(), Content: fixtureName("unmatched"), BelongsTo: "@c" }, + { AssetType: "Story", Name: fixtureName("unmatched"), Scope: "Scope:0" } + ], { throwOnFailure: true }); + const [conversation, expression, story] = made.created as [string, string, string]; + expect(made.unmatched).toEqual([]); + try { + // The control: an update and an operation that do apply are not flagged, a no-op update included. + const applied = await client.send([{ from: story, update: { Name: fixtureName("unmatched renamed") } }, { from: story, update: { Estimate: null } }, { from: story, execute: "QuickClose" }]); + expect(applied).toMatchObject({ unmatched: [], failures: [] }); + // An operation the type does not have is a failure, which is an answer: not also flagged. + const refused = await client.send([{ from: conversation, execute: "Delete" }]); + expect(refused).toMatchObject({ operated: [], unmatched: [], failures: [{ index: 0, message: "Unknown Operation 'Conversation.Delete'" }] }); + } finally { + await client.send([{ from: story, execute: "Reactivate" }]); + await client.send([{ from: story, execute: "Delete" }, { from: expression, execute: "Delete" }]); + } + // Both are gone now (the Conversation went with its last Expression): an update by OID matches nothing, and says so. + expect(await client.send([{ from: story, update: { Name: "x" } }, { from: conversation, execute: "Join" }])).toMatchObject({ modified: [], operated: [], failures: [], unmatched: [0, 1] }); + expect(await client.get(conversation)).toBeNull(); + }); + 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/integration/resolve.test.ts b/test/integration/resolve.test.ts index 70c3198..1b1c246 100644 --- a/test/integration/resolve.test.ts +++ b/test/integration/resolve.test.ts @@ -34,15 +34,32 @@ describeInstance("resolve (live)", () => { it("one request resolves a workitem's number and another root's, case-insensitively, and reports the number nothing has as missing — the expect-zero control", async () => { const res = await client.resolve.numbers([story.number.toLowerCase(), issue.number, "S-999999999"]); expect(res.found).toEqual([ - { number: story.number, oid: story.oid, type: "Story", name: expect.stringContaining("resolve story"), assetState: "Active" }, - { number: issue.number, oid: issue.oid, type: "Issue", name: expect.stringContaining("resolve issue"), assetState: "Active" } + { _oid: story.oid, AssetType: "Story", Number: story.number, Name: expect.stringContaining("resolve story"), AssetState: "Active" }, + { _oid: issue.oid, AssetType: "Issue", Number: issue.number, Name: expect.stringContaining("resolve issue"), AssetState: "Active" } ]); expect(res.missing).toEqual(["S-999999999"]); }); it("ref resolves a number, and takes an OID token as given", async () => { - expect(await client.resolve.ref(issue.number)).toMatchObject({ oid: issue.oid, type: "Issue" }); - expect(await client.resolve.ref(story.oid)).toMatchObject({ oid: story.oid, number: null }); + expect(await client.resolve.ref(issue.number)).toMatchObject({ _oid: issue.oid, AssetType: "Issue" }); + expect(await client.resolve.ref(story.oid)).toMatchObject({ _oid: story.oid, Number: null }); expect(await client.resolve.ref("I-999999999")).toBeNull(); }); + + it("refs reads numbers and OID tokens mixed, in the order asked, in two requests; what names nothing is missing", async () => { + const calls: string[] = []; + const counting = new AgilityApiClient({ baseUrl: instance!.url }, { transport: { request: (o) => { if (!o.path.startsWith("/meta.v1")) calls.push(o.path); return t.request(o); } }, types: client.schema.cache }); + await counting.schema.load("Story"); await counting.schema.load("Issue"); await counting.schema.load("Member"); + const me = await client.me(); + calls.length = 0; + const res = await counting.resolve.refs([issue.oid, story.number.toLowerCase(), me._oid, "Story:999999999", "S-999999999", `${story.oid}:1`]); + expect(calls).toEqual(["/api/asset", "/api/asset"]); + expect(res.found).toEqual([ + { _oid: issue.oid, AssetType: "Issue", Number: issue.number, Name: expect.stringContaining("resolve issue"), AssetState: "Active" }, + { _oid: story.oid, AssetType: "Story", Number: story.number, Name: expect.stringContaining("resolve story"), AssetState: "Active" }, + { _oid: me._oid, AssetType: "Member", Number: null, Name: me.Name, AssetState: "Active" }, // a Member has no Number: not asked for, so the query is not refused + { _oid: story.oid, AssetType: "Story", Number: story.number, Name: expect.stringContaining("resolve story"), AssetState: "Active" } + ]); + expect(res.missing).toEqual(["Story:999999999", "S-999999999"]); + }); }); diff --git a/test/unit/client.test.ts b/test/unit/client.test.ts index 598fea6..2f0ff6c 100644 --- a/test/unit/client.test.ts +++ b/test/unit/client.test.ts @@ -6,7 +6,9 @@ import { ApiError, UsageError } from "../../src/core/errors"; import type { RequestOptions, Transport } from "../../src/core/transport"; import { Schema } from "../../src/services/schema"; import type { Story } from "../../src/types/assets/Story"; -import { CommandFailureError, type AssetApiResponse } from "../../src/wire/assetApi"; +import { createFetchTransport } from "../../src/core/fetchTransport"; +import { assetStateKind } from "../../src/types/asset"; +import { CommandFailureError, unmatchedOf, type AssetApiResponse } from "../../src/wire/assetApi"; import { toMetamodel, type MetamodelDocument } from "../../src/wire/meta"; /** @@ -29,6 +31,43 @@ const envelope = (over: Partial = {}): AssetApiResponse => ({ commandFailures: { commands: [], count: 0 }, queryResult: { results: [], resultMetaData: [], count: 0 }, ...over }); +describe("unmatched, asset state kinds and the fetch a transport calls", () => { + it("unmatchedOf flags an update or operation by OID that is in neither list and has no failure; a query-scoped or aliased command, a failed one, and a failure nobody can place are not flagged", () => { + const commands = [ + { from: "Story:1", update: { Name: "a" } }, // applied + { from: "Story:2:77", update: { Name: "b" } }, // nothing: gone + { from: "Conversation:3", execute: "Delete" }, // nothing: no such operation + { from: "Story:4", execute: "QuickClose" }, // failed + { from: "Story", filter: ["Number='S-0'"], update: { Name: "c" } }, // matching nothing is an answer + { "@u": { from: "Story:5", update: { Name: "d" } } }, // aliased: not known from the request + { from: "Story:6", select: ["Name"], page: { size: 1, start: 0 } }, + { AssetType: "Story", Name: "new" } + ] as never[]; + const failure = (index: number | null) => ({ index, message: "x", violation: null, echoed: {} }); + expect(unmatchedOf(commands, { modified: ["Story:1:900"], operated: [], failures: [failure(3)] })).toEqual([1, 2]); + expect(unmatchedOf(commands, { modified: ["Story:1"], operated: [], failures: [failure(null)] })).toEqual([]); + // An update does not count as an operation, nor the reverse. + expect(unmatchedOf([{ from: "Story:1", execute: "QuickClose" }], { modified: ["Story:1"], operated: [], failures: [] })).toEqual([0]); + }); + + it("assetStateKind reads a name or a code as what to do with the asset", () => { + expect(["Active", "Future", 64, "0"].map(assetStateKind)).toEqual(["open", "open", "open", "open"]); + expect(["Closed", 128, "Template", "200", "Dead", 255, "Deleted"].map(assetStateKind)).toEqual(["closed", "closed", "template", "template", "deleted", "deleted", "deleted"]); + expect([208, "Deprecated", "Whatever", null, undefined].map(assetStateKind)).toEqual(["other", "other", "other", null, null]); + }); + + it("the fetch transport calls whatever the global fetch is when the request is made, so a stub installed after the client was built is used", async () => { + const transport = createFetchTransport({ baseUrl: "https://x", retries: 0 }); + const original = globalThis.fetch; + const stub = vi.fn(async () => new Response("[[]]", { status: 200, headers: { "content-type": "application/json" } })); + globalThis.fetch = stub as unknown as typeof fetch; + try { + expect(await transport.request({ method: "POST", path: "/query.v1", body: [], responseType: "json" })).toEqual([[]]); + } finally { globalThis.fetch = original; } + expect(stub).toHaveBeenCalledOnce(); + }); +}); + describe("client: reads", () => { it("query goes to query.v1, idempotent, after loading the types it touches from meta.v1, and translates the rows", async () => { const t = fake((o) => (o.path.startsWith("/meta.v1/") ? document.AssetTypes[o.path.slice("/meta.v1/".length)] : [[wireStory]])); @@ -140,7 +179,7 @@ describe("outcomeOf: a partial envelope is a contract", () => { it("every field has a default, so a fake that sends only queryResult yields a complete Outcome", async () => { const { outcomeOf } = await import("../../src/wire/assetApi"); const o = outcomeOf({ queryResult: { results: [[]], resultMetaData: [], count: 1 } } as never); - expect(o).toEqual({ requestId: null, created: [], modified: [], operated: [], failures: [], queryResults: [[]], durationSeconds: null }); + expect(o).toEqual({ requestId: null, created: [], modified: [], operated: [], failures: [], queryResults: [[]], unmatched: [], durationSeconds: null }); }); }); diff --git a/test/unit/resolve.test.ts b/test/unit/resolve.test.ts index b94d986..7372b07 100644 --- a/test/unit/resolve.test.ts +++ b/test/unit/resolve.test.ts @@ -44,8 +44,8 @@ describe("resolve", () => { expect(q.page.size).toBe(3); } expect(res.found).toEqual([ - { number: "S-21622", oid: "Story:145845", type: "Story", name: "One", assetState: "Active" }, - { number: "I-01001", oid: "Issue:7", type: "Issue", name: "Two", assetState: "Closed" } + { _oid: "Story:145845", AssetType: "Story", Number: "S-21622", Name: "One", AssetState: "Active" }, + { _oid: "Issue:7", AssetType: "Issue", Number: "I-01001", Name: "Two", AssetState: "Closed" } ]); expect(res.missing).toEqual(["S-99999999"]); }); @@ -65,7 +65,7 @@ describe("resolve", () => { const roots = ROOTS.filter((r) => r !== "Okr"); const missingOkr = envelope(roots.map(() => []), [{ "@x$auto-aliased": { from: "Okr" }, error: { message: "Unknown AssetType: Okr", sourceCommandIndex: ROOTS.indexOf("Okr") } }]); const t = fakeTransport(missingOkr, answer({ Workitem: [{ _oid: "Story:1", Name: "A", Number: "S-1", AssetState: "Active" }] }, roots), answer({}, roots)); - expect((await resolveNumbers(t, ["S-1"])).found.map((f) => f.oid)).toEqual(["Story:1"]); + expect((await resolveNumbers(t, ["S-1"])).found.map((f) => f._oid)).toEqual(["Story:1"]); expect((t.calls[1]!.body as Sent).map((q) => q.from)).toEqual(roots); // Remembered for this transport: the next call does not ask Okr at all. await resolveNumbers(t, ["S-2"]); @@ -85,7 +85,7 @@ describe("resolve", () => { expect(bob.calls).toHaveLength(1); expect((bob.calls[0]!.body as Sent).map((q) => q.from)).toEqual(roots); // A template's state comes back as its code; it reads by name. - expect(found.found[0]!.assetState).toBe("Template"); + expect(found.found[0]!.AssetState).toBe("Template"); }); it("any other failure is the caller's to see", async () => { @@ -96,9 +96,9 @@ describe("resolve", () => { it("resolveRef takes an OID token as is, without a request; a number by resolving it; null when nothing has that number; anything else is a UsageError", async () => { const none = fakeTransport(); - expect(await resolveRef(none, " Story:1234:55 ")).toEqual({ number: null, oid: "Story:1234", type: "Story", name: null, assetState: null }); + expect(await resolveRef(none, " Story:1234:55 ")).toEqual({ _oid: "Story:1234", AssetType: "Story", Number: null, Name: null, AssetState: null }); expect(none.calls).toHaveLength(0); - expect(await resolveRef(fakeTransport(answer({ Workitem: [{ _oid: "Defect:9", Name: "D", Number: "D-9", AssetState: "Active" }] })), "d-9")).toMatchObject({ oid: "Defect:9", type: "Defect", number: "D-9" }); + expect(await resolveRef(fakeTransport(answer({ Workitem: [{ _oid: "Defect:9", Name: "D", Number: "D-9", AssetState: "Active" }] })), "d-9")).toMatchObject({ _oid: "Defect:9", AssetType: "Defect", Number: "D-9" }); expect(await resolveRef(fakeTransport(answer({})), "D-404")).toBeNull(); await expect(resolveRef(none, "fix the thing")).rejects.toThrow(UsageError); expect(isAssetNumber("TK-12")).toBe(true); diff --git a/test/unit/testing.test.ts b/test/unit/testing.test.ts index b8d633a..4deb9a9 100644 --- a/test/unit/testing.test.ts +++ b/test/unit/testing.test.ts @@ -111,10 +111,10 @@ describe("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" }], + found: [{ _oid: "Defect:9", AssetType: "Defect", Number: "D-00009", Name: "Crash", AssetState: "Closed" }, { _oid: "Story:1", AssetType: "Story", Number: "S-01001", Name: "Logon", AssetState: "Active" }], missing: ["S-99999"] }); - expect(await fake.resolve.ref("S-01001")).toMatchObject({ oid: "Story:1" }); + expect(await fake.resolve.ref("S-01001")).toMatchObject({ _oid: "Story:1" }); expect(await new FakeAgilityClient().resolve.ref("S-1")).toBeNull(); }); From 62a589ebaba8bdf8d83e6ba58369d39034ba6c7c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:28:27 +0000 Subject: [PATCH 05/17] alpha.8: batch.reversible requires the receipt's format, and says so when it is missing A caller that picked { reverse, after } by hand (type-correct before) had every receipt refused as "format undefined". The version is now required by the type, and a missing one is named for what it is. client.data's doc says why it has one member. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 5 ++++- src/client.ts | 7 +++++-- src/index.ts | 2 +- src/services/batch.ts | 15 +++++++++++++-- test/unit/batch.test.ts | 7 +++++-- 5 files changed, 28 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aa1504f..6a58ca5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -84,7 +84,10 @@ Each entry has the line a consumer follows to migrate. receipts: reverse one with `{ force: true }`, which sends its reverse without checking whether anyone changed the assets since; or run the batch again and keep the new receipt. `isReceipt(value)` tells a - current receipt from anything else before calling. + current receipt from anything else before calling. `batch.reversible` + now requires the receipt's `receipt` field in what it is given: pass + the whole receipt, or pick `receipt` along with `reverse`, `after` and + `changedAt`. - **An unguardable reason has a `code`** (`aliasedWrite`, `bareAliasFrom`, `inlineCreate`, `noMoment`). Migration: branch on `reason.code`, not on the words of `reason.reason`. diff --git a/src/client.ts b/src/client.ts index 1b3fbb4..4b6f9ea 100644 --- a/src/client.ts +++ b/src/client.ts @@ -257,7 +257,10 @@ export class AgilityApiClient { * query's (`select`, `filter`), and rows follow the rule every read * follows: a relation you select is a Ref, a path you select by name is * at `row[path]`, and nothing arrives that you did not select. For - * everything else use `query` / `queryPage`. + * everything else use `query` / `queryPage`. (`data` has this one member + * on purpose: it is the cross-type text search until a `client.search` + * exists, and stays here so that nobody needs the wire modules for an + * everyday read.) */ readonly data = { list: (type: string, params: rest1.ReadParams) => rest1.list(this.transport, type, params) @@ -376,7 +379,7 @@ export class AgilityApiClient { */ readonly batch = { run: (commands: assetApi.Command[], options: batch.BatchOptions) => batch.runBatch(this.transport, this.schema, commands, options), - reversible: (receipt: Parameters[1], options?: { force?: boolean }) => batch.reversible(this.transport, receipt, options) + reversible: (receipt: batch.ReversibleReceipt, options?: { force?: boolean }) => batch.reversible(this.transport, receipt, options) }; /** diff --git a/src/index.ts b/src/index.ts index ed65160..ddc0433 100644 --- a/src/index.ts +++ b/src/index.ts @@ -44,4 +44,4 @@ export type { Resolution, ResolvedAsset } from "./services/resolve"; export { ConflictError, GuardedPassError, UnguardableError, unguardable } from "./services/guard"; export type { GuardedOptions, GuardedResult, Unguardable, UnguardableCode } from "./services/guard"; export { BatchRecordError, BatchSendError, ReceiptVersionError, isReceipt } from "./services/batch"; -export type { BatchOptions, Described, Drifted, NameLookupFailure, Named, Receipt, Reverse } from "./services/batch"; +export type { BatchOptions, Described, Drifted, NameLookupFailure, Named, Receipt, Reverse, ReversibleReceipt } from "./services/batch"; diff --git a/src/services/batch.ts b/src/services/batch.ts index d258e64..1ceb696 100644 --- a/src/services/batch.ts +++ b/src/services/batch.ts @@ -494,7 +494,9 @@ async function versionsOf(transport: Transport, oids: Oid[]): Promise !!value && typeof /** An asset a reverse leaves alone because someone changed it since the batch: its Moment then and now (null: gone), and the same as readable times when known. */ export interface Drifted { oid: Oid; was: string; now: string | null; wasChangedAt: string | null; nowChangedAt: string | null } +/** + * What `reversible` reads of a receipt: pass the receipt itself. A caller + * that picks fields by hand must pick `receipt` (its format) too — it is + * required here so that leaving it out is a compile error and not a + * refusal at run time; its type is open because a receipt read back from a + * file may be of any format. + */ +export type ReversibleReceipt = Pick & { receipt: unknown; changedAt?: Record }; + /** * A receipt's reverse batch, minus the assets someone changed since * the batch (their Moment is no longer the one recorded just after it), @@ -519,7 +530,7 @@ export interface Drifted { oid: Oid; was: string; now: string | null; wasChanged * it: two commands on one asset, which runBatch sends in two guarded passes * (the Delete only if the Reactivate applied). `reactivated` lists them. */ -export async function reversible(transport: Transport, receipt: Pick & { receipt?: unknown; changedAt?: Record }, options: { force?: boolean } = {}): Promise<{ commands: Command[]; drifted: Drifted[]; reactivated: Oid[] }> { +export async function reversible(transport: Transport, receipt: ReversibleReceipt, options: { force?: boolean } = {}): Promise<{ commands: Command[]; drifted: Drifted[]; reactivated: Oid[] }> { const targets = receipt.reverse.commands.map((c) => momentless(String(bodyOf(c).from))); const current = receipt.receipt === 2; if (!current && !options.force) throw new ReceiptVersionError(receipt.receipt, targets); diff --git a/test/unit/batch.test.ts b/test/unit/batch.test.ts index 1e704f3..0a59c31 100644 --- a/test/unit/batch.test.ts +++ b/test/unit/batch.test.ts @@ -279,8 +279,11 @@ group("batch", () => { expect(error).toMatchObject({ kind: "usage", code: "RECEIPT_VERSION", status: 0, receiptVersion: 1, targets: ["Story:1"] }); expect(error.message).toMatch(/before 1\.0\.0-alpha\.8.*Reverse it with force.*or run the batch again/); expect(await reversible(t, old, { force: true })).toEqual({ commands: old.reverse.commands, drifted: [], reactivated: [] }); - // A receipt with no version at all is treated the same. - await expect(reversible(t, { after: {}, reverse: old.reverse })).rejects.toBeInstanceOf(ReceiptVersionError); + // Fields picked by hand without the version: a compile error; for a caller the types do not reach, a refusal that says what is missing. + // @ts-expect-error `receipt` (the format) is required + const picked = reversible(t, { after: {}, reverse: old.reverse }); + await expect(picked).rejects.toThrow(/has no format version.*pass the whole receipt/); + await expect(picked).rejects.toMatchObject({ code: "RECEIPT_VERSION", receiptVersion: undefined }); expect(t.calls).toHaveLength(0); }); }); From f032029664da23eb61db586b39b65f90c5cb3e43 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:30:52 +0000 Subject: [PATCH 06/17] alpha.8: client.explain says an error to a person One Explanation per failed command (from a CommandFailureError, an Outcome or its failures), or one for any other error: a short sentence ("Project is required.") with the instance's own labels for the attribute and the asset type, the parts it was made from, and the server's own sentence for the whole token where loc-2 has one. Resolution failures are read as well as Violations. One loc-2 request at most, none for an error that is not about commands, and a label that cannot be fetched is replaced by the attribute's name, never an error. Built from what the instance answers (loc-2 localizes a Required violation usefully and an Invalid one emptily, so the sentence is made here and loc-2's is offered beside it). Two consumers each wrote this by hand. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 9 +++ README.md | 1 + src/client.ts | 15 ++++ src/index.ts | 1 + src/services/explain.ts | 135 ++++++++++++++++++++++++++++++++ src/services/index.ts | 1 + test/integration/client.test.ts | 18 +++++ test/unit/explain.test.ts | 80 +++++++++++++++++++ 8 files changed, 260 insertions(+) create mode 100644 src/services/explain.ts create mode 100644 test/unit/explain.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a58ca5..7e31aa1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -140,6 +140,15 @@ Each entry has the line a consumer follows to migrate. ### Added +- **`client.explain(error)`**: an error said to a person. One + `Explanation` per failed command (from a `CommandFailureError`, an + `Outcome` or its `failures`), or one for any other error: a short + `sentence` ("Project is required.") with the instance's own labels for + the attribute and the asset type, the parts it was made from (`rule`, + `attribute`, `attributeLabel`, `typeLabel`), and the server's own + `localized` sentence where it has one. `Resolution'…` failures are read + too. One loc-2 request at most. Migration: a consumer's own failure + patterns and three-tag loc-2 lookups can go. - **`client.resolve.refs(specs)`**: numbers and OID tokens mixed, each one read, in two requests at most; what names nothing is `missing`. - **`Outcome.unmatched`**: the indexes of updates and operations diff --git a/README.md b/README.md index 0c6924b..9a81369 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ npm test | What a form needs | `client.fields.describe(type, scope)` | Required, visible and important attributes. | | Files | `client.attachments.*`, `client.embeddedImages.*` | | | A link for a person | `client.urls.asset(oidOrNumber)` | | +| An error, said to a person | `client.explain(error)` | "Project is required.", with the instance's labels. | | Labels in the instance's words | `client.localize(tags)` | | Every row follows one rule, whichever call read it: **a relation you select is a Ref (`{ _oid }`); a path you select by name is at `row[path]` (`row["Status.Name"]`); nothing arrives that you did not select.** Select both `Owners` and `Owners.Name` and you get the Refs and, beside them, a parallel array at `"Owners.Name"`. To get attributes on the related rows themselves, use a sub-select: `{ from: "Owners", select: ["Name"] }` gives `row.Owners[i].Name`. (rest-1 also puts the display attributes it sends unasked on the Refs of a relation you selected.) diff --git a/src/client.ts b/src/client.ts index 4b6f9ea..2216b77 100644 --- a/src/client.ts +++ b/src/client.ts @@ -4,6 +4,7 @@ import { createFetchTransport } from "./core/fetchTransport"; import type { Transport } from "./core/transport"; import * as attachments from "./services/attachments"; import * as batch from "./services/batch"; +import * as explainService from "./services/explain"; import * as fieldsService from "./services/fields"; import * as guard from "./services/guard"; import * as resolve from "./services/resolve"; @@ -249,6 +250,20 @@ export class AgilityApiClient { return loc2.localize(this.transport, tags, options); } + /** + * An error, said to a person: one Explanation per failed command (from a + * CommandFailureError, an Outcome or its `failures`), or one for any + * other error. Each has a short `sentence` — "Project is required.", + * with the instance's own label for the attribute — and the parts it was + * made from (`rule`, `attribute`, `attributeLabel`, `typeLabel`, the + * server's own `localized` sentence where it has one). One loc-2 request + * at most; a label it cannot get is replaced by the attribute's name, + * never an error. + */ + explain(error: unknown, options?: loc2.LocalizeOptions): Promise { + return explainService.explain(this.transport, error, options); + } + /** * rest-1's list read, for what the other reads cannot do: full-text * `find` / `findin` across types with one order and a total, a diff --git a/src/index.ts b/src/index.ts index ddc0433..efecabb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -39,6 +39,7 @@ export type { Schema } from "./services/schema"; export { AttachmentUploadError, INLINE_LIMIT } from "./services/attachments"; export type { AddOptions as AttachmentAddOptions, AttachmentFile, AttachmentInfo, GetOptions as AttachmentGetOptions, ListOptions as AttachmentListOptions, ListedAttachment } from "./services/attachments"; export { fromBase64, toBase64 } from "./wire/attachment"; +export type { Explanation } from "./services/explain"; export { isAssetNumber } from "./services/resolve"; export type { Resolution, ResolvedAsset } from "./services/resolve"; export { ConflictError, GuardedPassError, UnguardableError, unguardable } from "./services/guard"; diff --git a/src/services/explain.ts b/src/services/explain.ts new file mode 100644 index 0000000..b6425c1 --- /dev/null +++ b/src/services/explain.ts @@ -0,0 +1,135 @@ +/** + * The explain service: an error, said to a person. Every consumer wrote + * this once — a chat bot answered "Agility didn't accept that" while + * holding the violation that said why, a CLI re-parsed failure messages + * with its own patterns and asked loc-2 for three tags per failure. + * + * A failed command's message is a token (`Violation'Required' + * AttributeDefinition'Scope'Story`, `Resolution'Unresolved'Story.Status' + * StoryStatus`), not a sentence. This reads the token, asks loc-2 once for + * every label it needs — the attribute's and the asset type's, in the + * instance's own words ("Project", "Backlog Item"), and the server's own + * sentence for the whole token where it has one — and answers a short + * sentence plus the parts, so a caller can use either. + * + * Seen live (the API-testing instance, 2026-11-26): + * - loc-2 localizes a whole violation token, usefully for Required ("…The + * attribute Project is required and was not supplied…") and emptily for + * Invalid ("…has encountered an invalid ."), which is why the short + * sentence is built here from the labels and loc-2's is offered beside it. + * - an attribute is named as a loc-2 tag (AttributeDefinition'Scope'Story) + * or as a token (Story.Owners); a Resolution failure names the attribute + * as a token and then the related type. + * - loc-2 answers a tag it does not know with the tag itself. + */ +import { ApiError } from "../core/errors"; +import type { Transport } from "../core/transport"; +import type { CommandFailureDetail, Outcome } from "../types/command"; +import type { AttributeTokenRef } from "../types/metamodel"; +import { parseViolation } from "../types/command"; +import * as loc2 from "../wire/loc2"; + +export interface Explanation { + /** One short sentence for a person. English, with the instance's own labels for attributes and asset types. */ + sentence: string; + /** The failed command's index in the batch, when this explains one; null otherwise. */ + index: number | null; + /** What was violated: Required, Invalid, Unresolved, Ambiguous, AssetCannotDeleteClosed, …; null when the message is not such a token. */ + rule: string | null; + /** The attribute at fault ("Story.Scope"), when the message names one. */ + attribute: AttributeTokenRef | null; + /** That attribute as the instance labels it ("Project"); its bare name when the instance has no label. */ + attributeLabel: string | null; + /** The asset type as the instance labels it ("Backlog Item"); its token when the instance has no label. */ + typeLabel: string | null; + /** The server's own sentence for the whole message, when loc-2 has one; null when it only echoes the token. */ + localized: string | null; + /** The message as the server sent it. */ + message: string; +} + +interface Problem { rule: string | null; attribute: AttributeTokenRef | null; related: string | null } + +/** What a failure message says went wrong: a Violation (parseViolation), a Resolution, or nothing readable. */ +function problemOf(message: string): Problem { + const violation = parseViolation(message); + if (violation) return { rule: violation.rule, attribute: violation.attribute, related: null }; + const parts = message.trim().split("'"); + if (parts[0] === "Resolution" && parts[1] && /^[A-Za-z]\w*\.[A-Za-z]\w*$/.test(parts[2] ?? "")) return { rule: parts[1], attribute: parts[2] as AttributeTokenRef, related: parts[3] || null }; + return { rule: null, attribute: null, related: null }; +} + +const attributeTag = (attribute: AttributeTokenRef): string => { const [type, name] = attribute.split("."); return `AttributeDefinition'${name}'${type}`; }; +const typeTag = (type: string): string => `AssetType'${type}`; +/** A token that looks like one loc-2 would know: no spaces, apostrophe-delimited. A plain sentence is not asked about. */ +const isTag = (message: string): boolean => /^[A-Za-z]\w*'[^\s]+$/.test(message.trim()); + +function sentenceOf(problem: Problem, label: string | null, related: string | null, localized: string | null, message: string): string { + if (label) { + switch (problem.rule) { + case "Required": return `${label} is required.`; + case "Invalid": return `${label} is not valid.`; + case "Unresolved": return `${label}: no ${related ?? "asset"} matches the value given.`; + case "Ambiguous": return `${label}: more than one ${related ?? "asset"} matches the value given.`; + } + return localized ?? `${label}: ${problem.rule ?? message}`; + } + return localized ?? message; +} + +/** The failures to explain, from whatever the caller holds: an Outcome, a list of failures, or a thrown error. */ +function failuresOf(input: unknown): CommandFailureDetail[] | null { + if (Array.isArray(input)) return input as CommandFailureDetail[]; + if (input && typeof input === "object" && Array.isArray((input as { failures?: unknown }).failures)) return (input as Pick).failures; + return null; +} + +/** A sentence for an error that is not a list of failed commands, by its kind. */ +function sentenceForError(error: unknown): string { + if (!(error instanceof ApiError)) return error instanceof Error ? error.message : String(error); + switch (error.kind) { + case "auth": return "Agility did not accept the sign-in: the token is missing, wrong or no longer valid."; + case "forbidden": return "Agility refused: this member is not allowed to do that."; + case "notFound": return `Agility has nothing there: ${error.message}`; + case "transient": return `Agility could not be reached, or is busy (${error.message}). The same request may work in a moment.`; + case "aborted": return "The request was cancelled."; + case "protocol": return `Agility answered something unexpected: ${error.message}`; + // usage, invalid, conflict and the rest: the message is already a sentence (the SDK's own, or the server's). + default: return error.message; + } +} + +/** + * Explain an error, an Outcome's failures, or a list of failures: one + * Explanation per failed command, or one for an error that is not about + * commands. One loc-2 request at most, none when there is nothing to + * label. Never throws for a label it could not get: the explanation then + * uses the attribute's and type's own names. + */ +export async function explain(transport: Transport, input: unknown, options: loc2.LocalizeOptions = {}): Promise { + const failures = failuresOf(input); + if (!failures) return [{ sentence: sentenceForError(input), index: null, rule: null, attribute: null, attributeLabel: null, typeLabel: null, localized: null, message: input instanceof Error ? input.message : String(input) }]; + const problems = failures.map((f) => problemOf(f.message)); + const tags = new Set(); + failures.forEach((f, i) => { + const p = problems[i]!; + if (isTag(f.message)) tags.add(f.message.trim()); + if (p.attribute) { tags.add(attributeTag(p.attribute)); tags.add(typeTag(p.attribute.split(".")[0]!)); } + if (p.related) tags.add(typeTag(p.related)); + }); + let labels: loc2.Localizations = {}; + try { + if (tags.size) labels = await loc2.localize(transport, [...tags], options); + } catch { /* labels are a nicety: the names below stand in */ } + // loc-2 answers a tag it does not know with the tag itself: that is "no label". + const label = (tag: string): string | null => { const l = labels[tag]; return typeof l === "string" && l && l !== tag ? l : null; }; + return failures.map((f, i) => { + const p = problems[i]!; + const [type, name] = p.attribute ? p.attribute.split(".") : [null, null]; + const attributeLabel = p.attribute ? label(attributeTag(p.attribute)) ?? name! : null; + const typeLabel = type ? label(typeTag(type)) ?? type : null; + const related = p.related ? label(typeTag(p.related)) ?? p.related : null; + const localized = isTag(f.message) ? label(f.message.trim()) : null; + return { sentence: sentenceOf(p, attributeLabel, related, localized, f.message), index: f.index, rule: p.rule, attribute: p.attribute, attributeLabel, typeLabel, localized, message: f.message }; + }); +} diff --git a/src/services/index.ts b/src/services/index.ts index 72118df..22fdd8e 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -8,6 +8,7 @@ */ export * as attachments from "./attachments"; export * as batch from "./batch"; +export * as explain from "./explain"; export * as fields from "./fields"; export * as guard from "./guard"; export * as resolve from "./resolve"; diff --git a/test/integration/client.test.ts b/test/integration/client.test.ts index 46149fb..98b4ba9 100644 --- a/test/integration/client.test.ts +++ b/test/integration/client.test.ts @@ -94,6 +94,24 @@ describeInstance("client reads (live)", () => { expect(await client.get(conversation)).toBeNull(); }); + it("explain says real failures in a sentence with the instance's labels, in one loc-2 request; nothing is created", async () => { + const outcome = await client.send([ + { AssetType: "Story", Name: fixtureName("explain") }, // no Scope + { AssetType: "Story", Name: fixtureName("explain"), Scope: "Scope:0", Status: "NoSuchStatus" }, // nothing by that name + { AssetType: "Story", Name: fixtureName("explain"), Scope: "Scope:0", Estimate: "abc" } // not a number + ]); + expect(outcome.created).toEqual([]); // the control: all three were refused + const explained = await client.explain(outcome); + expect(explained.map((e) => [e.index, e.rule, e.attribute])).toEqual([[0, "Required", "Story.Scope"], [1, "Unresolved", "Story.Status"], [2, null, null]]); + // The instance's own words for Story.Scope and for Story (they are configurable, so only their presence is asserted). + expect(explained[0]!.attributeLabel).toEqual(expect.any(String)); + expect(explained[0]!.sentence).toBe(`${explained[0]!.attributeLabel} is required.`); + expect(explained[0]!.localized).toMatch(/required/i); + expect(explained[0]!.typeLabel).not.toBe("AssetType'Story"); + expect(explained[1]!.sentence).toMatch(/: no .+ matches the value given\.$/); + expect(explained[2]!.sentence).toBe(outcome.failures[2]!.message); + }); + 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/explain.test.ts b/test/unit/explain.test.ts new file mode 100644 index 0000000..a7f5fe2 --- /dev/null +++ b/test/unit/explain.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it, vi } from "vitest"; +import { ApiError, UsageError } from "../../src/core/errors"; +import type { RequestOptions, Transport } from "../../src/core/transport"; +import { explain } from "../../src/services/explain"; +import { FakeAgilityClient } from "../../src/testing"; +import { parseViolation } from "../../src/types/command"; + +/** + * An error, said to a person. The failure messages and loc-2's answers are + * copied from the API-testing instance (2026-11-26). + */ +const LOC2: Record = { + "Violation'Required'AttributeDefinition'Scope'Story": "Agility Warning: The attribute Project is required and was not supplied. This change was not saved. Please alert your administrator if you continue to have an issue.", + "AttributeDefinition'Scope'Story": "Project", + "AssetType'Story": "Backlog Item", + "Violation'AssetCannotDeleteClosed": "Agility Warning: Attempting to delete a closed item. This change was not saved." +}; +function loc2(): Transport & { calls: RequestOptions[] } { + const calls: RequestOptions[] = []; + // loc-2 answers a tag it does not know with the tag itself. + const request = vi.fn(async (o: RequestOptions) => { calls.push(o); const tags = JSON.parse(decodeURIComponent(o.path.slice(o.path.indexOf("?") + 1))) as string[]; return Object.fromEntries(tags.map((t) => [t, LOC2[t] ?? t])); }); + return { request: request as Transport["request"], calls }; +} +const failure = (index: number, message: string) => ({ index, message, violation: parseViolation(message), echoed: {} }); + +describe("explain", () => { + it("says each failed command in a sentence, with the instance's labels, from one loc-2 request", async () => { + const t = loc2(); + const explained = await explain(t, [ + failure(0, "Violation'Required'AttributeDefinition'Scope'Story"), + failure(1, "Resolution'Unresolved'Story.Status'StoryStatus"), + failure(2, "Input string was not in a correct format."), + failure(3, "Violation'Invalid'Story.Owners"), + failure(4, "Violation'AssetCannotDeleteClosed") + ]); + expect(t.calls).toHaveLength(1); + expect(explained.map((e) => e.sentence)).toEqual([ + "Project is required.", + "Status: no StoryStatus matches the value given.", + "Input string was not in a correct format.", + "Owners is not valid.", + "Agility Warning: Attempting to delete a closed item. This change was not saved." + ]); + expect(explained[0]).toEqual({ + sentence: "Project is required.", index: 0, rule: "Required", attribute: "Story.Scope", attributeLabel: "Project", typeLabel: "Backlog Item", + localized: LOC2["Violation'Required'AttributeDefinition'Scope'Story"], message: "Violation'Required'AttributeDefinition'Scope'Story" + }); + // A Resolution failure names the attribute as a token and then the related type; loc-2 has no label for these here, so their own names stand in. + expect(explained[1]).toMatchObject({ rule: "Unresolved", attribute: "Story.Status", attributeLabel: "Status", typeLabel: "Backlog Item", localized: null }); + // A plain sentence is not a tag: nothing is asked about it and nothing is invented. + expect(explained[2]).toMatchObject({ rule: null, attribute: null, attributeLabel: null, localized: null }); + expect(explained[4]).toMatchObject({ rule: "AssetCannotDeleteClosed", attribute: null }); + }); + + it("takes an Outcome, a CommandFailureError or its failures alike; no failures, no request", async () => { + const fake = new FakeAgilityClient().onLocalize(LOC2).onSend({ failures: [{ index: 0, message: "Violation'Required'AttributeDefinition'Scope'Story" }] }); + const outcome = await fake.send([{ AssetType: "Story", Name: "x" }]); + const thrown = await fake.send([{ AssetType: "Story", Name: "x" }], { throwOnFailure: true }).catch((e: unknown) => e); + for (const input of [outcome, thrown, outcome.failures]) expect((await fake.explain(input)).map((e) => e.sentence)).toEqual(["Project is required."]); + const t = loc2(); + expect(await explain(t, { failures: [] })).toEqual([]); + expect(t.calls).toHaveLength(0); + }); + + it("an error that is not about commands gets one sentence by its kind, and no request; a label that cannot be fetched never becomes an error", async () => { + const t = loc2(); + const say = async (e: unknown) => (await explain(t, e))[0]!.sentence; + expect(await say(new ApiError("Unauthorized", 401))).toBe("Agility did not accept the sign-in: the token is missing, wrong or no longer valid."); + expect(await say(new ApiError("Forbidden", 403))).toBe("Agility refused: this member is not allowed to do that."); + expect(await say(new ApiError("fetch failed", 0, "NETWORK_ERROR"))).toBe("Agility could not be reached, or is busy (fetch failed). The same request may work in a moment."); + expect(await say(new ApiError("Request aborted", 0, "ABORTED"))).toBe("The request was cancelled."); + // The SDK's own sentences and the server's (a rejected query) are said as they are. + expect(await say(new UsageError("query of Story without a page: every read must be bounded"))).toBe("query of Story without a page: every read must be bounded"); + expect(await say(new ApiError("Invalid WHERE parameter; Invalid QueryFilter2 token Nope=1", 400, "QUERY_REJECTED"))).toBe("Invalid WHERE parameter; Invalid QueryFilter2 token Nope=1"); + expect(await say(new Error("boom"))).toBe("boom"); + expect(t.calls).toHaveLength(0); + const down: Transport = { request: async () => { throw new ApiError("down", 503); } }; + expect((await explain(down, [failure(0, "Violation'Required'AttributeDefinition'Scope'Story")]))[0]).toMatchObject({ sentence: "Scope is required.", attributeLabel: "Scope", typeLabel: "Story", localized: null }); + }); +}); From 7978ffc02645ddd968eda830303fcebc9e7e0507 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:33:05 +0000 Subject: [PATCH 07/17] alpha.8: a conformance suite for a custom Transport, in /testing transportConformance(make) answers the SDK's expectations of a Transport as named checks any test runner can run: a path stays inside the base URL, bodies are sent in the shape given, responses are read as asked, onResponse runs before the body with case-insensitive headers, a 304 with acceptNotModified resolves undefined, a refused response is worded as apiErrorFromResponse words it, an abort is ABORTED and a failed connection NETWORK_ERROR, and responseType json insists. The SDK's fetch transport runs the suite, and a test shows it catching three broken transports. From a browser app consumer's nine hand-written rules. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 10 ++ README.md | 1 + src/testing/index.ts | 3 + src/testing/transportConformance.ts | 190 +++++++++++++++++++++++++ test/unit/transportConformance.test.ts | 37 +++++ 5 files changed, 241 insertions(+) create mode 100644 src/testing/transportConformance.ts create mode 100644 test/unit/transportConformance.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e31aa1..dca8770 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -149,6 +149,16 @@ Each entry has the line a consumer follows to migrate. `localized` sentence where it has one. `Resolution'…` failures are read too. One loc-2 request at most. Migration: a consumer's own failure patterns and three-tag loc-2 lookups can go. +- **`transportConformance(make)`** from `@versionone/agility-sdk/testing`: + the SDK's expectations of a `Transport` as a list of named checks, + runnable against a custom transport with any test runner (path inside + the base URL, body encodings, response types, `onResponse`, a 304 with + `acceptNotModified`, errors worded as `apiErrorFromResponse` words + them, abort and connection failure, `BAD_JSON`). `fetchFrom(server)` + adapts the suite's stand-in network for a transport built on fetch. The + SDK's own fetch transport runs it. A new duty of a Transport is from + now on a new check here and a "Breaking" line. (a browser app consumer + with an axios transport.) - **`client.resolve.refs(specs)`**: numbers and OID tokens mixed, each one read, in two requests at most; what names nothing is `missing`. - **`Outcome.unmatched`**: the indexes of updates and operations diff --git a/README.md b/README.md index 9a81369..d28cd1d 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,7 @@ expect(fake.sent[0]).toEqual([{ from: "Story:1", execute: "QuickClose" }]); - 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. +- A custom `Transport` has its own suite: `transportConformance(make)` answers the SDK's expectations of a transport as named checks (`for (const c of transportConformance(make)) it(c.name, c.run)`), and the SDK's fetch transport runs the same ones. - 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/ diff --git a/src/testing/index.ts b/src/testing/index.ts index f6eae23..4f4362f 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -14,6 +14,9 @@ * integration test against an instance is for. */ import { AgilityApiClient } from "../client"; + +export { CONFORMANCE_BASE_URL, fetchFrom, transportConformance } from "./transportConformance"; +export type { ConformanceCheck, ConformanceRequest, ConformanceResponse, ConformanceServer } from "./transportConformance"; import type { ClientConfig } from "../core/clientConfig"; import { ApiError, UsageError, apiErrorFromResponse } from "../core/errors"; import type { RequestOptions, Transport } from "../core/transport"; diff --git a/src/testing/transportConformance.ts b/src/testing/transportConformance.ts new file mode 100644 index 0000000..cd61345 --- /dev/null +++ b/src/testing/transportConformance.ts @@ -0,0 +1,190 @@ +/** + * A conformance suite for a custom Transport: the SDK's own expectations + * of one, runnable against any implementation with any test runner. A + * consumer that wraps its HTTP client (axios, an instrumented fetch) as a + * Transport would otherwise re-derive these rules from the fetch + * transport's source, and learn of a new one when something breaks. + * + * ```ts + * import { transportConformance } from "@versionone/agility-sdk/testing"; + * + * for (const check of transportConformance((server) => makeMyTransport({ baseUrl: "https://agility.example.com/Instance/", adapter: server }))) { + * it(check.name, check.run); // Jest, Vitest, node:test — each check throws an Error when the rule is broken + * } + * ``` + * + * `server` stands in for the network: the suite hands it to your factory, + * and your factory makes the transport's HTTP client call it for every + * request (an axios adapter, a `fetch` replacement — `fetchFrom(server)` + * is one). The base URL must be `https://agility.example.com/Instance/`, + * so the suite can tell that a path stays inside the instance. + * + * When the SDK asks something new of a Transport, a check is added here and + * the change is listed under "Breaking" in the changelog. + */ +import { ApiError, apiErrorFromResponse } from "../core/errors"; +import type { Transport } from "../core/transport"; + +/** A request as it reaches the network: what the suite inspects. Header names in lower case. */ +export interface ConformanceRequest { + method: string; + /** The absolute URL, query string included. */ + url: string; + headers: Record; + /** The body as the HTTP client was given it: a string, bytes, a Blob, a FormData, or undefined. */ + body?: unknown; + signal?: AbortSignal; +} + +/** What the suite's server answers: a response, or "network-error" for a connection that fails. */ +export type ConformanceResponse = { status: number; headers?: Record; body?: string | Uint8Array } | "network-error"; + +/** The stand-in for the network: call it with each request; it answers what the current check scripted. */ +export type ConformanceServer = (request: ConformanceRequest) => Promise; + +export interface ConformanceCheck { name: string; run: () => Promise } + +/** The base URL a transport under test must be built with. */ +export const CONFORMANCE_BASE_URL = "https://agility.example.com/Instance/"; + +/** A `fetch` that answers from the suite's server: for a transport built on fetch. */ +export function fetchFrom(server: ConformanceServer): typeof fetch { + return (async (input: RequestInfo | URL, init: RequestInit = {}) => { + const headers: Record = {}; + new Headers(init.headers).forEach((value, key) => { headers[key.toLowerCase()] = value; }); + if (init.signal?.aborted) throw Object.assign(new Error("aborted"), { name: "AbortError" }); + const answer = await server({ method: init.method ?? "GET", url: String(input), headers, body: init.body ?? undefined, signal: init.signal ?? undefined }); + if (answer === "network-error") throw new TypeError("fetch failed"); + // A 304 (like a 204) carries no body. + return new Response(answer.status === 304 || answer.status === 204 ? null : (answer.body as BodyInit | undefined) ?? null, { status: answer.status, headers: answer.headers }); + }) as typeof fetch; +} + +const json = (value: unknown, status = 200): ConformanceResponse => ({ status, headers: { "content-type": "application/json; charset=utf-8" }, body: JSON.stringify(value) }); +const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b); +function expect(condition: unknown, rule: string): asserts condition { + if (!condition) throw new Error(`Transport conformance: ${rule}`); +} +async function rejection(promise: Promise): Promise { + try { await promise; } catch (error) { return error; } + throw new Error("Transport conformance: the request resolved, and the rule says it must reject"); +} + +/** + * The checks. `make` is called once per check with that check's server and + * must answer a fresh Transport whose HTTP client calls it, built on + * CONFORMANCE_BASE_URL. + */ +export function transportConformance(make: (server: ConformanceServer) => Transport): ConformanceCheck[] { + /** A transport whose network answers `answer` to everything and records what it was asked. */ + const scripted = (answer: ConformanceResponse | ((request: ConformanceRequest) => ConformanceResponse)) => { + const seen: ConformanceRequest[] = []; + const transport = make(async (request) => { seen.push(request); return typeof answer === "function" ? answer(request) : answer; }); + return { transport, seen }; + }; + // A rejection a check did not expect is a broken rule too: say which, rather than surface the transport's own error bare. + const named = (checks: ConformanceCheck[]): ConformanceCheck[] => checks.map(({ name, run }) => ({ name, run: async () => { + try { await run(); } catch (error) { + if (error instanceof Error && error.message.startsWith("Transport conformance:")) throw error; + throw new Error(`Transport conformance: "${name}" — the transport rejected where the rule says it must resolve: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); + } + } })); + return named([ + { name: "a path is resolved inside the instance's base URL, a leading slash included, and query values are sent", run: async () => { + const { transport, seen } = scripted(json([])); + await transport.request({ method: "GET", path: "/rest-1.v1/Data/Story", query: { sel: "Name", page: "2,0", skipped: undefined, none: null } }); + const url = new URL(seen[0]!.url); + expect(url.origin + url.pathname === "https://agility.example.com/Instance/rest-1.v1/Data/Story", `the path must stay under the base path: got ${seen[0]!.url}`); + expect(url.searchParams.get("sel") === "Name" && url.searchParams.get("page") === "2,0", "query values must be sent"); + expect(!url.searchParams.has("skipped") && !url.searchParams.has("none"), "an undefined or null query value must be left out"); + expect(seen[0]!.method === "GET", "the method must be the one asked for"); + } }, + { name: "a body is sent in the shape it was given: a value as JSON, a string as text unless told otherwise, bytes as octet-stream, a Blob with its own type", run: async () => { + const { transport, seen } = scripted(json({})); + await transport.request({ method: "POST", path: "/api/asset", body: [{ from: "Story" }] }); + await transport.request({ method: "POST", path: "/api/asset", body: "from: Story" }); + await transport.request({ method: "POST", path: "/api/asset", body: "from: Story", contentType: "text/yaml" }); + await transport.request({ method: "POST", path: "/attachment.img/5", body: new Uint8Array([1, 2, 3]) }); + await transport.request({ method: "POST", path: "/attachment.img/5", body: new Blob(["hi"], { type: "text/csv" }) }); + const type = (i: number) => seen[i]!.headers["content-type"] ?? ""; + const sent = seen[0]!.body; + expect(type(0).startsWith("application/json") && same(typeof sent === "string" ? JSON.parse(sent) : sent, [{ from: "Story" }]), "a JSON value must be sent as JSON with content-type application/json"); + expect(type(1).startsWith("text/plain") && seen[1]!.body === "from: Story", "a string must be sent as it is, as text/plain"); + expect(type(2).startsWith("text/yaml"), "contentType must override the implied content type"); + expect(type(3).startsWith("application/octet-stream"), "bytes must be sent as application/octet-stream"); + expect(type(4).startsWith("text/csv"), "a Blob must keep its own type"); + } }, + { name: "a FormData body is handed over untouched, with no content type of the transport's own (the runtime writes the multipart boundary)", run: async () => { + if (typeof FormData === "undefined") return; + const { transport, seen } = scripted({ status: 200, headers: { "content-type": "text/html" }, body: "" }); + const form = new FormData(); + form.append("oidToken", "Story:1"); + await transport.request({ method: "POST", path: "/EmbeddedImage.mvc/Upload", body: form, responseType: "text" }); + expect(seen[0]!.body instanceof FormData, "a FormData must reach the HTTP client as a FormData"); + expect(!(seen[0]!.headers["content-type"] ?? "").startsWith("application/json"), "a FormData must not be labelled as JSON"); + } }, + { name: "the response is read as asked: bytes as a Uint8Array, text as a string, auto as JSON when the server says JSON and text otherwise", run: async () => { + const bytes = await scripted({ status: 200, headers: { "content-type": "image/png" }, body: new Uint8Array([1, 2, 3]) }).transport.request({ method: "GET", path: "/attachment.img/5", responseType: "bytes" }); + expect(bytes instanceof Uint8Array && same([...bytes], [1, 2, 3]), "responseType \"bytes\" must answer a Uint8Array (not an ArrayBuffer)"); + const text = await scripted(json({ a: 1 })).transport.request({ method: "GET", path: "/x", responseType: "text" }); + expect(text === "{\"a\":1}", "responseType \"text\" must answer the body as a string, unparsed"); + expect(same(await scripted(json({ a: 1 })).transport.request({ method: "GET", path: "/x" }), { a: 1 }), "with no responseType, a JSON response must be parsed"); + expect((await scripted({ status: 200, headers: { "content-type": "text/html" }, body: "

hi

" }).transport.request({ method: "GET", path: "/x" })) === "

hi

", "with no responseType, a non-JSON response must answer as text"); + } }, + { name: "onResponse is called with the status and case-insensitive headers before the body is answered; a missing header is null", run: async () => { + const { transport } = scripted({ status: 200, headers: { "content-type": "text/plain", ETag: "\"26.3.2.13.1\"" }, body: "ok" }); + const order: string[] = []; + let seenHeaders: (string | null)[] = [], status = 0; + const body = await transport.request({ method: "GET", path: "/meta.v1/Story", responseType: "text", onResponse: (r) => { order.push("onResponse"); status = r.status; seenHeaders = [r.headers.get("etag"), r.headers.get("ETag"), r.headers.get("x-missing")]; } }); + order.push("body"); + expect(body === "ok" && same(order, ["onResponse", "body"]), "onResponse must run once, before the request resolves"); + expect(status === 200, "onResponse must be given the status"); + expect(seenHeaders[0] === "\"26.3.2.13.1\"" && seenHeaders[1] === seenHeaders[0], "headers.get must find a header whatever its case"); + expect(seenHeaders[2] === null, "headers.get must answer null for a header that was not sent"); + } }, + { name: "a 304 on a request with acceptNotModified resolves undefined after onResponse has seen it; without the flag a 304 is an error like any other status outside 2xx", run: async () => { + const notModified: ConformanceResponse = { status: 304, headers: { etag: "\"t\"" } }; + let seen: number | null = null, tag: string | null = null; + const answer = await scripted(notModified).transport.request({ method: "GET", path: "/meta.v1/Story", headers: { "If-None-Match": "\"t\"" }, acceptNotModified: true, onResponse: (r) => { seen = r.status; tag = r.headers.get("etag"); } }); + expect(answer === undefined, "a 304 with acceptNotModified must resolve to undefined"); + expect(seen === 304 && tag === "\"t\"", "onResponse must be called with the 304 and its headers"); + const error = await rejection(scripted(notModified).transport.request({ method: "GET", path: "/meta.v1/Story" })); + expect(error instanceof ApiError && error.status === 304, "without acceptNotModified a 304 must reject with an ApiError carrying the status"); + } }, + { name: "a refused response rejects with the ApiError that apiErrorFromResponse makes: the status, the server's own words, the body as details", run: async () => { + const bodies: [number, unknown][] = [ + [400, { _type: "Error", error: "Invalid WHERE parameter", exceptions: [{ type: "FormatException", message: "Invalid QueryFilter2 token Nope=1" }] }], + [400, { Exceptions: ["The request body is not valid JSON."] }], + [401, "Unauthorized"], + [503, ""] + ]; + for (const [status, data] of bodies) { + const response: ConformanceResponse = typeof data === "string" ? { status, headers: { "content-type": "text/plain" }, body: data } : json(data, status); + const error = await rejection(scripted(response).transport.request({ method: "GET", path: "/x" })); + const expected = apiErrorFromResponse(status, data); + expect(error instanceof ApiError, `a ${status} must reject with an ApiError`); + expect(error.status === status && error.kind === expected.kind, `a ${status} must carry its status and the kind it implies (${expected.kind})`); + expect(error.message === expected.message, `a ${status} must be worded as apiErrorFromResponse words it ("${expected.message}"), got "${error.message}"`); + if (typeof data === "object") expect(same(error.details, data), "the parsed error body must be the error's details"); + } + } }, + { name: "a caller's abort rejects with code ABORTED and status 0, before sending when the signal is already aborted; a failed connection rejects as NETWORK_ERROR, kind transient", run: async () => { + const aborted = new AbortController(); + aborted.abort(); + const early = scripted(json([])); + const before = await rejection(early.transport.request({ method: "GET", path: "/x", signal: aborted.signal })); + expect(before instanceof ApiError && before.code === "ABORTED" && before.status === 0 && before.kind === "aborted", "a request whose signal is already aborted must reject with ApiError code ABORTED, status 0"); + expect(early.seen.length === 0, "a request whose signal is already aborted must not be sent"); + const controller = new AbortController(); + const during = await rejection(scripted(() => { controller.abort(); return "network-error"; }).transport.request({ method: "GET", path: "/x", signal: controller.signal })); + expect(during instanceof ApiError && during.code === "ABORTED", "an abort while the request is in flight must reject with ApiError code ABORTED"); + const lost = await rejection(scripted("network-error").transport.request({ method: "POST", path: "/api/asset", body: [] })); + expect(lost instanceof ApiError && lost.code === "NETWORK_ERROR" && lost.status === 0 && lost.kind === "transient", "a failed connection must reject with ApiError code NETWORK_ERROR, status 0, kind transient"); + } }, + { name: "responseType \"json\" insists: a body that is not JSON rejects with code BAD_JSON, and an empty one resolves undefined", run: async () => { + const error = await rejection(scripted({ status: 200, headers: { "content-type": "text/html" }, body: "Sign in" }).transport.request({ method: "GET", path: "/x", responseType: "json" })); + expect(error instanceof ApiError && error.code === "BAD_JSON" && error.kind === "protocol", "a non-JSON body under responseType \"json\" must reject with ApiError code BAD_JSON"); + expect((await scripted({ status: 200, headers: { "content-type": "application/json" }, body: "" }).transport.request({ method: "POST", path: "/x", responseType: "json" })) === undefined, "an empty body under responseType \"json\" must resolve to undefined"); + } } + ]); +} diff --git a/test/unit/transportConformance.test.ts b/test/unit/transportConformance.test.ts new file mode 100644 index 0000000..4a46a01 --- /dev/null +++ b/test/unit/transportConformance.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vitest"; +import { ApiError } from "../../src/core/errors"; +import { createFetchTransport } from "../../src/core/fetchTransport"; +import type { Transport } from "../../src/core/transport"; +import { CONFORMANCE_BASE_URL, fetchFrom, transportConformance } from "../../src/testing"; + +/** + * The conformance suite a consumer runs against its own Transport, run + * here against the SDK's: if the fetch transport stops doing what the + * suite says a Transport does, this fails before a consumer's suite does. + */ +describe("Transport conformance: the fetch transport", () => { + for (const check of transportConformance((server) => createFetchTransport({ baseUrl: CONFORMANCE_BASE_URL, retries: 0, fetchImpl: fetchFrom(server) }))) it(check.name, check.run); +}); + +describe("Transport conformance: the suite catches a transport that breaks a rule", () => { + const good = (server: Parameters[0]) => createFetchTransport({ baseUrl: CONFORMANCE_BASE_URL, retries: 0, fetchImpl: fetchFrom(server) }); + const failing = async (make: (server: Parameters[0]) => Transport): Promise => { + const failed: string[] = []; + for (const check of transportConformance(make)) await check.run().catch((e: Error) => failed.push(e.message)); + return failed; + }; + + it("one that rejects a 304 it was told to accept (an HTTP client's default), and one that throws its own error type", async () => { + // As an HTTP client that treats every status outside 2xx as an error does: the 304 never resolves. + const strict = (server: Parameters[0]): Transport => { const t = good(server); return { request: (o) => t.request({ ...o, acceptNotModified: false }) }; }; + const broken = await failing(strict); + expect(broken).toEqual([expect.stringMatching(/^Transport conformance: "a 304 on a request with acceptNotModified.*the transport rejected where the rule says it must resolve: HTTP 304$/)]); + const ownErrors = (server: Parameters[0]): Transport => { const t = good(server); return { request: (o) => t.request(o).catch((e: unknown) => { throw e instanceof ApiError && e.status >= 400 ? new Error(`HTTP ${e.status}`) : e; }) as never }; }; + expect((await failing(ownErrors)).some((m) => /must reject with an ApiError/.test(m))).toBe(true); + }); + + it("one that lets a leading slash escape the base path", async () => { + const escaping = (server: Parameters[0]): Transport => createFetchTransport({ baseUrl: "https://agility.example.com/", retries: 0, fetchImpl: fetchFrom(server) }); + expect(await failing(escaping)).toEqual([expect.stringMatching(/the path must stay under the base path: got https:\/\/agility\.example\.com\/rest-1\.v1/)]); + }); +}); From b0528575c2fa4b335d58cd57541d473fc9003539 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:36:06 +0000 Subject: [PATCH 08/17] alpha.8: the fake serves a metamodel and rest-1 list reads; meta.v1's document form under /wire - new FakeAgilityClient({ metamodel }) takes a meta.v1 document and serves meta.v1/ from it, so the fake's instance has those types: a response captured from a server and scripted with onRequest reads translated, for the fake and for a client built on fake.transport. Rows scripted in the model's shape still read as scripted, and the type loads stay out of `requests`. - onList(type, rows) scripts client.data.list in the model's shape; the fake answers rest-1's document so the client's own translation reads it back, paging and total included. - /wire meta: readMetamodelDocument and readAssetTypeDocument, the document form with the conditional read, for a caller whose code parses meta.v1's own spelling. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 12 ++++++ README.md | 2 +- src/index.ts | 2 +- src/testing/index.ts | 87 ++++++++++++++++++++++++++++++++++++--- src/wire/meta.ts | 16 +++++++ test/unit/etag.test.ts | 15 ++++++- test/unit/testing.test.ts | 40 ++++++++++++++++++ 7 files changed, 166 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dca8770..17247d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -159,6 +159,18 @@ Each entry has the line a consumer follows to migrate. SDK's own fetch transport runs it. A new duty of a Transport is from now on a new check here and a "Breaking" line. (a browser app consumer with an axios transport.) +- `meta.readMetamodelDocument({ ifNoneMatch })` and + `meta.readAssetTypeDocument(token, { ifNoneMatch })` in + `@versionone/agility-sdk/wire`: meta.v1's own document form with the + conditional read, for a caller whose code parses the document. + (`client.meta` answers the model's `Metamodel` and is unchanged.) +- **`FakeAgilityClient` at the transport's level too**: `new + FakeAgilityClient({ metamodel })` gives the fake's instance the asset + types of a meta.v1 document, so a response captured from a server and + scripted with `onRequest` reads translated, for the fake and for any + client built on `fake.transport`; and `onList(type, rows)` scripts + `client.data.list` in the model's shape. (a chat-bot consumer and a CLI + consumer, whose tests replay captured responses.) - **`client.resolve.refs(specs)`**: numbers and OID tokens mixed, each one read, in two requests at most; what names nothing is `missing`. - **`Outcome.unmatched`**: the indexes of updates and operations diff --git a/README.md b/README.md index d28cd1d..840f32e 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ expect(fake.sent[0]).toEqual([{ from: "Story:1", execute: "QuickClose" }]); - `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. +- `onList(type, rows)` answers `client.data.list` the same way. `onRequest(path, answer)` answers any other endpoint in its own shape; with `new FakeAgilityClient({ metamodel })` (a meta.v1 document) a response captured from a server reads translated, as it would live. An `Error` as an answer is thrown. - A custom `Transport` has its own suite: `transportConformance(make)` answers the SDK's expectations of a transport as named checks (`for (const c of transportConformance(make)) it(c.name, c.run)`), and the SDK's fetch transport runs the same ones. - 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. diff --git a/src/index.ts b/src/index.ts index efecabb..fb959bb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -25,7 +25,7 @@ export { normalizeQuery } from "./wire/rest1"; export type { LooseQuery, OperationResult, ReadParams, ReadResult, Template } from "./wire/rest1"; export type { Bytes, EmbeddedImage } from "./wire/attachment"; export type { Localizations, LocalizeOptions } from "./wire/loc2"; -export type { ConditionalOptions, Tagged } from "./wire/meta"; +export type { ConditionalOptions, MetamodelDocument, Tagged } from "./wire/meta"; export type { QueryRejection } from "./wire/queryV1"; export type { FieldsOf } from "./services/fields"; export { importantName } from "./services/fields"; diff --git a/src/testing/index.ts b/src/testing/index.ts index 4f4362f..dcf21ad 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -23,6 +23,9 @@ import type { RequestOptions, Transport } from "../core/transport"; import type { Asset, Oid } from "../types/asset"; import { isOidToken, momentless, typeOfOid } from "../types/oid"; import type { Command, CommandBody, QueryBody } from "../wire/assetApi"; +import type { MetamodelDocument } from "../wire/meta"; + +export type { MetamodelDocument } from "../wire/meta"; /** A scripted row: an OID and whatever the code under test selects, in the model's shape. */ export type FakeRow = Asset & { [attribute: string]: unknown }; @@ -51,7 +54,11 @@ const bodyOf = (command: Command): 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); +type ListMatch = string | ((type: string, params: Record) => boolean); + interface Script { + lists: { match: ListMatch; answer: FakeRows | Error | ((type: string, params: Record) => FakeRows) }[]; + metamodel: MetamodelDocument | null; queries: { match: QueryMatch; answer: QueryAnswer }[]; sends: SendAnswer[]; requests: { match: RequestMatch; answer: RequestAnswer }[]; @@ -119,6 +126,14 @@ function respond(script: Script, request: RequestOptions): unknown { const raw = [...script.requests].reverse().find(({ match }) => (typeof match === "string" ? request.path.startsWith(match) : match instanceof RegExp ? match.test(request.path) : match(request))); // A type nothing scripted is a type the fake's instance does not have, so rows are read as scripted. These // reads are the client's own schema loading, not something the code under test asked for: they are not recorded. + if (!raw && request.method === "GET" && request.path.startsWith("/meta.v1/") && script.metamodel) { + // The fake's instance has the metamodel's types: serve the document, part by part, as meta.v1 does. + const [type, attribute] = request.path.slice("/meta.v1/".length).split("/").map(decodeURIComponent); + const found = attribute ? script.metamodel.AssetTypes[type!]?.Attributes[`${type}.${attribute}`] : script.metamodel.AssetTypes[type!]; + if (!found) throw apiErrorFromResponse(404, { error: "Not Found", exceptions: [{ message: `FakeAgilityClient's metamodel has nothing at ${request.path}` }] }); + request.onResponse?.({ status: 200, headers: { get: () => null } }); + return found; + } if (!raw && request.method === "GET" && request.path.startsWith("/meta.v1/")) throw apiErrorFromResponse(404, { error: "Not Found", exceptions: [{ message: `FakeAgilityClient knows no asset type at ${request.path}` }] }); script.seen.requests.push(request); if (raw) { @@ -130,6 +145,22 @@ function respond(script: Script, request: RequestOptions): unknown { 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 === "GET" && request.path.startsWith("/rest-1.v1/Data/") && !request.path.slice("/rest-1.v1/Data/".length).includes("/")) { + const type = decodeURIComponent(request.path.slice("/rest-1.v1/Data/".length)); + const params = (request.query ?? {}) as Record; + const hit = [...script.lists].reverse().find(({ match }) => (typeof match === "function" ? match(type, params) : match === type)); + if (hit) { + if (hit.answer instanceof Error) throw hit.answer; + const answered = typeof hit.answer === "function" ? hit.answer(type, params) : hit.answer; + const [size, start] = (params.page ?? "").split(",").map(Number) as [number, number]; + // A list is the whole result and is paged here; a function answers one page itself. + const whole = Array.isArray(answered) && typeof hit.answer !== "function"; + const all = (Array.isArray(answered) ? answered : (answered as { rows: readonly FakeRow[] }).rows) as readonly FakeRow[]; + const rows = whole ? all.slice(start, start + size) : all; + const total = Array.isArray(answered) ? (whole ? all.length : undefined) : (answered as { total?: number | null }).total ?? undefined; + return { _type: "Assets", total: params.needTotal === "true" ? total : undefined, pageSize: size, pageStart: start, Assets: rows.map(toAssetDocument) }; + } + } 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[]; @@ -165,6 +196,35 @@ function respond(script: Script, request: RequestOptions): unknown { throw new UsageError(`FakeAgilityClient: no answer scripted for ${request.method} ${request.path}; script one with fake.onRequest("${request.path}", answer)`); } +export interface FakeOptions { + /** + * A metamodel as meta.v1 delivers it (the document a consumer captures + * from `GET /meta.v1`, or this repository's `metamodel.json`). With it + * the fake's instance has those asset types: it serves `meta.v1/` + * from the document, so answers go through the real translation — a + * response captured from a server, scripted with `onRequest`, reads as + * it would live ("5" becomes 5, a sub-selected single relation one Ref) + * — for the fake and for any client built on `fake.transport`. Rows + * scripted in the model's shape still read as scripted. Without it, the + * instance has no types and nothing is translated. + */ + metamodel?: MetamodelDocument; +} + +/** A model row as rest-1 would send it: what `onList` answers with, so the client's own translation reads it back. */ +function toAssetDocument(row: FakeRow): Record { + const isRef = (v: unknown): v is { _oid: string } => !!v && typeof v === "object" && typeof (v as { _oid?: unknown })._oid === "string"; + const ref = (r: { _oid: string }) => ({ _type: "Asset", href: "", idref: r._oid }); + const Attributes: Record = {}; + for (const [name, value] of Object.entries(row)) { + if (name === "_oid") continue; + if (isRef(value)) Attributes[name] = { _type: "Relation", name, value: ref(value) }; + else if (Array.isArray(value) && value.length && value.every(isRef)) Attributes[name] = { _type: "Relation", name, value: value.map(ref) }; + else Attributes[name] = { _type: "Attribute", name, value }; + } + return { _type: "Asset", href: "", id: row._oid, Attributes }; +} + /** * An AgilityApiClient that sends nothing: reads answer the rows a test * scripted, writes are recorded and answer OIDs, and everything asked is @@ -202,9 +262,12 @@ function respond(script: Script, request: RequestOptions): unknown { * - `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". + * - `onList(type, rows)` answers `client.data.list` the same way: rows in + * the model's shape, a list paged by the fake. * - `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 + * endpoint's own shape (attachment bytes, a captured response), and wins + * over everything above. With `new FakeAgilityClient({ metamodel })` a + * captured query response reads as it would live: translated. 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. @@ -221,8 +284,8 @@ export class FakeAgilityClient extends AgilityApiClient { readonly sent: Command[][]; private readonly script: Script; - constructor(config: Partial = {}) { - const script: Script = { queries: [], sends: [], requests: [], labels: {}, seen: { requests: [], asked: [], sent: [] }, nextId: 1000 }; + constructor(config: Partial & FakeOptions = {}) { + const script: Script = { lists: [], metamodel: config.metamodel ?? null, 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 => { @@ -231,7 +294,8 @@ export class FakeAgilityClient extends AgilityApiClient { } }; // The fake's instance has no asset type (every meta.v1 read answers 404), so rows scripted in the model's shape pass through as written. - super({ baseUrl: "https://agility.example.com/Fake", ...config }, { transport }); + const { metamodel: _metamodel, ...clientConfig } = config; + super({ baseUrl: "https://agility.example.com/Fake", ...clientConfig }, { transport }); this.script = script; this.requests = script.seen.requests; this.asked = script.seen.asked; @@ -254,6 +318,19 @@ export class FakeAgilityClient extends AgilityApiClient { return this; } + /** + * Script `client.data.list` (rest-1's list read: text search, deleted + * assets) for an asset type or a predicate over the type and the query + * string rest-1 is sent (`find`, `where`, `sel`, `deleted`). Rows are in + * the model's shape, as for `onQuery`: a list is the whole result (the + * fake pages it and reports its length as the total when asked), a + * function answers one page. No `find` or filter is evaluated. + */ + onList(match: ListMatch, answer: FakeRows | Error | ((type: string, params: Record) => FakeRows)): this { + this.script.lists.push({ match, 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); diff --git a/src/wire/meta.ts b/src/wire/meta.ts index 50bbd6d..3e82d04 100644 --- a/src/wire/meta.ts +++ b/src/wire/meta.ts @@ -157,6 +157,22 @@ export async function readMetamodel(transport: Transport, options: ConditionalOp return read && { value: toMetamodel(read.value), etag: read.etag }; } +/** + * The metamodel as meta.v1 spells it — references as `{ nameref, href }` + * and `{ tokenref, href }`, operations keyed by token — with its tag; null + * when `ifNoneMatch` still matches (nothing was downloaded). For a caller + * whose own code reads the document form; `readMetamodel` answers the + * model's. + */ +export async function readMetamodelDocument(transport: Transport, options: ConditionalOptions = {}): Promise | null> { + return conditional(transport, "/meta.v1", options); +} + +/** One type as meta.v1 spells it, with the schema's tag; null when `ifNoneMatch` still matches. */ +export async function readAssetTypeDocument(transport: Transport, token: AssetTypeToken, options: ConditionalOptions = {}): Promise | null> { + return conditional(transport, `/meta.v1/${encodeURIComponent(token)}`, options); +} + export async function getAssetType(transport: Transport, token: AssetTypeToken): Promise { return toAssetType(await transport.request({ method: "GET", path: `/meta.v1/${encodeURIComponent(token)}`, responseType: "json" })); } diff --git a/test/unit/etag.test.ts b/test/unit/etag.test.ts index 54e9be9..9bf5592 100644 --- a/test/unit/etag.test.ts +++ b/test/unit/etag.test.ts @@ -5,7 +5,7 @@ import { AgilityApiClient } from "../../src/client"; import { createFetchTransport } from "../../src/core/fetchTransport"; import type { RequestOptions, Transport } from "../../src/core/transport"; import { Schema, TypeCache } from "../../src/services/schema"; -import { etag, readAssetType, readMetamodel, type MetamodelDocument } from "../../src/wire/meta"; +import { etag, readAssetType, readAssetTypeDocument, readMetamodel, readMetamodelDocument, type MetamodelDocument } from "../../src/wire/meta"; /** * meta.v1's one strong ETag for the whole schema, and what the SDK does @@ -43,6 +43,19 @@ describe("conditional meta reads", () => { expect((await readMetamodel(transport, { ifNoneMatch: TAG }))?.etag).toBe(NEXT); }); + it("readMetamodelDocument and readAssetTypeDocument answer meta.v1's own spelling (references as { nameref }), conditionally, for a caller whose code reads the document", async () => { + const { state, transport } = metaServer(); + const first = await readMetamodelDocument(transport); + expect(first?.etag).toBe(TAG); + expect(first!.value.AssetTypes.Story!.Base).toEqual({ nameref: "PrimaryWorkitem", href: "/meta.v1/PrimaryWorkitem" }); + expect((await readMetamodel(transport))!.value.AssetTypes.Story!.Base).toBe("PrimaryWorkitem"); // the model's spelling, for contrast + expect(await readMetamodelDocument(transport, { ifNoneMatch: TAG })).toBeNull(); + expect(state.bodies).toBe(2); + const type = await readAssetTypeDocument(transport, "Story"); + expect(type?.value.Attributes["Story.Scope"]!.RelatedAsset).toMatchObject({ nameref: "Scope" }); + expect(await readAssetTypeDocument(transport, "Story", { ifNoneMatch: TAG })).toBeNull(); + }); + it("readAssetType and etag do the same with one type and with the smallest resource", async () => { const { state, transport } = metaServer(); expect((await readAssetType(transport, "Story"))?.value.Token).toBe("Story"); diff --git a/test/unit/testing.test.ts b/test/unit/testing.test.ts index 4deb9a9..c7fb1a7 100644 --- a/test/unit/testing.test.ts +++ b/test/unit/testing.test.ts @@ -1,8 +1,11 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; 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"; +import type { MetamodelDocument } from "../../src/wire/meta"; /** * The consumer-facing fake: a real client over a transport that answers @@ -134,6 +137,43 @@ describe("FakeAgilityClient", () => { expect(fake.requests.map((r) => r.path)).toEqual(["/query.v1"]); // the type load is the client's plumbing, not the test's subject }); + it("onList answers client.data.list from rows in the model's shape: Refs, dotted paths, paging, the total and `more`, and the rows rule", async () => { + const found = [ + { _oid: "Story:1", Name: "Logon", Number: "S-01001", AssetState: "Active", Owners: [{ _oid: "Member:20" }], "Owners.Name": ["Dana"], Status: null }, + { _oid: "Defect:9", Name: "Crash on logon", Number: "D-00009", AssetState: "Closed", Owners: [], Status: { _oid: "StoryStatus:5" } }, + { _oid: "Story:3", Name: "Logon help", Number: "S-01003", AssetState: "Active", Owners: [], Status: null } + ]; + const fake = new FakeAgilityClient().onList("BaseAsset", found); + const page = await fake.data.list("BaseAsset", { find: "logon", findin: ["Name"], select: ["Name", "Number", "AssetState", "Owners", "Owners.Name", "Status"], page: { size: 2, start: 0 }, needTotal: true }); + // As scripted, read back through the client's own rest-1 translation: so, as live, a selected dotted path is also on its Refs. + expect(page.rows).toEqual([{ ...found[0], Owners: [{ _oid: "Member:20", Name: "Dana" }] }, found[1]]); + expect(page).toMatchObject({ total: 3, more: true }); + expect((await fake.data.list("BaseAsset", { page: { size: 2, start: 2 }, needTotal: true })).rows).toEqual([found[2]]); + expect(fake.requests[0]).toMatchObject({ method: "GET", path: "/rest-1.v1/Data/BaseAsset", query: { find: "logon", findin: "Name", page: "2,0" } }); + // A function sees the type and rest-1's own query string, and answers one page. + fake.onList((type, q) => type === "Story" && q.deleted === "true", () => ({ rows: [{ _oid: "Story:7", Name: "gone" }], total: 12 })); + expect(await fake.data.list("Story", { deleted: true, page: { size: 1, start: 0 }, needTotal: true })).toMatchObject({ rows: [{ _oid: "Story:7", Name: "gone" }], total: 12, more: true }); + await expect(fake.data.list("Epic", { page: { size: 1, start: 0 } })).rejects.toThrow(/no answer scripted for GET \/rest-1\.v1\/Data\/Epic/); + }); + + it("with a metamodel the fake's instance has those types: a response captured from a server reads translated, for the fake and for a client built on its transport", async () => { + const metamodel = JSON.parse(readFileSync(join(__dirname, "..", "..", "metamodel.json"), "utf8")) as MetamodelDocument; + // As query.v1 sent it (every scalar a string, a sub-selected single relation a one-element list). + const captured = [[{ _oid: "Story:1055:900", Name: "Sample: Logon", Estimate: "2", IsClosed: "True", Status: [{ _oid: "StoryStatus:137", Name: "Accepted" }], Super: { _oid: "NULL" } }]]; + const fake = new FakeAgilityClient({ metamodel }).onRequest("/query.v1", captured); + const q = { from: "Story", select: ["Name", "Estimate", "IsClosed", { from: "Status", select: ["Name"] }, "Super"], page: { size: 1, start: 0 } }; + const expected = [{ _oid: "Story:1055", Name: "Sample: Logon", Estimate: 2, IsClosed: true, Status: { _oid: "StoryStatus:137", Name: "Accepted" }, Super: null }]; + expect(await fake.query(q)).toEqual(expected); + const wrapped = new AgilityApiClient({ baseUrl: "https://x" }, { transport: fake.transport }); + expect(await wrapped.query(q)).toEqual(expected); + // Rows scripted in the model's shape still read as scripted, and the type loads are not in `requests`. + const scripted = new FakeAgilityClient({ metamodel }).onQuery("Story", [{ _oid: "Story:1", Name: "n", Estimate: 3, IsClosed: false, Status: null }]); + expect(await scripted.query({ from: "Story", select: ["Name", "Estimate", "IsClosed", "Status"], page: { size: 1, start: 0 } })).toEqual([{ _oid: "Story:1", Name: "n", Estimate: 3, IsClosed: false, Status: null }]); + expect(scripted.requests.map((r) => r.path)).toEqual(["/query.v1"]); + expect((await scripted.meta.assetType("Story")).Token).toBe("Story"); + await expect(scripted.meta.assetType("NoSuchType")).rejects.toMatchObject({ kind: "notFound" }); + }); + it("an aborted signal ends a read as ABORTED, like the fetch transport", async () => { const controller = new AbortController(); controller.abort(); From cb85a428cc49ad201d0b0d0f6f6a0aebea951142 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:39:14 +0000 Subject: [PATCH 09/17] alpha.8: guarded sends and batch.run on the fake FakeAgilityClient keeps a moment per asset, so sendGuarded and batch.run work on it for assets addressed by OID that a row was scripted for: a guarded command applies only at the asset's moment, a batch's snapshot, stamps and read-backs are answered from the scripted rows, and a preview projects OID-addressed writes per asset. fake.touch(oid) is someone else changing the asset (a conflict for a write stamped earlier, drift for a receipt's reverse); fake.remove(oid) is it being deleted. A write scoped by a query cannot be previewed by a fake that evaluates no filter, and the fake says so. onSend still replaces the simulation with its own answer. Also: the alpha.4 notes now list urls.asset's UsageError as the breaking change it was. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 13 ++++- README.md | 1 + src/testing/index.ts | 99 ++++++++++++++++++++++++++++++++++----- test/unit/testing.test.ts | 37 +++++++++++++++ 4 files changed, 137 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 17247d0..ee8dfec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -169,8 +169,13 @@ Each entry has the line a consumer follows to migrate. types of a meta.v1 document, so a response captured from a server and scripted with `onRequest` reads translated, for the fake and for any client built on `fake.transport`; and `onList(type, rows)` scripts - `client.data.list` in the model's shape. (a chat-bot consumer and a CLI - consumer, whose tests replay captured responses.) + `client.data.list` in the model's shape. `sendGuarded` and `batch.run` + work on the fake for assets addressed by OID that a row was scripted + for: it keeps a moment per asset, `fake.touch(oid)` is someone else + changing it (a conflict for a write stamped earlier, drift for a + receipt's reverse) and `fake.remove(oid)` is it being deleted. (a + chat-bot consumer and a CLI consumer, whose tests replay captured + responses and fake a batch by hand.) - **`client.resolve.refs(specs)`**: numbers and OID tokens mixed, each one read, in two requests at most; what names nothing is `missing`. - **`Outcome.unmatched`**: the indexes of updates and operations @@ -392,6 +397,10 @@ entry says what a consumer changes, if anything. fields with whether they are enforced at close; `visible(types, scopes)` and `visibleByAsset(oid)` are the endpoints alone. New wire module `fields`. +- **`client.urls.asset` throws a `UsageError` for anything that is + neither an OID token nor an asset Number** (it built a URL from any + string before). This was a breaking change and was not listed as one + when alpha.4 shipped. Migration: validate, or catch the `UsageError`. - **`client.urls.asset` takes an asset Number** as well as an OID (`assetdetail.v1?Number=S-01001`): the readable form a CLI prints and a chat message shows (a CLI consumer, a chat-bot consumer). diff --git a/README.md b/README.md index 840f32e..fa65094 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,7 @@ expect(fake.sent[0]).toEqual([{ from: "Story:1", execute: "QuickClose" }]); - `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. +- `sendGuarded` and `batch.run` work on assets addressed by OID that you scripted a row for: `fake.touch(oid)` is someone else changing the asset (the next write stamped earlier is a conflict), `fake.remove(oid)` is it being deleted. - `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. - `onList(type, rows)` answers `client.data.list` the same way. `onRequest(path, answer)` answers any other endpoint in its own shape; with `new FakeAgilityClient({ metamodel })` (a meta.v1 document) a response captured from a server reads translated, as it would live. An `Error` as an answer is thrown. - A custom `Transport` has its own suite: `transportConformance(make)` answers the SDK's expectations of a transport as named checks (`for (const c of transportConformance(make)) it(c.name, c.run)`), and the SDK's fetch transport runs the same ones. diff --git a/src/testing/index.ts b/src/testing/index.ts index dcf21ad..4e38b6b 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -65,6 +65,42 @@ interface Script { labels: Record; seen: { requests: RequestOptions[]; asked: QueryBody[]; sent: Command[][] }; nextId: number; + /** The fake's versions: each asset's moment (1 until something writes it), and the assets that are gone. */ + moments: Map; + gone: Set; + /** Assets the fake itself created or wrote: they exist without a scripted row. */ + known: Set; +} + +const momentOf = (script: Script, oid: Oid): number => script.moments.get(oid) ?? 1; +const bump = (script: Script, oid: Oid): void => { script.moments.set(oid, momentOf(script, oid) + 1); script.known.add(oid); }; +/** A readable time that moves with the moment, for `ChangeDate`. */ +const changedAt = (moment: number): string => `2026-01-01T00:00:${String(moment % 60).padStart(2, "0")}.${String(moment).padStart(3, "0")}`; +/** Does the fake's instance have this asset: a row was scripted for it, or the fake created or wrote it, and nobody removed it. */ +const exists = (script: Script, oid: Oid): boolean => !script.gone.has(oid) && (script.known.has(oid) || scriptedRows(script).some((row) => momentless(row._oid) === oid)); + +/** The SDK's own lookup of assets by OID (stamps, a batch's snapshot, names, states): `filter: ["ID=$oids"]`. */ +const isOidLookup = (q: QueryBody): boolean => q.filter?.length === 1 && q.filter[0] === "ID=$oids" && Array.isArray(q.with?.$oids); +/** A command the guard wrote: one asset at one moment, while that version is current. */ +const guardedOn = (body: CommandBody): { oid: Oid; moment: string } | null => { + const b = body as { where?: Record; filter?: string[]; with?: Record }; + return b.where?.ID === "$oid" && b.where?.Moment === "$moment" && b.filter?.includes("RetireDateUTC=''") ? { oid: momentless(String(b.with?.$oid)), moment: String(b.with?.$moment) } : null; +}; + +/** The rows of an OID lookup: each asked asset that exists, with what was selected of its scripted row, its Moment and its ChangeDate. */ +function lookupByOid(script: Script, q: QueryBody): Asset[] { + const rows = scriptedRows(script); + return (q.with!.$oids as string[]).map(momentless).filter((oid) => exists(script, oid)).map((oid) => { + const scripted = rows.find((row) => momentless(row._oid) === oid) ?? { _oid: oid }; + const out: Record = { _oid: oid }; + for (const entry of q.select ?? []) { + const key = typeof entry === "string" ? entry : entry.from; + if (key === "Moment") out.Moment = String(momentOf(script, oid)); + else if (key === "ChangeDate") out.ChangeDate = changedAt(momentOf(script, oid)); + else if (scripted[key] !== undefined) out[key] = scripted[key]; + } + return out as unknown as Asset; + }); } /** The scripted rows for one query, and the total a paged read would report. */ @@ -84,6 +120,8 @@ function answerQuery(script: Script, q: QueryBody, created?: { type: string; oid script.seen.asked.push(q); const type = created?.type ?? typeOfFrom(q.from); const hit = hitFor(script, q, type); + // A lookup by OID is answered from what the fake knows of each asset, unless a function was scripted for it. + if (!created && isOidLookup(q) && typeof hit?.answer !== "function" && !(hit?.answer instanceof Error)) { const rows = lookupByOid(script, q); return { rows, total: rows.length }; } 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") { @@ -104,7 +142,13 @@ function answerQuery(script: Script, q: QueryBody, created?: { type: string; oid } 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 }; + // A row that was not scripted with a Moment or ChangeDate gets the fake's own when the query selects them: what a guard will compare. + const wants = (key: string) => (q.select ?? []).includes(key); + const versioned = (row: FakeRow): FakeRow => { + const moment = momentOf(script, momentless(row._oid)); + return { ...row, ...(wants("Moment") && row.Moment === undefined ? { Moment: String(moment) } : {}), ...(wants("ChangeDate") && row.ChangeDate === undefined ? { ChangeDate: changedAt(moment) } : {}) }; + }; + return { rows: all.slice(page.start, page.start + page.size).filter((row) => !script.gone.has(momentless(row._oid))).map(versioned), 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). */ @@ -115,9 +159,12 @@ function answerSend(script: Script, commands: Command[], writes: { body: Command 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)); + const guarded = guardedOn(body); + // A guarded command applies only to an asset that exists, at the moment it was guarded on; anything else matches nothing. + const target = guarded ? (exists(script, guarded.oid) && String(momentOf(script, guarded.oid)) === guarded.moment ? guarded.oid : null) : "from" in body && isOidToken(body.from) ? momentless(body.from) : null; + if ("AssetType" in body) { const oid = `${String(body.AssetType)}:${script.nextId++}`; out.created.push(oid); script.known.add(oid); } + else if (target && "update" in body) { out.modified.push(target); bump(script, target); } + else if (target && "execute" in body) { out.operated.push(target); bump(script, target); } } return out; } @@ -164,8 +211,15 @@ function respond(script: Script, request: RequestOptions): unknown { 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; + // A preview answers the projection: a write addressed to one asset becomes a per-asset command; creates, + // queries and aliased writes are echoed, as the server echoes them. + if (request.query?.previewOnly) return commands.map((c, i) => { + const body = bodyOf(c) as Record; + const aliased = body !== (c as unknown); + if (aliased || !("update" in body || "execute" in body)) return c; + if (typeof body.from !== "string" || !isOidToken(body.from)) throw new UsageError(`FakeAgilityClient cannot preview command ${i}: it is scoped by a query (from ${String(body.from)}), and the fake evaluates no filter. Address the assets by OID, or script the preview with fake.onRequest((r) => r.query?.previewOnly === "true", projection)`); + return { [`@fake-${i}`]: { oid: momentless(body.from), ...("update" in body ? { update: body.update } : { execute: body.execute }) } } as unknown as Command; + }); 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: [] }; @@ -262,15 +316,22 @@ function toAssetDocument(row: FakeRow): Record { * - `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". + * - `sendGuarded` and `batch.run` work on assets addressed by OID that a + * row was scripted for: the fake keeps a moment per asset, applies a + * guarded command only at that moment, and answers a batch's snapshot, + * stamps and read-backs from the scripted rows. `fake.touch(oid)` is + * someone else changing the asset (the next guarded write stamped + * earlier is a conflict; a receipt's reverse finds it drifted); + * `fake.remove(oid)` is it being deleted. `onSend` replaces this + * simulation with its own answer. A write scoped by a query cannot be + * previewed by the fake (it evaluates no filter): script that preview + * with `onRequest`. * - `onList(type, rows)` answers `client.data.list` the same way: rows in * the model's shape, a list paged by the fake. * - `onRequest(match, answer)` answers any other request by path, in the * endpoint's own shape (attachment bytes, a captured response), and wins * over everything above. With `new FakeAgilityClient({ metamodel })` a - * captured query response reads as it would live: translated. 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. + * captured query response reads as it would live: translated. * - An `Error` as an answer is thrown: `new ApiError("Unauthorized", 401)`, * or `apiErrorFromResponse(status, body)` for a refusal as the fetch * transport words it. @@ -285,7 +346,7 @@ export class FakeAgilityClient extends AgilityApiClient { private readonly script: Script; constructor(config: Partial & FakeOptions = {}) { - const script: Script = { lists: [], metamodel: config.metamodel ?? null, queries: [], sends: [], requests: [], labels: {}, seen: { requests: [], asked: [], sent: [] }, nextId: 1000 }; + const script: Script = { lists: [], metamodel: config.metamodel ?? null, queries: [], sends: [], requests: [], labels: {}, seen: { requests: [], asked: [], sent: [] }, nextId: 1000, moments: new Map(), gone: new Set(), known: new Set() }; 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 => { @@ -337,6 +398,22 @@ export class FakeAgilityClient extends AgilityApiClient { return this; } + /** + * Someone else changed this asset: its moment moves on, so a guarded + * write stamped before now is a conflict, and a receipt's reverse finds + * it drifted. + */ + touch(oid: Oid): this { + bump(this.script, momentless(oid)); + return this; + } + + /** This asset is gone: reads by OID no longer find it, and a write to it matches nothing. */ + remove(oid: Oid): this { + this.script.gone.add(momentless(oid)); + 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 }); diff --git a/test/unit/testing.test.ts b/test/unit/testing.test.ts index c7fb1a7..4b0de19 100644 --- a/test/unit/testing.test.ts +++ b/test/unit/testing.test.ts @@ -4,6 +4,7 @@ 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 { ConflictError } from "../../src/services/guard"; import { CommandFailureError } from "../../src/wire/assetApi"; import type { MetamodelDocument } from "../../src/wire/meta"; @@ -174,6 +175,42 @@ describe("FakeAgilityClient", () => { await expect(scripted.meta.assetType("NoSuchType")).rejects.toMatchObject({ kind: "notFound" }); }); + it("sendGuarded on the fake: applies at the asset's moment, conflicts after someone else touched it or when it is gone, and honours a moment the caller holds", async () => { + const fake = new FakeAgilityClient().onQuery("Story", [{ _oid: "Story:1", Name: "One", Estimate: 3 }, { _oid: "Story:2", Name: "Two", Estimate: 5 }]); + const first = await fake.sendGuarded([{ from: "Story:1", update: { Estimate: 8 } }, { from: "Story:2", execute: "QuickClose" }]); + expect(first).toMatchObject({ modified: ["Story:1"], operated: ["Story:2"], conflicts: [], touched: ["Story:1", "Story:2"], details: { stamps: { "Story:1": "1", "Story:2": "1" } } }); + // What the person saw, then someone else's change, then their click. + const seen = (await fake.get<{ _oid: string; Moment: string }>("Story:1", ["Moment"]))!.Moment; + fake.touch("Story:1"); + expect(await fake.sendGuarded([{ from: "Story:1", update: { Estimate: 9 } }], { moments: { "Story:1": seen } })).toMatchObject({ modified: [], conflicts: ["Story:1"] }); + await expect(fake.sendGuarded([{ from: "Story:1", update: { Estimate: 9 } }], { moments: { "Story:1": seen }, throwOnFailure: true })).rejects.toBeInstanceOf(ConflictError); + // Read now, it applies; an asset that is gone, or that nothing was scripted for, is a conflict. + expect(await fake.sendGuarded([{ from: "Story:1", update: { Estimate: 9 } }])).toMatchObject({ modified: ["Story:1"], conflicts: [] }); + fake.remove("Story:2"); + expect(await fake.sendGuarded([{ from: "Story:2", execute: "Reactivate" }, { from: "Story:404", update: { Name: "x" } }])).toMatchObject({ operated: [], modified: [], conflicts: ["Story:2", "Story:404"] }); + // A write scoped by a query cannot be previewed by a fake that evaluates no filter, and says so. + await expect(fake.sendGuarded([{ from: "Story", filter: ["Estimate>'3'"], update: { Estimate: 1 } }])).rejects.toThrow(/cannot preview command 0.*scoped by a query/); + }); + + it("batch.run on the fake: a receipt with the scripted before values, Moment stamps and a reverse; reversible finds an asset drifted after someone touched it", async () => { + const fake = new FakeAgilityClient().onQuery("Story", [{ _oid: "Story:1", Name: "One", Number: "S-1", Estimate: 3 }, { _oid: "Story:2", Name: "Two", Number: "S-2", Estimate: 5 }]); + const receipt = await fake.batch.run([{ from: "Story:1", update: { Estimate: 8 } }, { from: "Story:2", update: { Estimate: 8 } }, { "@t": { AssetType: "Task", Name: "new", Parent: "Story:1" } }], { guard: true }); + expect(receipt).toMatchObject({ receipt: 2, sent: true, guarded: true, stopped: null, conflicts: [], failed: [], stamps: { "Story:1": "1", "Story:2": "1" }, after: { "Story:1": "2", "Story:2": "2", "Task:1000": "1" } }); + expect(receipt.before["Story:1"]).toMatchObject({ Estimate: 3, Moment: "1" }); + expect(receipt.created).toMatchObject([{ alias: "@t", type: "Task", oid: "Task:1000" }]); + expect(receipt.reverse.commands).toEqual([{ from: "Story:1", update: { Estimate: 3 } }, { from: "Story:2", update: { Estimate: 3 + 2 } }, { from: "Task:1000", execute: "Delete" }]); + expect((await fake.batch.reversible(receipt)).drifted).toEqual([]); + fake.touch("Story:2"); + const undo = await fake.batch.reversible(receipt); + expect(undo.drifted).toMatchObject([{ oid: "Story:2", was: "2", now: "3" }]); + expect(undo.commands).toEqual([{ from: "Story:1", update: { Estimate: 3 } }, { from: "Task:1000", execute: "Delete" }]); + // A conflict at send time is on the receipt, and a dry run sends nothing. + fake.onQuery("Epic", [{ _oid: "Epic:9", Name: "Nine" }]); + const racing = await fake.batch.run([{ from: "Epic:9", update: { Name: "x" } }], { guard: true, confirm: () => { fake.touch("Epic:9"); return true; } }); + expect(racing).toMatchObject({ sent: true, conflicts: ["Epic:9"], touched: [] }); + expect(await fake.batch.run([{ from: "Epic:9", update: { Name: "x" } }], { guard: true, dryRun: true })).toMatchObject({ sent: false, stopped: "dryRun" }); + }); + it("an aborted signal ends a read as ABORTED, like the fetch transport", async () => { const controller = new AbortController(); controller.abort(); From 94b50df9831343dc76ba29db316835f6d0a3ff29 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:44:59 +0000 Subject: [PATCH 10/17] alpha.8: what three consumers' migration trials found - A receipt's assets are rows: `created` and `touched` carry _oid, AssetType, Number and Name (created also its alias), and `names[oid]` Number and Name. The receipt format is new in this release, so it ships with the one convention the release is about. - Outcome.unmatched is filled on the receipt of an unguarded batch.run, where it matters most, and for an aliased command addressed by OID. Live-tested for both. - resolve.refs finds an asset once when its number and its OID both name it. - assetStateKind claims only what a server confirms: Active is open, Closed is closed, code 200 is a template, Deleted is deleted (a live test walks a story through three of them); Future, Dead and a split story are "other". It had called Dead deleted, which the server contradicts. - A selected key is typed as its value or null, not undefined: a row has the keys that were selected, on all three read paths. - ReceiptVersionError describes the receipt (its format and what that format recorded), not a version of this package. - The fake treats a removed asset as gone for a plain write too. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 20 +++++++++++++++----- README.md | 2 ++ src/index.ts | 2 +- src/services/batch.ts | 32 ++++++++++++++++++++------------ src/services/resolve.ts | 7 +++++-- src/testing/index.ts | 5 +++-- src/types/asset.ts | 19 ++++++++++++------- src/types/query.ts | 6 ++++-- src/wire/assetApi.ts | 12 +++++++----- test/integration/batch.test.ts | 16 ++++++++-------- test/integration/client.test.ts | 26 ++++++++++++++++++++++++++ test/integration/resolve.test.ts | 7 +++---- test/unit/batch.test.ts | 17 +++++++++-------- test/unit/client.test.ts | 21 ++++++++++++++------- test/unit/testing.test.ts | 5 ++++- test/unit/typedQuery.test.ts | 22 +++++++++++----------- 16 files changed, 144 insertions(+), 75 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee8dfec..1fd0473 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -78,7 +78,11 @@ Each entry has the line a consumer follows to migrate. defaulted to true). Migration: `client.batch.run(commands)` → `client.batch.run(commands, { guard: true })`. - **Receipts are `receipt: 2`**: `skipped` → `conflicts`; new `stamps`, - `changedAt` and `stopped`. **A stored `receipt: 1` cannot be checked + `changedAt` and `stopped`; and the assets a receipt names are rows, + like every other asset the SDK answers: in `created` and `touched`, + `oid` → `_oid`, `type` → `AssetType`, `number` → `Number`, `name` → + `Name` (`touched` gains `AssetType`); in `names[oid]`, `number` → + `Number`, `name` → `Name`. **A stored `receipt: 1` cannot be checked for drift**: `batch.reversible` throws a `ReceiptVersionError` (`kind: "usage"`, code `RECEIPT_VERSION`) for it. Migration for a holder of old receipts: reverse one with `{ force: true }`, which sends its reverse @@ -126,7 +130,9 @@ Each entry has the line a consumer follows to migrate. as `details`. Migration: a formatter that special-cased rest-1 can print `message` for both. - **Row types**: a sub-select is typed as rows of the related type with - what it selected (it was typed as bare Refs, which was wrong), and a + what it selected (it was typed as bare Refs, which was wrong); a + selected key is its value or null and never `undefined` (a row has the + keys that were selected); and a single relation is always `| null` on a row, also where the metamodel calls it required (the asset it pointed at may be gone). Migration: a cast that worked around the old sub-select type can go; code that read @@ -183,9 +189,13 @@ Each entry has the line a consumer follows to migrate. because the asset is gone. The server answers such a command with success; a caller that checked `operated.length === 0` by hand reads this instead. (A command that applied without changing a value, and - one the server refused, are not in it.) -- `assetStateKind(value)`: an AssetState name or code as `"open"`, - `"closed"`, `"template"`, `"deleted"` or `"other"`. + one the server refused, are not in it.) It is filled by `client.send` + and on the receipt of an unguarded `batch.run`, for aliased commands + by OID as for bare ones. +- `assetStateKind(value)`: an AssetState name or code as `"open"` + (Active), `"closed"` (Closed), `"template"` (code 200) or `"deleted"` + (Deleted), each checked against a server, and `"other"` for every + other state: it does not guess at Future, Dead or a split story. - The fetch transport calls the global `fetch` as it is at each request (it captured it when the transport was made), so a stub installed later is used without passing `fetchImpl`. diff --git a/README.md b/README.md index fa65094..41836d8 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,8 @@ npm test Every row follows one rule, whichever call read it: **a relation you select is a Ref (`{ _oid }`); a path you select by name is at `row[path]` (`row["Status.Name"]`); nothing arrives that you did not select.** Select both `Owners` and `Owners.Name` and you get the Refs and, beside them, a parallel array at `"Owners.Name"`. To get attributes on the related rows themselves, use a sub-select: `{ from: "Owners", select: ["Name"] }` gives `row.Owners[i].Name`. (rest-1 also puts the display attributes it sends unasked on the Refs of a relation you selected.) +Rows are typed from what you select, against the product's metamodel: a selected key is its value or `null`, never `undefined`. For an attribute your instance has and the generated model does not (a custom field's relation, a product module's attribute), name your own row type at the call: `client.query(q)` needs only `_oid` on `MyRow`. + ### Reference Changes between alphas are in `CHANGELOG.md`, each with its migration line. diff --git a/src/index.ts b/src/index.ts index fb959bb..6aba328 100644 --- a/src/index.ts +++ b/src/index.ts @@ -45,4 +45,4 @@ export type { Resolution, ResolvedAsset } from "./services/resolve"; export { ConflictError, GuardedPassError, UnguardableError, unguardable } from "./services/guard"; export type { GuardedOptions, GuardedResult, Unguardable, UnguardableCode } from "./services/guard"; export { BatchRecordError, BatchSendError, ReceiptVersionError, isReceipt } from "./services/batch"; -export type { BatchOptions, Described, Drifted, NameLookupFailure, Named, Receipt, Reverse, ReversibleReceipt } from "./services/batch"; +export type { BatchOptions, Described, Drifted, NameLookupFailure, Named, Receipt, ReceiptAsset, Reverse, ReversibleReceipt } from "./services/batch"; diff --git a/src/services/batch.ts b/src/services/batch.ts index 1ceb696..dc6ea0b 100644 --- a/src/services/batch.ts +++ b/src/services/batch.ts @@ -87,7 +87,11 @@ const chunks = (list: T[]): T[][] => Array.from({ length: Math.ceil(list.leng const plain = (v: unknown): unknown => Array.isArray(v) ? v.map(plain) : v && typeof v === "object" && "_oid" in v ? momentless(String((v as { _oid: unknown })._oid)) : v ?? null; -export interface Named { number: string | null; name: string | null } +/** What a receipt says of an asset besides its OID, under the names a row uses: its Number and Name, null where its type has none or the lookup failed. */ +export interface Named { Number: string | null; Name: string | null } + +/** An asset on a receipt: a row, as `client.resolve` answers one, without the state. */ +export interface ReceiptAsset extends Named { _oid: Oid; AssetType: AssetTypeToken } /** Told about a name lookup that failed: the type, the assets left unnamed, and why. */ export type NameLookupFailure = (failure: { type: AssetTypeToken; oids: Oid[]; error: unknown }) => void; @@ -114,7 +118,7 @@ export async function namesOf(transport: Transport, schema: Schema, oids: Iterab for (const part of chunks(list)) { try { const rows = await assetApi.query(transport, { from: type, select, filter: ["ID=$oids"], with: { $oids: part }, page: { size: part.length, start: 0 } }); - for (const r of rows) out.set(momentless(r._oid), { number: r.Number ?? null, name: r.Name ?? null }); + for (const r of rows) out.set(momentless(r._oid), { Number: r.Number ?? null, Name: r.Name ?? null }); } catch (error) { onFailure?.({ type, oids: part, error }); } @@ -291,8 +295,10 @@ export interface Receipt { sentAt?: string; /** What the server says the batch did. */ outcome?: assetApi.Outcome; - created: ({ alias: string | null; type: string; oid: Oid } & Named)[]; - touched: ({ oid: Oid } & Named)[]; + /** The assets the batch created, in order, each a row with the alias its create carried (null for a bare create). */ + created: (ReceiptAsset & { alias: string | null })[]; + /** The assets the batch changed or operated on, each a row. */ + touched: ReceiptAsset[]; /** Moment of everything the batch touched, just after it: the stamp a later reverse checks for drift. */ after: Record; /** ChangeDate of the same assets at the same read: `after`, readable, for a message. */ @@ -402,6 +408,8 @@ export async function runBatch(transport: Transport, schema: Schema, commands: C } else { receipt.sentCommands = commands; done = assetApi.outcomeOf(await assetApi.send(transport, commands)); + // Unguarded is where a write to an asset that is gone goes unremarked by the server: say so. + done.unmatched = assetApi.unmatchedOf(commands, done); } } catch (error) { if (error instanceof GuardedPassError) { @@ -417,9 +425,9 @@ export async function runBatch(transport: Transport, schema: Schema, commands: C // The record, from the response alone: nothing below this block can lose it. const hit = [...new Set([...done.modified, ...done.operated])]; - const unnamed = { number: null, name: null }; - receipt.created = done.created.map((oid, i) => ({ alias: described.creates[i]?.alias ?? null, type: described.creates[i]?.type ?? typeOfOid(oid), oid, ...unnamed })); - receipt.touched = hit.map((oid) => ({ oid, ...(names.get(oid) ?? unnamed) })); + const unnamed: Named = { Number: null, Name: null }; + receipt.created = done.created.map((oid, i) => ({ _oid: oid, AssetType: typeOfOid(oid), alias: described.creates[i]?.alias ?? null, ...unnamed })); + receipt.touched = hit.map((oid) => ({ _oid: oid, AssetType: typeOfOid(oid), ...(names.get(oid) ?? unnamed) })); // A failed command names its asset in what was sent: the guard's // with.$oid, or the from of a per-asset command sent as written. const sentAs = receipt.sentCommands ?? []; @@ -445,8 +453,8 @@ export async function runBatch(transport: Transport, schema: Schema, commands: C receipt.reverse = reverseOf(described, receipt.before, done, { openDescendants: receipt.openDescendants, cascaded: receipt.cascaded, canOperate }); } const more = await namesOf(transport, schema, [...done.created, ...hit.filter((oid) => !names.has(oid))], noteFailure); - receipt.created = receipt.created.map((c) => ({ ...c, ...(more.get(c.oid) ?? unnamed) })); - receipt.touched = receipt.touched.map((t) => (names.has(t.oid) ? t : { ...t, ...(more.get(t.oid) ?? unnamed) })); + receipt.created = receipt.created.map((c) => ({ ...c, ...(more.get(c._oid) ?? unnamed) })); + receipt.touched = receipt.touched.map((t) => (names.has(t._oid) ? t : { ...t, ...(more.get(t._oid) ?? unnamed) })); // The cascade's descendants too: a later reverse reopens them, and checks them for changes first. const all = [...new Set([...done.created, ...hit, ...Object.values(receipt.cascaded).flat()])]; const versions = all.length ? await versionsOf(transport, all) : {}; @@ -488,15 +496,15 @@ async function versionsOf(transport: Transport, oids: Oid[]): Promise isOidToken(spec); const answer = (spec: string): ResolvedAsset | undefined => (isOid(spec) ? byOid.get(momentless(spec)) : byNumber.get(spec.toUpperCase())); - return { found: asked.flatMap((s) => answer(s) ?? []), missing: asked.filter((s) => !answer(s)) }; + // One entry per asset, in the order first asked for: a number and the OID of the same asset are one asset. + const found = [...new Map(asked.flatMap((s) => { const a = answer(s); return a ? [[a._oid, a] as const] : []; })).values()]; + return { found, missing: asked.filter((s) => !answer(s)) }; } diff --git a/src/testing/index.ts b/src/testing/index.ts index 4e38b6b..61c3d22 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -160,8 +160,9 @@ function answerSend(script: Script, commands: Command[], writes: { body: Command const out: Required = { created: [], modified: [], operated: [], failures: [] }; for (const { body } of writes) { const guarded = guardedOn(body); - // A guarded command applies only to an asset that exists, at the moment it was guarded on; anything else matches nothing. - const target = guarded ? (exists(script, guarded.oid) && String(momentOf(script, guarded.oid)) === guarded.moment ? guarded.oid : null) : "from" in body && isOidToken(body.from) ? momentless(body.from) : null; + // A guarded command applies only to an asset that exists, at the moment it was guarded on; anything else matches + // nothing. A plain one applies to whatever its OID names, unless the test removed that asset. + const target = guarded ? (exists(script, guarded.oid) && String(momentOf(script, guarded.oid)) === guarded.moment ? guarded.oid : null) : "from" in body && isOidToken(body.from) && !script.gone.has(momentless(body.from)) ? momentless(body.from) : null; if ("AssetType" in body) { const oid = `${String(body.AssetType)}:${script.nextId++}`; out.created.push(oid); script.known.add(oid); } else if (target && "update" in body) { out.modified.push(target); bump(script, target); } else if (target && "execute" in body) { out.operated.push(target); bump(script, target); } diff --git a/src/types/asset.ts b/src/types/asset.ts index 1cc973d..f90648a 100644 --- a/src/types/asset.ts +++ b/src/types/asset.ts @@ -75,20 +75,25 @@ export interface Asset extends CustomAttributes { } /** - * What an AssetState means for someone deciding what to do with the asset: - * "open" (Future, Active), "closed" (Closed), "template" (Template), - * "deleted" (Dead, Deleted), or "other" for the server's two rare states - * (OldBrokenDownStory, Deprecated) and anything unknown. Takes a name or a - * code, as assetStateOf does; null for no value. + * What an AssetState means for someone deciding what to do with the asset, + * for the four states whose meaning is established against a server: + * "open" Active + * "closed" Closed + * "template" code 200, which the server sends as "200" (it has no name + * for it; `Template` is this SDK's) + * "deleted" Deleted + * and "other" for every other state — Future, Dead (the server's word for + * the whole range from 192 up, not a state rows are seen to carry), + * OldBrokenDownStory (a story that was split: dead, not deleted), + * Deprecated — and for a value it does not know. Null for no value. Takes + * a name or a code, as assetStateOf does. */ export function assetStateKind(value: unknown): "open" | "closed" | "template" | "deleted" | "other" | null { switch (assetStateOf(value)) { case null: return null; - case "Future": case "Active": return "open"; case "Closed": return "closed"; case "Template": return "template"; - case "Dead": case "Deleted": return "deleted"; default: return "other"; } diff --git a/src/types/query.ts b/src/types/query.ts index 0165113..eddb8ba 100644 --- a/src/types/query.ts +++ b/src/types/query.ts @@ -56,11 +56,13 @@ export type SelectKey = E extends string ? E : E extends { from: infer F exte /** * The value a selected key carries on rows of T: the attribute's type when * the key is one, a number for an aggregate, unknown for a path the model - * cannot follow. A single relation is always `| null`, even one the + * cannot follow. A selected key is never absent from a row (the rows + * rule), so an optional attribute loses its `undefined`: it is its value + * or null. A single relation is always `| null`, even one the * metamodel calls required: the asset it pointed at may have been deleted * (a Conversation's Topic, live 2026-11-26). */ -export type SelectValue = K extends keyof T ? (T[K] extends { _oid: string } ? T[K] | null : T[K]) : K extends `${string}.@${string}` ? number : unknown; +export type SelectValue = K extends keyof T ? (Exclude extends { _oid: string } ? Exclude | null : Exclude) : K extends `${string}.@${string}` ? number : unknown; /** The asset type behind a relation attribute's value (`Ref[]`, `Ref | null`), or Asset when it is not one. */ type Related = NonNullable extends readonly (infer R)[] ? Target : Target>; diff --git a/src/wire/assetApi.ts b/src/wire/assetApi.ts index 982def0..2c98b47 100644 --- a/src/wire/assetApi.ts +++ b/src/wire/assetApi.ts @@ -229,8 +229,9 @@ export function mergeOutcome(into: Outcome, done * nothing (see Outcome.unmatched). An update that matched is in `modified` * even when it changed no value, and an operation that ran is in * `operated`, so absence from both with no failure is "nothing was there to - * act on". Aliased commands are left out: an alias's target is not known - * from the request. + * act on". An aliased command counts like a bare one when its `from` is an + * OID; one whose `from` is another alias is left out (its target is not + * known from the request). */ export function unmatchedOf(commands: readonly Command[], outcome: Pick): number[] { const failed = new Set(outcome.failures.map((f) => f.index)); @@ -238,8 +239,9 @@ export function unmatchedOf(commands: readonly Command[], outcome: Pick { - const body = c as Partial; - if (typeof body.from !== "string" || !/^[A-Za-z][A-Za-z0-9_]*:\d+(:\d+)?$/.test(body.from) || failed.has(index)) return []; + // Aliased or bare: what matters is that the command names one asset by its OID. + const body = bodyOf(c) as Partial; + if (typeof body?.from !== "string" || !/^[A-Za-z][A-Za-z0-9_]*:\d+(:\d+)?$/.test(body.from) || failed.has(index)) return []; if ("update" in body) return modified.has(momentless(body.from)) ? [] : [index]; if ("execute" in body) return operated.has(momentless(body.from)) ? [] : [index]; return []; @@ -300,7 +302,7 @@ export interface SendOptions extends ReadOptions { } /** A command's body, aliased or bare. */ -const bodyOf = (c: Command): unknown => { const keys = Object.keys(c); return keys.length === 1 && keys[0]!.startsWith("@") ? (c as Record)[keys[0]!] : c; }; +function bodyOf(c: Command): unknown { const keys = Object.keys(c); return keys.length === 1 && keys[0]!.startsWith("@") ? (c as Record)[keys[0]!] : c; } const isQuery = (body: unknown): body is QueryBody => !!body && typeof body === "object" && typeof (body as QueryBody).from === "string" && !("update" in body) && !("execute" in body) && !("AssetType" in body); /** The query commands of a batch, in order, each with its index in the batch. */ function queriesIn(commands: Command[]): { body: QueryBody; index: number }[] { diff --git a/test/integration/batch.test.ts b/test/integration/batch.test.ts index b86fed9..8a83a8a 100644 --- a/test/integration/batch.test.ts +++ b/test/integration/batch.test.ts @@ -36,15 +36,15 @@ describeInstance("batch (live)", () => { { "@t": { AssetType: "Task", Name: fixtureName("batch task"), Parent: { _oid: a } } } ], { guard: true }); const task = receipt.created[0]!; - created.push(task.oid); + created.push(task._oid); expect(receipt.sent && receipt.guarded).toBe(true); expect(receipt.outcome!.failures).toEqual([]); expect(receipt.conflicts).toEqual([]); - expect(task).toMatchObject({ alias: "@t", type: "Task", number: expect.stringMatching(/-\d+$/) }); - expect(receipt.touched.map((x) => x.oid).sort()).toEqual([a, b].sort()); + expect(task).toMatchObject({ alias: "@t", AssetType: "Task", Number: expect.stringMatching(/-\d+$/) }); + expect(receipt.touched.map((x) => x._oid).sort()).toEqual([a, b].sort()); expect(receipt.before[a]).toMatchObject({ Estimate: "1", Owners: [] }); expect(receipt.before[b]).toMatchObject({ Estimate: null, Owners: [] }); - expect(Object.keys(receipt.after).sort()).toEqual([a, b, task.oid].sort()); + expect(Object.keys(receipt.after).sort()).toEqual([a, b, task._oid].sort()); // Stamps are Moments: digits, guarded on the snapshot's, advanced by the batch; the readable time rides beside. expect(receipt).toMatchObject({ receipt: 2, stopped: null }); for (const oid of [a, b]) { @@ -61,7 +61,7 @@ describeInstance("batch (live)", () => { expect(undone.outcome!.failures).toEqual([]); expect(await read(a)).toMatchObject({ Estimate: "1", Owners: [] }); expect(await read(b)).toMatchObject({ Estimate: null, Owners: [] }); - const [gone] = await assetApi.query<{ _oid: string; AssetState: string }>(t, { from: task.oid, select: ["AssetState"], page: { size: 1, start: 0 } }); + const [gone] = await assetApi.query<{ _oid: string; AssetState: string }>(t, { from: task._oid, select: ["AssetState"], page: { size: 1, start: 0 } }); expect(gone?.AssetState ?? "Deleted").toMatch(/Dead|Deleted/); }); @@ -82,7 +82,7 @@ describeInstance("batch (live)", () => { expect(receipt.sent).toBe(true); expect(receipt.outcome!.failures).toEqual([]); expect(receipt.described.deferred).toEqual([{ index: 0, alias: "@close", from: story, kind: "execute" }]); - expect(receipt.touched).toEqual([expect.objectContaining({ oid: story, name: expect.stringContaining("batch aliased") })]); + expect(receipt.touched).toEqual([expect.objectContaining({ _oid: story, AssetType: "Story", Name: expect.stringContaining("batch aliased") })]); expect(receipt.after[story]).toMatch(/^\d+$/); expect(receipt.changedAt[story]).toMatch(/^\d{4}-/); const [row] = await assetApi.query<{ _oid: string; AssetState: string }>(t, { from: story, select: ["AssetState"], page: { size: 1, start: 0 } }); @@ -90,7 +90,7 @@ describeInstance("batch (live)", () => { }); it("undoing a batch whose created asset was closed since reactivates it first, then deletes it (Agility refuses to delete a closed asset)", async () => { const receipt = await client.batch.run([{ "@s": { AssetType: "Story", Name: fixtureName("batch undo closed"), Scope: { _oid: "Scope:0" } } }], { guard: true }); - const story = receipt.created[0]!.oid; + const story = receipt.created[0]!._oid; created.push(story); await assetApi.send(t, [{ from: story, execute: "QuickClose" }], { throwOnFailure: true }); // Closing it changed it since the batch, so the reverse is forced. @@ -142,7 +142,7 @@ describeInstance("batch (live)", () => { { "@e": { AssetType: "Expression", BelongsTo: "@c", Content: fixtureName("reverse conversation") } } ], { guard: true }); expect(receipt.outcome!.failures).toEqual([]); - const [conversation, expression] = [receipt.created[0]!.oid, receipt.created[1]!.oid]; + const [conversation, expression] = [receipt.created[0]!._oid, receipt.created[1]!._oid]; expect(conversation).toMatch(/^Conversation:/); expect(receipt.reverse.commands).toEqual([{ from: expression, execute: "Delete" }]); expect(receipt.reverse.notes.join("\n")).toMatch(new RegExp(`${conversation}: Conversation has no Delete operation`)); diff --git a/test/integration/client.test.ts b/test/integration/client.test.ts index 98b4ba9..8e48ebc 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 { assetStateKind } from "../../src/types/asset"; import { normalizeQuery } from "../../src/wire/rest1"; import { describeInstance, fixtureName, instance } from "./instance"; @@ -92,6 +93,10 @@ describeInstance("client reads (live)", () => { // Both are gone now (the Conversation went with its last Expression): an update by OID matches nothing, and says so. expect(await client.send([{ from: story, update: { Name: "x" } }, { from: conversation, execute: "Join" }])).toMatchObject({ modified: [], operated: [], failures: [], unmatched: [0, 1] }); expect(await client.get(conversation)).toBeNull(); + // The same for a command under an alias, and on the receipt of a batch sent unguarded (where nothing else would say so). + expect(await client.send([{ "@u": { from: story, update: { Name: "x" } } }])).toMatchObject({ modified: [], failures: [], unmatched: [0] }); + const receipt = await client.batch.run([{ "@u": { from: story, update: { Name: "x" } } }], { guard: false }); + expect(receipt).toMatchObject({ sent: true, guarded: false, conflicts: [], outcome: { modified: [], failures: [], unmatched: [0] } }); }); it("explain says real failures in a sentence with the instance's labels, in one loc-2 request; nothing is created", async () => { @@ -112,6 +117,27 @@ describeInstance("client reads (live)", () => { expect(explained[2]!.sentence).toBe(outcome.failures[2]!.message); }); + it("assetStateKind agrees with the server for the states it names: a live story open, then closed, then deleted; a template, where the instance has one", async () => { + const made = await client.send([{ AssetType: "Story", Name: fixtureName("state kind"), Scope: "Scope:0" }], { throwOnFailure: true }); + const story = made.created[0]!; + const state = async () => (await client.get<{ _oid: string; AssetState: string }>(story, ["AssetState"]))?.AssetState; + try { + expect([await state(), assetStateKind(await state())]).toEqual(["Active", "open"]); + await client.send([{ from: story, execute: "QuickClose" }], { throwOnFailure: true }); + expect([await state(), assetStateKind(await state())]).toEqual(["Closed", "closed"]); + await client.send([{ from: story, execute: "Reactivate" }], { throwOnFailure: true }); + } finally { + await client.send([{ from: story, execute: "Delete" }]); + } + // Gone from an ordinary read; rest-1's deleted read still shows it, and says Deleted. + expect(await client.get(story)).toBeNull(); + const [deleted] = (await client.data.list<{ _oid: string; AssetState: string }>("Story", { select: ["AssetState"], filter: [`ID='${story}'`], deleted: true, page: { size: 1, start: 0 } })).rows; + expect([deleted?.AssetState, assetStateKind(deleted?.AssetState)]).toEqual(["Deleted", "deleted"]); + // A template is state 200, which query.v1 sends as "200" and the model names Template. (None on an empty instance: then nothing is asserted.) + const [template] = await client.query<{ _oid: string; AssetState: string }>({ from: "Story", select: ["AssetState"], filter: ["AssetState='200'"], page: { size: 1, start: 0 } }); + if (template) expect(assetStateKind(template.AssetState)).toBe("template"); + }); + 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/integration/resolve.test.ts b/test/integration/resolve.test.ts index 1b1c246..af82d1e 100644 --- a/test/integration/resolve.test.ts +++ b/test/integration/resolve.test.ts @@ -46,7 +46,7 @@ describeInstance("resolve (live)", () => { expect(await client.resolve.ref("I-999999999")).toBeNull(); }); - it("refs reads numbers and OID tokens mixed, in the order asked, in two requests; what names nothing is missing", async () => { + it("refs reads numbers and OID tokens mixed, in the order first asked, in two requests; an asset named twice is found once; what names nothing is missing", async () => { const calls: string[] = []; const counting = new AgilityApiClient({ baseUrl: instance!.url }, { transport: { request: (o) => { if (!o.path.startsWith("/meta.v1")) calls.push(o.path); return t.request(o); } }, types: client.schema.cache }); await counting.schema.load("Story"); await counting.schema.load("Issue"); await counting.schema.load("Member"); @@ -57,9 +57,8 @@ describeInstance("resolve (live)", () => { expect(res.found).toEqual([ { _oid: issue.oid, AssetType: "Issue", Number: issue.number, Name: expect.stringContaining("resolve issue"), AssetState: "Active" }, { _oid: story.oid, AssetType: "Story", Number: story.number, Name: expect.stringContaining("resolve story"), AssetState: "Active" }, - { _oid: me._oid, AssetType: "Member", Number: null, Name: me.Name, AssetState: "Active" }, // a Member has no Number: not asked for, so the query is not refused - { _oid: story.oid, AssetType: "Story", Number: story.number, Name: expect.stringContaining("resolve story"), AssetState: "Active" } - ]); + { _oid: me._oid, AssetType: "Member", Number: null, Name: me.Name, AssetState: "Active" } // a Member has no Number: not asked for, so the query is not refused + ]); // the story was asked for twice, by its number and by its OID: one asset, found once expect(res.missing).toEqual(["Story:999999999", "S-999999999"]); }); }); diff --git a/test/unit/batch.test.ts b/test/unit/batch.test.ts index 0a59c31..37e3327 100644 --- a/test/unit/batch.test.ts +++ b/test/unit/batch.test.ts @@ -78,8 +78,8 @@ group("batch", () => { expect(sent[1]).toEqual({ from: "Story", where: { ID: "$oid", Moment: "$moment" }, filter: ["RetireDateUTC=''"], with: { $oid: "Story:1", $moment: "100" }, update: { Estimate: { add: ["5"], remove: [] }, Owners: { add: ["Member:20"], remove: [] } } }); expect(t.calls.at(-3)!.idempotent).toBe(false); // the batch creates: never resent expect(r.sent && r.guarded).toBe(true); - expect(r.created).toEqual([{ alias: "@t", type: "Task", oid: "Task:50", number: "TK-50", name: "new task" }]); - expect(r.touched).toEqual([{ oid: "Story:1", number: "S-1", name: "One" }, { oid: "Epic:9", number: "E-9", name: "Nine" }]); + expect(r.created).toEqual([{ _oid: "Task:50", AssetType: "Task", alias: "@t", Number: "TK-50", Name: "new task" }]); + expect(r.touched).toEqual([{ _oid: "Story:1", AssetType: "Story", Number: "S-1", Name: "One" }, { _oid: "Epic:9", AssetType: "Epic", Number: "E-9", Name: "Nine" }]); expect(r.conflicts).toEqual(["Story:2"]); expect(r).toMatchObject({ receipt: 2, stopped: null, stamps: { "Story:1": "100", "Story:2": "200", "Epic:9": "300" } }); expect(r.after).toEqual(AFTER); @@ -207,7 +207,7 @@ group("batch", () => { expect(sent).toEqual(close); expect(r.sent).toBe(true); expect(r.described.deferred).toEqual([{ index: 0, alias: "@close", from: "Story:20", kind: "execute" }]); - expect(r.touched).toEqual([{ oid: "Story:20", number: "S-20", name: "Twenty" }]); // named after the send: preview never listed it + expect(r.touched).toEqual([{ _oid: "Story:20", AssetType: "Story", Number: "S-20", Name: "Twenty" }]); // named after the send: preview never listed it expect(r.after).toEqual({ "Story:20": "900" }); expect(r.changedAt).toEqual({ "Story:20": "2026-11-06T10:00:00.1" }); expect(r.conflicts).toEqual([]); // not guarded: nothing is compared, so nothing conflicts @@ -220,10 +220,10 @@ group("batch", () => { const t = server({ preview: PREVIEW, lookup, send: () => envelope({ assetsCreated: { oidTokens: ["Task:50"], count: 1 }, assetsModified: { oidTokens: ["Story:1"], count: 1 }, assetsOperatedOn: { oidTokens: ["Epic:9"], count: 1 } }) }); let seen: Receipt["names"] | undefined; const r = await runBatch(t, schema, REQUEST, { guard: true, confirm: (receipt) => { seen = receipt.names; return true; } }); - expect(seen).toEqual({ "Story:1": { number: "S-1", name: "One" }, "Story:2": { number: "S-2", name: "Two" }, "Epic:9": { number: "E-9", name: "Nine" } }); + expect(seen).toEqual({ "Story:1": { Number: "S-1", Name: "One" }, "Story:2": { Number: "S-2", Name: "Two" }, "Epic:9": { Number: "E-9", Name: "Nine" } }); const nameQueries = t.calls.filter((c) => (c.body as Q[])[0]?.select?.includes("Name") && (c.body as Q[])[0]?.with?.$oids?.some((o) => o.startsWith("Story"))); expect(nameQueries).toHaveLength(1); // not again after the send - expect(r.touched.map((x) => x.name)).toEqual(["One", "Nine"]); + expect(r.touched.map((x) => x.Name)).toEqual(["One", "Nine"]); expect(r.notes).toEqual([]); const refusing = server({ preview: PREVIEW, lookup: (q) => { if (q.select!.includes("Name") && q.with!.$oids![0]!.startsWith("Epic")) throw new Error("Unknown AttributeDefinition: Epic.Name"); return lookup(q); }, send: () => envelope({ assetsOperatedOn: { oidTokens: ["Epic:9"], count: 1 } }) }); @@ -240,7 +240,7 @@ group("batch", () => { expect(e.message).toMatch(/sent and its outcome recorded.*receipt\.after is incomplete.*socket hang up/); expect(e.receipt.sent).toBe(true); expect(e.receipt.outcome?.created).toEqual(["Task:50"]); - expect(e.receipt.created).toEqual([{ alias: "@t", type: "Task", oid: "Task:50", number: "TK-50", name: "new task" }]); + expect(e.receipt.created).toEqual([{ _oid: "Task:50", AssetType: "Task", alias: "@t", Number: "TK-50", Name: "new task" }]); expect(e.receipt.reverse.commands.length).toBeGreaterThan(0); expect(e.receipt.after).toEqual({}); }); @@ -277,12 +277,13 @@ group("batch", () => { const error = (await reversible(t, old).catch((e: unknown) => e)) as ReceiptVersionError; expect(error).toBeInstanceOf(ReceiptVersionError); expect(error).toMatchObject({ kind: "usage", code: "RECEIPT_VERSION", status: 0, receiptVersion: 1, targets: ["Story:1"] }); - expect(error.message).toMatch(/before 1\.0\.0-alpha\.8.*Reverse it with force.*or run the batch again/); + expect(error.message).toMatch(/format 1, which recorded each asset's ChangeDate.*format 2.*Reverse it with force.*or run the batch again/); + expect(error.message).not.toMatch(/alpha/); // a consumer's user knows the consumer's version, not this package's expect(await reversible(t, old, { force: true })).toEqual({ commands: old.reverse.commands, drifted: [], reactivated: [] }); // Fields picked by hand without the version: a compile error; for a caller the types do not reach, a refusal that says what is missing. // @ts-expect-error `receipt` (the format) is required const picked = reversible(t, { after: {}, reverse: old.reverse }); - await expect(picked).rejects.toThrow(/has no format version.*pass the whole receipt/); + await expect(picked).rejects.toThrow(/has no format number.*pass the whole receipt/); await expect(picked).rejects.toMatchObject({ code: "RECEIPT_VERSION", receiptVersion: undefined }); expect(t.calls).toHaveLength(0); }); diff --git a/test/unit/client.test.ts b/test/unit/client.test.ts index 2f0ff6c..bef03d7 100644 --- a/test/unit/client.test.ts +++ b/test/unit/client.test.ts @@ -32,28 +32,35 @@ const envelope = (over: Partial = {}): AssetApiResponse => ({ }); describe("unmatched, asset state kinds and the fetch a transport calls", () => { - it("unmatchedOf flags an update or operation by OID that is in neither list and has no failure; a query-scoped or aliased command, a failed one, and a failure nobody can place are not flagged", () => { + it("unmatchedOf flags an update or operation by OID that is in neither list and has no failure; a query-scoped command, a failed one, and a failure nobody can place are not flagged", () => { const commands = [ { from: "Story:1", update: { Name: "a" } }, // applied { from: "Story:2:77", update: { Name: "b" } }, // nothing: gone { from: "Conversation:3", execute: "Delete" }, // nothing: no such operation { from: "Story:4", execute: "QuickClose" }, // failed { from: "Story", filter: ["Number='S-0'"], update: { Name: "c" } }, // matching nothing is an answer - { "@u": { from: "Story:5", update: { Name: "d" } } }, // aliased: not known from the request + { "@u": { from: "Story:5", update: { Name: "d" } } }, // aliased, by OID: counts like a bare one { from: "Story:6", select: ["Name"], page: { size: 1, start: 0 } }, { AssetType: "Story", Name: "new" } ] as never[]; const failure = (index: number | null) => ({ index, message: "x", violation: null, echoed: {} }); - expect(unmatchedOf(commands, { modified: ["Story:1:900"], operated: [], failures: [failure(3)] })).toEqual([1, 2]); + expect(unmatchedOf(commands, { modified: ["Story:1:900"], operated: [], failures: [failure(3)] })).toEqual([1, 2, 5]); + expect(unmatchedOf(commands, { modified: ["Story:1", "Story:5"], operated: [], failures: [failure(3)] })).toEqual([1, 2]); + // An aliased write from another alias names no asset the request can show. + expect(unmatchedOf([{ "@u": { from: "@s", update: { Name: "d" } } }] as never[], { modified: [], operated: [], failures: [] })).toEqual([]); expect(unmatchedOf(commands, { modified: ["Story:1"], operated: [], failures: [failure(null)] })).toEqual([]); // An update does not count as an operation, nor the reverse. expect(unmatchedOf([{ from: "Story:1", execute: "QuickClose" }], { modified: ["Story:1"], operated: [], failures: [] })).toEqual([0]); }); - it("assetStateKind reads a name or a code as what to do with the asset", () => { - expect(["Active", "Future", 64, "0"].map(assetStateKind)).toEqual(["open", "open", "open", "open"]); - expect(["Closed", 128, "Template", "200", "Dead", 255, "Deleted"].map(assetStateKind)).toEqual(["closed", "closed", "template", "template", "deleted", "deleted", "deleted"]); - expect([208, "Deprecated", "Whatever", null, undefined].map(assetStateKind)).toEqual(["other", "other", "other", null, null]); + it("assetStateKind names the four states whose meaning is established against a server, by name or code, and calls everything else other", () => { + expect(["Active", 64, "64"].map(assetStateKind)).toEqual(["open", "open", "open"]); + expect(["Closed", 128].map(assetStateKind)).toEqual(["closed", "closed"]); + expect(["200", 200, "Template"].map(assetStateKind)).toEqual(["template", "template", "template"]); // the server sends "200"; Template is this SDK's name for it + expect(["Deleted", 255].map(assetStateKind)).toEqual(["deleted", "deleted"]); + // Not claimed: Future, Dead (a range, not a state rows carry), a split story (dead, not deleted), Deprecated, the unknown. + expect(["Future", 0, "Dead", 192, "OldBrokenDownStory", 208, "Deprecated", "Whatever"].map(assetStateKind)).toEqual(Array(8).fill("other")); + expect([null, undefined].map(assetStateKind)).toEqual([null, null]); }); it("the fetch transport calls whatever the global fetch is when the request is made, so a stub installed after the client was built is used", async () => { diff --git a/test/unit/testing.test.ts b/test/unit/testing.test.ts index 4b0de19..fae0479 100644 --- a/test/unit/testing.test.ts +++ b/test/unit/testing.test.ts @@ -197,7 +197,7 @@ describe("FakeAgilityClient", () => { const receipt = await fake.batch.run([{ from: "Story:1", update: { Estimate: 8 } }, { from: "Story:2", update: { Estimate: 8 } }, { "@t": { AssetType: "Task", Name: "new", Parent: "Story:1" } }], { guard: true }); expect(receipt).toMatchObject({ receipt: 2, sent: true, guarded: true, stopped: null, conflicts: [], failed: [], stamps: { "Story:1": "1", "Story:2": "1" }, after: { "Story:1": "2", "Story:2": "2", "Task:1000": "1" } }); expect(receipt.before["Story:1"]).toMatchObject({ Estimate: 3, Moment: "1" }); - expect(receipt.created).toMatchObject([{ alias: "@t", type: "Task", oid: "Task:1000" }]); + expect(receipt.created).toMatchObject([{ alias: "@t", AssetType: "Task", _oid: "Task:1000" }]); expect(receipt.reverse.commands).toEqual([{ from: "Story:1", update: { Estimate: 3 } }, { from: "Story:2", update: { Estimate: 3 + 2 } }, { from: "Task:1000", execute: "Delete" }]); expect((await fake.batch.reversible(receipt)).drifted).toEqual([]); fake.touch("Story:2"); @@ -208,6 +208,9 @@ describe("FakeAgilityClient", () => { fake.onQuery("Epic", [{ _oid: "Epic:9", Name: "Nine" }]); const racing = await fake.batch.run([{ from: "Epic:9", update: { Name: "x" } }], { guard: true, confirm: () => { fake.touch("Epic:9"); return true; } }); expect(racing).toMatchObject({ sent: true, conflicts: ["Epic:9"], touched: [] }); + // Sent unguarded to an asset that is gone: the receipt's outcome says the command matched nothing. + fake.remove("Epic:9"); + expect((await fake.batch.run([{ from: "Epic:9", update: { Name: "x" } }], { guard: false })).outcome).toMatchObject({ modified: [], unmatched: [0] }); expect(await fake.batch.run([{ from: "Epic:9", update: { Name: "x" } }], { guard: true, dryRun: true })).toMatchObject({ sent: false, stopped: "dryRun" }); }); diff --git a/test/unit/typedQuery.test.ts b/test/unit/typedQuery.test.ts index ac657c4..0c8e625 100644 --- a/test/unit/typedQuery.test.ts +++ b/test/unit/typedQuery.test.ts @@ -23,8 +23,8 @@ describe("typed queries", () => { const rows = await client.query({ from: "Story", select: ["Name", "Estimate", "Status", "Status.Name", "Owners.@Count", { from: "Owners", select: ["Name"] }], page: { size: 1, start: 0 } }); expectTypeOf(rows[0]!._oid).toEqualTypeOf(); expectTypeOf(rows[0]!.Name).toEqualTypeOf(); - expectTypeOf(rows[0]!.Estimate).toEqualTypeOf(); - expectTypeOf(rows[0]!.Status).toEqualTypeOf | null | undefined>(); + expectTypeOf(rows[0]!.Estimate).toEqualTypeOf(); + expectTypeOf(rows[0]!.Status).toEqualTypeOf | null>(); expectTypeOf(rows[0]!["Status.Name"]).toEqualTypeOf(); expectTypeOf(rows[0]!["Owners.@Count"]).toEqualTypeOf(); // A sub-select is rows of the related type with what it selected, not bare Refs. @@ -42,20 +42,20 @@ describe("typed queries", () => { const [byOid] = await client.query({ from: "Story:1055", select: ["Name"], page: { size: 1, start: 0 } }); expectTypeOf(byOid!.Name).toEqualTypeOf(); const got = await client.get("Story:1055", ["Name", "Number"]); - expectTypeOf(got).toEqualTypeOf<(Asset & { Name: string; Number: string | null | undefined }) | null>(); + expectTypeOf(got).toEqualTypeOf<(Asset & { Name: string; Number: string | null }) | null>(); }); it("a custom list type (Custom_, a subtype of List) has List's attributes and its own token; custom and reciprocal attributes are attribute values", async () => { const [value] = await client.query({ from: "Custom_Demo_List", select: ["Name", "Order", "Inactive", "ReciprocalOf_Story_Custom_Demo_Single_List"], page: { size: 1, start: 0 } }); expectTypeOf(value!.Name).toEqualTypeOf(); - expectTypeOf(value!.Order).toEqualTypeOf(); - expectTypeOf(value!.Inactive).toEqualTypeOf(); - expectTypeOf(value!.ReciprocalOf_Story_Custom_Demo_Single_List).toEqualTypeOf(); + expectTypeOf(value!.Order).toEqualTypeOf(); + expectTypeOf(value!.Inactive).toEqualTypeOf(); + expectTypeOf(value!.ReciprocalOf_Story_Custom_Demo_Single_List).toEqualTypeOf(); const byOid = await client.get("Custom_Demo_List:12", ["AssetType", "ColorName"]); expectTypeOf(byOid!.AssetType).toEqualTypeOf<"Custom_Demo_List">(); expectTypeOf(byOid!.ColorName).toEqualTypeOf(); const [story] = await client.query({ from: "Story", select: ["Custom_Demo_List", "Custom_Points"], page: { size: 1, start: 0 } }); - expectTypeOf(story!.Custom_Demo_List).toEqualTypeOf(); + expectTypeOf(story!.Custom_Demo_List).toEqualTypeOf(); // @ts-expect-error a List has no Estimate value!.Estimate; expect(value).toBeDefined(); @@ -67,7 +67,7 @@ describe("typed queries", () => { { from: "Story", select: ["Name", "Estimate"], page: { size: 1, start: 0 } }, { from: "Scope", select: ["Name"], page: { size: 1, start: 0 } } ]); - expectTypeOf(stories[0]!.Estimate).toEqualTypeOf(); + expectTypeOf(stories[0]!.Estimate).toEqualTypeOf(); expectTypeOf(scopes[0]!.Name).toEqualTypeOf(); // @ts-expect-error Estimate was not selected on Scope scopes[0]!.Estimate; @@ -99,7 +99,7 @@ describe("typed sub-selects and a consumer's own row type", () => { type Row = (typeof rows)[number]; expectTypeOf().toEqualTypeOf(); expectTypeOf().toEqualTypeOf(); - expectTypeOf["IsInactive"]>().toEqualTypeOf(); + expectTypeOf["IsInactive"]>().toEqualTypeOf(); expectTypeOf().toBeNullable(); expectTypeOf().toEqualTypeOf(); // A bare single relation can be null on a row even where the metamodel calls it required. @@ -124,7 +124,7 @@ describe("typed attachment listing", () => { 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]!.Days).toEqualTypeOf(); expectTypeOf(more[0]!["Asset.Number"]).toBeUnknown(); // @ts-expect-error IsDeleted was not selected void more[0]!.IsDeleted; @@ -140,6 +140,6 @@ describe("typed attachment listing", () => { 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(); + expectTypeOf(paged.attachments[0]!.Days).toEqualTypeOf(); }); }); From 73872968961c341a4f3f3f588eadc00504f0a4aa Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:49:29 +0000 Subject: [PATCH 11/17] alpha.8: the resend rule is the client's, with any Transport; onError; reauthorize: false - An idempotent request (a GET, a query.v1 read, a guarded batch with no creates) is sent once more after a transient failure whichever Transport the client has: the built-in one does it itself, and the client does it around a custom one (core/retry). `retries: 0` turns it off per client. A plain write, a 401, a 403, any other 4xx and an aborted request are never resent. A behaviour change for a consumer with its own transport; the changelog says what to do when that transport reports errors to a user before throwing, or resends on its own. - ClientConfig.onError(error, request) is told about each request that finally failed, after any resend, with any transport; it observes. - RequestOptions.reauthorize: false skips the unauthorized hook for that request, so a hook's own "is the session alive" request cannot wait on itself. - withSignal does not stack a second resend; the fake resends nothing unless asked. Merged master (alpha.7 is released from there). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 27 ++++++++++ README.md | 1 + specs/000-layers.md | 11 +++- src/client.ts | 15 +++++- src/core/clientConfig.ts | 21 ++++++-- src/core/fetchTransport.ts | 2 +- src/core/retry.ts | 57 ++++++++++++++++++++ src/core/transport.ts | 9 ++++ src/index.ts | 1 + src/testing/index.ts | 3 +- test/unit/retry.test.ts | 105 +++++++++++++++++++++++++++++++++++++ 11 files changed, 243 insertions(+), 9 deletions(-) create mode 100644 src/core/retry.ts create mode 100644 test/unit/retry.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1fd0473..79501a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -96,6 +96,23 @@ Each entry has the line a consumer follows to migrate. `bareAliasFrom`, `inlineCreate`, `noMoment`). Migration: branch on `reason.code`, not on the words of `reason.reason`. +- **Idempotent requests are resent once with any Transport, not only the + built-in one.** The rule (a GET, a query.v1 read or a guarded batch + with no creates is sent once more after a network failure, a timeout, + a 5xx or a 429; `retries` says how many times, default 1) was the fetch + transport's; it is now the client's, applied around a custom + `Transport`. A plain write is never resent, nor a 401 or 403 + (re-authentication is the transport's own business), nor any other 4xx, + nor an aborted request. **This changes behaviour for a consumer with a + custom Transport**: its reads start being resent once. Migration: + nothing, if that is welcome. To keep the old behaviour, pass `retries: + 0` in the client's config. A transport that shows an error to the user + before it throws (an interceptor's toast) will have shown the first + failure of a request that then succeeded: either pass `retries: 0` for + that client, or move the reporting to the client's new `onError`, which + is told only about a request that finally failed. A custom transport + that already resends on its own should pass `retries: 0` or stop doing + so, or a read is tried up to four times. - **One rule for every row, on every read path**: a relation you select is a Ref; a path you select by name is at `row[path]`; nothing arrives that you did not select. query.v1 and api/asset rows already followed @@ -146,6 +163,16 @@ Each entry has the line a consumer follows to migrate. ### Added +- **`ClientConfig.onError(error, request)`**: told about every request + that finally failed, after any resend, with any Transport. It + observes: the error is still thrown. For an app-wide toast or a log + line, without a wrapper Transport. +- **`RequestOptions.reauthorize: false`**: a refusal of that request is + answered straight away, without calling the transport's + `onUnauthorized` hook. For the request a hook itself sends to ask + whether the session is alive, which would otherwise wait on itself. +- `withRetry(transport, retries)`: the resend rule as a function, for a + caller that uses a Transport without a client. - **`client.explain(error)`**: an error said to a person. One `Explanation` per failed command (from a `CommandFailureError`, an `Outcome` or its `failures`), or one for any other error: a short diff --git a/README.md b/README.md index 41836d8..f071ac5 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,7 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - Errors: everything thrown is an `ApiError` with a `kind` (`auth`, `forbidden`, `notFound`, `invalid`, `transient`, `aborted`, `commandFailure`, `conflict`, `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 })`); `TypeCache.fromMetamodel(metamodel)` seeds one so nothing is loaded - `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 +- Resends and failures are the client's business with any transport: an idempotent request (a GET, a read, a guarded batch with no creates) is sent once more after a network failure, a timeout, a 5xx or a 429 (`retries`, default 1, 0 for none; never a plain write, a 401 or a 403), and `onError(error, request)` in the config is told about each request that finally failed - 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/services` - the services as free functions over a `Transport` (`guard`, `batch`, `resolve`, `schema`, `attachments`, `fields`), for a caller that composes one differently; the client's methods are the same things - `@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. diff --git a/specs/000-layers.md b/specs/000-layers.md index f95d462..a843f33 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -200,13 +200,20 @@ retries only idempotent requests (GET by default, and every query.v1 POST, since that endpoint cannot write), only on a network failure, a 5xx or a 429 (Retry-After honoured, up to 30 s), never another 4xx, and once by default (`retries: 1`); a batch write is never retried unless the -caller has made it idempotent with a guard and says so. +caller has made it idempotent with a guard and says so. That rule is +the client's, not one transport's: the built-in fetch transport applies it +itself (it can read Retry-After), and the client applies it around a +custom Transport (`core/retry`), so a consumer's transport does not +re-implement it and cannot forget it. `retries: 0` turns it off for a +client. A 401 or 403 is never resent by it. Re-authentication follows the same rule. On a 401 (or a status the caller lists) the transport calls `onUnauthorized` once per request; "retry" resends an idempotent request one more time, outside the `retries` count. A plain write is never resent: the hook still runs, so the session can be repaired, -and the caller decides. A caller's abort (`signal`) ends the request as +and the caller decides. A request sent with `reauthorize: false` skips +the hook: it is how a hook asks whether the session is alive without +waiting on itself. A caller's abort (`signal`) ends the request as `ABORTED` and is never retried. A failure never reads as an empty. api/asset answers 200 and commits per diff --git a/src/client.ts b/src/client.ts index 2216b77..410da5c 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,6 +1,7 @@ import type { ClientConfig } from "./core/clientConfig"; import { ApiError, UsageError } from "./core/errors"; import { createFetchTransport } from "./core/fetchTransport"; +import { withErrorHook, withRetry } from "./core/retry"; import type { Transport } from "./core/transport"; import * as attachments from "./services/attachments"; import * as batch from "./services/batch"; @@ -67,6 +68,9 @@ export type Me = Pick(); + /** Every read is bounded: the type says so, and for a caller the type did not reach this says so before any request (not even a schema load) is sent. */ function bounded(qs: readonly assetApi.QueryBody[]): void { for (const q of qs) if (!q.page) throw new UsageError(`query of ${q.from} without a page: every read must be bounded`); @@ -95,7 +99,9 @@ export class AgilityApiClient { readonly schema: Schema; constructor(config: ClientConfig, opts: ClientOptions = {}) { - this.transport = opts.transport ?? createFetchTransport({ + // The built-in transport resends idempotent requests itself (it can read Retry-After); a custom one gets the + // same rule from the client. A transport another client of ours already dressed (withSignal) is taken as it is. + let transport = opts.transport ?? createFetchTransport({ baseUrl: config.baseUrl, authorization: config.authorization, accessToken: config.accessToken, @@ -106,6 +112,12 @@ export class AgilityApiClient { onUnauthorized: config.onUnauthorized, unauthorizedStatuses: config.unauthorizedStatuses }); + if (!dressed.has(transport)) { + if (opts.transport) transport = withRetry(transport, config.retries ?? 1); + if (config.onError) transport = withErrorHook(transport, config.onError); + dressed.add(transport); + } + this.transport = transport; this.config = config; this.schema = new Schema(this.transport, undefined, opts.types); } @@ -121,6 +133,7 @@ export class AgilityApiClient { withSignal(signal: AbortSignal): AgilityApiClient { const base = this.transport; const transport: Transport = { request: (options) => base.request({ ...options, signal: options.signal ?? signal }) }; + dressed.add(transport); // `base` already resends and reports errors: not twice return new AgilityApiClient(this.config, { transport, types: this.schema.cache }); } diff --git a/src/core/clientConfig.ts b/src/core/clientConfig.ts index a9cb584..131ab47 100644 --- a/src/core/clientConfig.ts +++ b/src/core/clientConfig.ts @@ -1,4 +1,6 @@ +import type { ApiError } from "./errors"; import type { FetchTransportConfig } from "./fetchTransport"; +import type { RequestOptions } from "./transport"; export interface ClientConfig extends Pick { /** @@ -18,11 +20,22 @@ export interface ClientConfig extends Pick; + /** + * Told about every request that finally failed, after any resend: the + * place for an app-wide error toast or a log line, with any Transport. + * It observes; the error is still thrown to the caller, and what this + * returns or throws changes nothing. (A failed command inside a batch + * the server answered 200 is not a failed request: read the Outcome, or + * pass `throwOnFailure` and catch.) + */ + onError?: (error: ApiError, request: RequestOptions) => void; } diff --git a/src/core/fetchTransport.ts b/src/core/fetchTransport.ts index 148e817..317d7dd 100644 --- a/src/core/fetchTransport.ts +++ b/src/core/fetchTransport.ts @@ -215,7 +215,7 @@ export function createFetchTransport(config: FetchTransportConfig): Transport { settle(); } - if (config.onUnauthorized && !reauthorized && unauthorizedStatuses.includes(response.status)) { + if (config.onUnauthorized && options.reauthorize !== false && !reauthorized && unauthorizedStatuses.includes(response.status)) { // One re-authentication per request: a second refusal is final. reauthorized = true; const decision = await config.onUnauthorized({ error: lastError as ApiError, request: options, retryable: idempotent }); diff --git a/src/core/retry.ts b/src/core/retry.ts new file mode 100644 index 0000000..7ea7ca1 --- /dev/null +++ b/src/core/retry.ts @@ -0,0 +1,57 @@ +import { ApiError } from "./errors"; +import type { RequestOptions, Transport } from "./transport"; + +const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); + +/** + * The resend rule, for any Transport: an idempotent request (a GET, or one + * the caller marked — a query.v1 read, a guarded batch with no creates) + * that fails with a transient error (no answer, a timeout, a 5xx, a 429) + * is sent again, `retries` times at most, a little later each time. + * Nothing else is: not a plain write, whatever happened to it; not a 401 + * or 403 (re-authentication is the unauthorized hook's business, and a + * resend would prompt twice); not any other 4xx, which is an answer; not a + * request its caller aborted. + * + * The client puts this around a custom Transport, so the rule is the + * client's and not each transport's to re-implement. The built-in fetch + * transport applies the same rule itself (it can also read Retry-After) + * and is not wrapped again. + */ +export function withRetry(transport: Transport, retries: number): Transport { + const extra = Math.max(0, retries); + if (!extra) return transport; + return { + async request(options: RequestOptions): Promise { + const idempotent = options.idempotent ?? options.method === "GET"; + const attempts = idempotent ? extra + 1 : 1; + for (let attempt = 0; ; attempt += 1) { + try { + return await transport.request(options); + } catch (error) { + const again = attempt + 1 < attempts && error instanceof ApiError && error.kind === "transient" && !options.signal?.aborted; + if (!again) throw error; + await delay(150 * (attempt + 1)); + } + } + } + }; +} + +/** + * A Transport that tells `onError` about every request that finally + * failed (after any resend), and then fails as before. Observation only: + * what the hook returns or throws changes nothing. + */ +export function withErrorHook(transport: Transport, onError: (error: ApiError, request: RequestOptions) => void): Transport { + return { + async request(options: RequestOptions): Promise { + try { + return await transport.request(options); + } catch (error) { + if (error instanceof ApiError) { try { onError(error, options); } catch { /* an observer cannot break the request */ } } + throw error; + } + } + }; +} diff --git a/src/core/transport.ts b/src/core/transport.ts index 4e00ee7..aa680c9 100644 --- a/src/core/transport.ts +++ b/src/core/transport.ts @@ -35,6 +35,15 @@ export interface RequestOptions { * Content-Type, an ETag). A transport that cannot see headers may skip it. */ onResponse?: (response: { status: number; headers: { get(name: string): string | null } }) => void; + /** + * False: a refusal of this request (a 401, or another status the + * transport treats as "not signed in") is answered as an error straight + * away, without calling the transport's re-authentication hook. For the + * request a hook itself sends to ask whether the session is alive: sent + * through the same transport without this, its own refusal would call + * the hook that is waiting for it. + */ + reauthorize?: boolean; /** * The request is conditional (an If-None-Match header is set) and a * 304 Not Modified is an answer, not a failure: the promise then resolves diff --git a/src/index.ts b/src/index.ts index 6aba328..fc2bf1a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,6 +3,7 @@ export type { ClientOptions, Me, Page, PagesOptions } from "./client"; export { ApiError, UsageError, WrappedError, apiErrorFromResponse, kindOf } from "./core/errors"; export type { ErrorKind } from "./core/errors"; export { createFetchTransport } from "./core/fetchTransport"; +export { withRetry } from "./core/retry"; export type { FetchTransportConfig, UnauthorizedContext, UnauthorizedDecision } from "./core/fetchTransport"; export type { ClientConfig } from "./core/clientConfig"; export type { RequestBody, RequestOptions, ResponseType, Transport } from "./core/transport"; diff --git a/src/testing/index.ts b/src/testing/index.ts index 61c3d22..6caf5af 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -357,7 +357,8 @@ export class FakeAgilityClient extends AgilityApiClient { }; // The fake's instance has no asset type (every meta.v1 read answers 404), so rows scripted in the model's shape pass through as written. const { metamodel: _metamodel, ...clientConfig } = config; - super({ baseUrl: "https://agility.example.com/Fake", ...clientConfig }, { transport }); + // No resends by default: an error a test scripts is seen once, as scripted. Pass `retries` to test a resend. + super({ baseUrl: "https://agility.example.com/Fake", retries: 0, ...clientConfig }, { transport }); this.script = script; this.requests = script.seen.requests; this.asked = script.seen.asked; diff --git a/test/unit/retry.test.ts b/test/unit/retry.test.ts new file mode 100644 index 0000000..f02e9cb --- /dev/null +++ b/test/unit/retry.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it, vi } from "vitest"; +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 { FakeAgilityClient } from "../../src/testing"; + +/** + * The resend rule belongs to the client, so it holds with a consumer's + * own Transport: an idempotent request is sent once more after a + * transient failure, and nothing else is ever resent. + */ +function custom(...answers: unknown[]): Transport & { calls: RequestOptions[] } { + const calls: RequestOptions[] = []; + const request = vi.fn(async (o: RequestOptions) => { calls.push(o); const a = answers.shift(); if (a instanceof Error) throw a; return a; }); + return { request: request as Transport["request"], calls }; +} +const envelope = { requestId: "r", assetsCreated: { oidTokens: [], count: 0 }, assetsModified: { oidTokens: ["Story:1"], count: 1 }, assetsOperatedOn: { oidTokens: [], count: 0 }, commandFailures: { commands: [], count: 0 }, queryResult: { results: [], resultMetaData: [], count: 0 } }; +const noTypes = (t: Transport): Transport => ({ request: (o) => (o.path.startsWith("/meta.v1/") ? Promise.reject(new ApiError("Not Found", 404)) : t.request(o)) }); +const q = { from: "Story", select: ["Name"], page: { size: 1, start: 0 } }; + +describe("the resend rule above a custom Transport", () => { + it("a read is sent once more after a 5xx, a lost connection or a timeout, by default", async () => { + for (const failure of [new ApiError("Bad Gateway", 502), new ApiError("fetch failed", 0, "NETWORK_ERROR"), new ApiError("Timed out", 0, "TIMEOUT"), new ApiError("Too Many Requests", 429)]) { + const t = custom(failure, [[{ _oid: "Story:1", Name: "n" }]]); + const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: noTypes(t) }); + expect(await client.query(q)).toEqual([{ _oid: "Story:1", Name: "n" }]); + expect(t.calls).toHaveLength(2); + } + }); + + it("once, not forever; `retries` says how many times, and 0 turns it off", async () => { + const down = () => new ApiError("Service Unavailable", 503); + const once = custom(down(), down(), [[]]); + await expect(new AgilityApiClient({ baseUrl: "https://x" }, { transport: noTypes(once) }).query(q)).rejects.toMatchObject({ status: 503 }); + expect(once.calls).toHaveLength(2); + const twice = custom(down(), down(), [[]]); + expect(await new AgilityApiClient({ baseUrl: "https://x", retries: 2 }, { transport: noTypes(twice) }).query(q)).toEqual([]); + const off = custom(down(), [[]]); + await expect(new AgilityApiClient({ baseUrl: "https://x", retries: 0 }, { transport: noTypes(off) }).query(q)).rejects.toMatchObject({ status: 503 }); + expect(off.calls).toHaveLength(1); + }); + + it("a plain write is never resent, whatever happened to it; a guarded one with no creates may be", async () => { + const write = custom(new ApiError("Bad Gateway", 502), envelope); + const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: write }); + await expect(client.send([{ from: "Story:1", update: { Name: "x" } }])).rejects.toMatchObject({ status: 502 }); + expect(write.calls).toHaveLength(1); + // preview, the Moment read, then the guarded send: it fails once and is sent again, because a resend of it matches nothing if the first one landed. + const guarded = custom([{ "@p": { oid: "Story:1", update: { Name: "x" } } }], { ...envelope, assetsModified: { oidTokens: [], count: 0 }, queryResult: { results: [[{ _oid: "Story:1", Moment: "7" }]], resultMetaData: [], count: 1 } }, new ApiError("Bad Gateway", 502), envelope); + const result = await new AgilityApiClient({ baseUrl: "https://x" }, { transport: guarded }).sendGuarded([{ from: "Story:1", update: { Name: "x" } }]); + expect(result).toMatchObject({ modified: ["Story:1"], conflicts: [] }); + expect(guarded.calls).toHaveLength(4); + }); + + it("a 401 or 403 is never resent (re-authentication is the unauthorized hook's business), nor any other 4xx, nor an aborted request", async () => { + for (const refusal of [new ApiError("Unauthorized", 401), new ApiError("Forbidden", 403), new ApiError("Bad Request", 400), new ApiError("Request aborted", 0, "ABORTED")]) { + const t = custom(refusal, [[]]); + await expect(new AgilityApiClient({ baseUrl: "https://x" }, { transport: noTypes(t) }).query(q)).rejects.toBe(refusal); + expect(t.calls).toHaveLength(1); + } + }); + + it("withSignal does not stack a second resend on the first, and the fake resends nothing unless asked", async () => { + const t = custom(new ApiError("down", 503), new ApiError("down", 503), [[]]); + const scoped = new AgilityApiClient({ baseUrl: "https://x" }, { transport: noTypes(t) }).withSignal(new AbortController().signal); + await expect(scoped.query(q)).rejects.toMatchObject({ status: 503 }); + expect(t.calls).toHaveLength(2); + const fake = new FakeAgilityClient().onQuery("Story", new ApiError("down", 503)); + await expect(fake.query(q)).rejects.toMatchObject({ kind: "transient" }); + expect(fake.asked).toHaveLength(1); + }); +}); + +describe("onError and reauthorize", () => { + it("onError is told once about a request that finally failed, with any transport, and the error is still thrown; a throwing observer changes nothing", async () => { + const seen: [string, string][] = []; + const t = custom(new ApiError("down", 503), new ApiError("still down", 503), [[{ _oid: "Story:1" }]]); + const client = new AgilityApiClient({ baseUrl: "https://x", onError: (error, request) => { seen.push([error.message, request.path]); throw new Error("observer bug"); } }, { transport: noTypes(t) }); + await expect(client.query(q)).rejects.toMatchObject({ message: "still down" }); + expect(seen).toEqual([["Not Found", "/meta.v1/Story"], ["still down", "/query.v1"]]); // the failed type load is a failed request too; the resend that failed is reported once, with the final error + expect(await client.query(q)).toEqual([{ _oid: "Story:1" }]); + expect(seen).toHaveLength(2); + // With the built-in transport as well. + const fetched: string[] = []; + const builtIn = new AgilityApiClient({ baseUrl: "https://x", retries: 0, onError: (e) => fetched.push(e.kind) }); + const original = globalThis.fetch; + globalThis.fetch = (async () => new Response("no", { status: 403 })) as typeof fetch; + try { await expect(builtIn.localize(["Story"])).rejects.toMatchObject({ kind: "forbidden" }); } finally { globalThis.fetch = original; } + expect(fetched).toEqual(["forbidden"]); + }); + + it("a request sent with reauthorize: false is refused straight away, without calling the re-authentication hook it may have been sent from", async () => { + const onUnauthorized = vi.fn(async () => "retry" as const); + const fetchImpl = vi.fn(async () => new Response("Unauthorized", { status: 401 })); + const transport = createFetchTransport({ baseUrl: "https://x", retries: 0, fetchImpl: fetchImpl as unknown as typeof fetch, onUnauthorized }); + await expect(transport.request({ method: "GET", path: "/session", reauthorize: false })).rejects.toMatchObject({ kind: "auth" }); + expect(onUnauthorized).not.toHaveBeenCalled(); + expect(fetchImpl).toHaveBeenCalledOnce(); + // The control: without it the hook runs and its "retry" sends the request once more. + await expect(transport.request({ method: "GET", path: "/session" })).rejects.toMatchObject({ kind: "auth" }); + expect(onUnauthorized).toHaveBeenCalledOnce(); + expect(fetchImpl).toHaveBeenCalledTimes(3); + }); +}); From 44187cde38c05f2e3c4ae93e2bd6afd50874bc54 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:53:08 +0000 Subject: [PATCH 12/17] alpha.8: _oid wherever an object names an asset; explanations say whether they are fit for a user - described.updates / executes and reversible's drifted entries name their asset as _oid, like every other object that carries an asset's identity. No exceptions left to remember. - Explanation.explained: true when the sentence was made for a person (from a rule and the instance's labels, the server's localized sentence, or the kind of error), false when it is only the message as it came: a token the instance has no words for (seen live: closing a closed story), raw server text, or a developer's message such as a usage error. A consumer can explain any error and show only what is explained. - assetStateKind gains "future" for the Future state, which the server names and Timeboxes carry (checked live); "open" is Active alone. - The fake's metamodel option takes any subset of meta.v1 type documents, Version optional: only the types the code under test touches. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 17 +++++++---- src/services/batch.ts | 48 +++++++++++++++--------------- src/services/explain.ts | 52 ++++++++++++++++++++------------- src/testing/index.ts | 26 ++++++++++------- src/types/asset.ts | 13 +++++---- test/integration/batch.test.ts | 2 +- test/integration/client.test.ts | 3 ++ test/unit/batch.test.ts | 8 ++--- test/unit/client.test.ts | 7 +++-- test/unit/explain.test.ts | 12 ++++++-- test/unit/testing.test.ts | 6 +++- 11 files changed, 117 insertions(+), 77 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79501a8..c686cc4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -78,7 +78,9 @@ Each entry has the line a consumer follows to migrate. defaulted to true). Migration: `client.batch.run(commands)` → `client.batch.run(commands, { guard: true })`. - **Receipts are `receipt: 2`**: `skipped` → `conflicts`; new `stamps`, - `changedAt` and `stopped`; and the assets a receipt names are rows, + `changedAt` and `stopped`; `described.updates[i]`, + `described.executes[i]` and `batch.reversible`'s `drifted[i]` name + their asset as `_oid` (was `oid`); and the assets a receipt names are rows, like every other asset the SDK answers: in `created` and `touched`, `oid` → `_oid`, `type` → `AssetType`, `number` → `Number`, `name` → `Name` (`touched` gains `AssetType`); in `names[oid]`, `number` → @@ -180,7 +182,10 @@ Each entry has the line a consumer follows to migrate. the attribute and the asset type, the parts it was made from (`rule`, `attribute`, `attributeLabel`, `typeLabel`), and the server's own `localized` sentence where it has one. `Resolution'…` failures are read - too. One loc-2 request at most. Migration: a consumer's own failure + too. `explained` says whether the sentence is fit to show a user: false + when it is only the message as it came (a token the instance has no + words for, raw server text, a message for a developer), so a caller + can explain any error and show only what is explained. One loc-2 request at most. Migration: a consumer's own failure patterns and three-tag loc-2 lookups can go. - **`transportConformance(make)`** from `@versionone/agility-sdk/testing`: the SDK's expectations of a `Transport` as a list of named checks, @@ -199,7 +204,8 @@ Each entry has the line a consumer follows to migrate. (`client.meta` answers the model's `Metamodel` and is unchanged.) - **`FakeAgilityClient` at the transport's level too**: `new FakeAgilityClient({ metamodel })` gives the fake's instance the asset - types of a meta.v1 document, so a response captured from a server and + types of meta.v1 documents (only the types the code under test + touches are needed), so a response captured from a server and scripted with `onRequest` reads translated, for the fake and for any client built on `fake.transport`; and `onList(type, rows)` scripts `client.data.list` in the model's shape. `sendGuarded` and `batch.run` @@ -220,9 +226,10 @@ Each entry has the line a consumer follows to migrate. and on the receipt of an unguarded `batch.run`, for aliased commands by OID as for bare ones. - `assetStateKind(value)`: an AssetState name or code as `"open"` - (Active), `"closed"` (Closed), `"template"` (code 200) or `"deleted"` + (Active, and only Active), `"future"` (Future: not begun), + `"closed"` (Closed), `"template"` (code 200) or `"deleted"` (Deleted), each checked against a server, and `"other"` for every - other state: it does not guess at Future, Dead or a split story. + other state: it does not guess at Dead or a split story. - The fetch transport calls the global `fetch` as it is at each request (it captured it when the transport was made), so a stub installed later is used without passing `fetchImpl`. diff --git a/src/services/batch.ts b/src/services/batch.ts index dc6ea0b..8ca4eed 100644 --- a/src/services/batch.ts +++ b/src/services/batch.ts @@ -41,8 +41,8 @@ export const CHUNK = 100; export interface Described { creates: { index: number; alias: string | null; type: string; name: string | null }[]; queries: { index: number; from: string }[]; - updates: { oid: Oid; attributes: Record }[]; - executes: { oid: Oid; op: string; args: Record }[]; + updates: { _oid: Oid; attributes: Record }[]; + executes: { _oid: Oid; op: string; args: Record }[]; /** * Aliased updates and executes: preview does not expand them, so they * have no per-asset entry above, no snapshot and no reverse. They are @@ -66,10 +66,10 @@ export function describe(commands: Command[], projected: Command[]): Described { const body = bodyOf(p); if (typeof body.oid !== "string") continue; const oid = momentless(body.oid); - if (body.update && typeof body.update === "object") out.updates.push({ oid, attributes: body.update as Record }); + if (body.update && typeof body.update === "object") out.updates.push({ _oid: oid, attributes: body.update as Record }); else if (body.execute !== undefined) { const e = body.execute as string | { op: string; args?: Record }; - out.executes.push({ oid, op: typeof e === "string" ? e : e.op, args: typeof e === "string" ? {} : e.args ?? {} }); + out.executes.push({ _oid: oid, op: typeof e === "string" ? e : e.op, args: typeof e === "string" ? {} : e.args ?? {} }); } } return out; @@ -131,8 +131,8 @@ export async function namesOf(transport: Transport, schema: Schema, oids: Iterab export async function snapshot(transport: Transport, described: Described): Promise>> { const wanted = new Map>(); const want = (oid: Oid, attrs: string[]) => { const s = wanted.get(oid) ?? new Set(); attrs.forEach((a) => s.add(a)); wanted.set(oid, s); }; - for (const u of described.updates) want(u.oid, [...Object.keys(u.attributes), "Moment", "ChangeDate"]); - for (const e of described.executes) want(e.oid, ["AssetState", "Moment", "ChangeDate"]); + for (const u of described.updates) want(u._oid, [...Object.keys(u.attributes), "Moment", "ChangeDate"]); + for (const e of described.executes) want(e._oid, ["AssetState", "Moment", "ChangeDate"]); const before: Record> = {}; for (const [type, oids] of byType(wanted.keys())) { const select = [...new Set(oids.flatMap((o) => [...wanted.get(o)!]))]; @@ -225,9 +225,9 @@ export function reverseOf(described: Described, before: Record context.canOperate?.(typeOfOid(oid), op) === false; const modified = new Set(done.modified.map(momentless)), operated = new Set(done.operated.map(momentless)); for (const u of described.updates) { - if (!modified.has(u.oid)) continue; - const was = before[u.oid]; - if (!was) { notes.push(`${u.oid}: no snapshot, cannot restore`); continue; } + if (!modified.has(u._oid)) continue; + const was = before[u._oid]; + if (!was) { notes.push(`${u._oid}: no snapshot, cannot restore`); continue; } const update: Record = {}; for (const [attr, change] of Object.entries(u.attributes)) { const prior = was[attr]; @@ -236,29 +236,29 @@ export function reverseOf(described: Described, before: Record !prior.includes(v)), removed = remove.filter((v) => prior.includes(v)); if (added.length || removed.length) update[attr] = { add: removed, remove: added }; - } else if (prior === undefined) notes.push(`${u.oid}.${attr}: not in snapshot, cannot restore`); + } else if (prior === undefined) notes.push(`${u._oid}.${attr}: not in snapshot, cannot restore`); else update[attr] = prior as CommandValue; // a scalar or single relation: put the old value back (null clears) } - if (Object.keys(update).length) commands.push({ from: u.oid, update }); + if (Object.keys(update).length) commands.push({ from: u._oid, update }); } for (const e of described.executes) { - if (!operated.has(e.oid)) continue; + if (!operated.has(e._oid)) continue; const inverse = INVERSE[e.op]; - if (!inverse) { notes.push(`${e.oid}: ${e.op} has no known inverse (was ${String(before[e.oid]?.AssetState ?? "?")})`); continue; } - if (cannot(e.oid, inverse)) { notes.push(`${e.oid}: ${typeOfOid(e.oid)} has no ${inverse} operation, so its ${e.op} is not reversed`); continue; } - commands.push({ from: e.oid, execute: inverse }); + if (!inverse) { notes.push(`${e._oid}: ${e.op} has no known inverse (was ${String(before[e._oid]?.AssetState ?? "?")})`); continue; } + if (cannot(e._oid, inverse)) { notes.push(`${e._oid}: ${typeOfOid(e._oid)} has no ${inverse} operation, so its ${e.op} is not reversed`); continue; } + commands.push({ from: e._oid, execute: inverse }); if (!CASCADING.has(e.op)) continue; - const open = context.openDescendants?.[e.oid] ?? []; - const closed = context.cascaded ? context.cascaded[e.oid] ?? [] : undefined; + const open = context.openDescendants?.[e._oid] ?? []; + const closed = context.cascaded ? context.cascaded[e._oid] ?? [] : undefined; if (closed === undefined) { - if (open.length) notes.push(`${e.oid}: ${e.op} may also have closed ${open.length} open descendant${open.length === 1 ? "" : "s"} (${open.join(", ")}); they could not be read back, so they are not reopened`); + if (open.length) notes.push(`${e._oid}: ${e.op} may also have closed ${open.length} open descendant${open.length === 1 ? "" : "s"} (${open.join(", ")}); they could not be read back, so they are not reopened`); continue; } for (const d of closed) { - if (cannot(d, "Reactivate")) notes.push(`${d}: closed with ${e.oid}, but ${typeOfOid(d)} has no Reactivate operation`); + if (cannot(d, "Reactivate")) notes.push(`${d}: closed with ${e._oid}, but ${typeOfOid(d)} has no Reactivate operation`); else commands.push({ from: d, execute: "Reactivate" }); } - if (closed.length) notes.push(`${e.oid}: ${e.op} also closed ${closed.join(", ")}; reopened after it`); + if (closed.length) notes.push(`${e._oid}: ${e.op} also closed ${closed.join(", ")}; reopened after it`); } for (const oid of [...done.created].reverse().map(momentless)) { if (cannot(oid, "Delete")) notes.push(`${oid}: ${typeOfOid(oid)} has no Delete operation, so it is not deleted${typeOfOid(oid) === "Conversation" ? " (the server removes a Conversation once its last Expression is deleted)" : ""}`); @@ -386,7 +386,7 @@ export async function runBatch(transport: Transport, schema: Schema, commands: C for (const d of described.deferred) notes.push(`command ${d.index} (${d.alias}): an aliased ${d.kind}, which preview does not expand; sent as written, not snapshotted, not reversible`); receipt.snapshotAt = now(); receipt.before = await snapshot(transport, described); - const closing = described.executes.filter((e) => CASCADING.has(e.op)).map((e) => e.oid); + const closing = described.executes.filter((e) => CASCADING.has(e.op)).map((e) => e._oid); if (closing.length) receipt.openDescendants = await openDescendantsOf(transport, schema, closing); if (options.dryRun) return { ...receipt, stopped: "dryRun" }; if (options.confirm && !(await options.confirm(receipt))) return { ...receipt, stopped: "declined" }; @@ -513,7 +513,7 @@ export class ReceiptVersionError extends ApiError { export const isReceipt = (value: unknown): value is Receipt => !!value && typeof value === "object" && (value as { receipt?: unknown }).receipt === 2 && typeof (value as Receipt).reverse === "object"; /** An asset a reverse leaves alone because someone changed it since the batch: its Moment then and now (null: gone), and the same as readable times when known. */ -export interface Drifted { oid: Oid; was: string; now: string | null; wasChangedAt: string | null; nowChangedAt: string | null } +export interface Drifted { _oid: Oid; was: string; now: string | null; wasChangedAt: string | null; nowChangedAt: string | null } /** * What `reversible` reads of a receipt: pass the receipt itself. A caller @@ -544,8 +544,8 @@ export async function reversible(transport: Transport, receipt: ReversibleReceip if (!current && !options.force) throw new ReceiptVersionError(receipt.receipt, targets); // An old receipt's stamps are not Moments: with force there is nothing to compare, and nothing is. const now = current ? await versionsOf(transport, targets.filter((oid) => receipt.after[oid] !== undefined)) : {}; - const drifted: Drifted[] = current ? targets.flatMap((oid) => (receipt.after[oid] !== undefined && now[oid]?.moment !== receipt.after[oid] ? [{ oid, was: receipt.after[oid]!, now: now[oid]?.moment ?? null, wasChangedAt: receipt.changedAt?.[oid] ?? null, nowChangedAt: now[oid]?.changedAt ?? null }] : [])) : []; - const skip = new Set(options.force ? [] : drifted.map((d) => d.oid)); + const drifted: Drifted[] = current ? targets.flatMap((oid) => (receipt.after[oid] !== undefined && now[oid]?.moment !== receipt.after[oid] ? [{ _oid: oid, was: receipt.after[oid]!, now: now[oid]?.moment ?? null, wasChangedAt: receipt.changedAt?.[oid] ?? null, nowChangedAt: now[oid]?.changedAt ?? null }] : [])) : []; + const skip = new Set(options.force ? [] : drifted.map((d) => d._oid)); const kept = receipt.reverse.commands.filter((c) => !skip.has(momentless(String(bodyOf(c).from)))); const deletes = kept.flatMap((c) => (bodyOf(c).execute === "Delete" ? [momentless(String(bodyOf(c).from))] : [])); const states = deletes.length ? await statesOf(transport, deletes) : {}; diff --git a/src/services/explain.ts b/src/services/explain.ts index b6425c1..82d8615 100644 --- a/src/services/explain.ts +++ b/src/services/explain.ts @@ -30,8 +30,19 @@ import { parseViolation } from "../types/command"; import * as loc2 from "../wire/loc2"; export interface Explanation { - /** One short sentence for a person. English, with the instance's own labels for attributes and asset types. */ + /** One short sentence. English, with the instance's own labels for attributes and asset types. */ sentence: string; + /** + * Is `sentence` fit to show a person using the consumer's product? True + * when it was made for one: from a rule and the instance's labels, from + * the server's own localized sentence, or from the kind of error + * ("Agility could not be reached…"). False when it is only the message + * as it came — a token the instance has no words for + * (`Violation'AssetCannotInactivateClosed`), the server's raw text, or a + * message written for a developer (a usage error, a protocol error): + * log those, and show the user something of your own. + */ + explained: boolean; /** The failed command's index in the batch, when this explains one; null otherwise. */ index: number | null; /** What was violated: Required, Invalid, Unresolved, Ambiguous, AssetCannotDeleteClosed, …; null when the message is not such a token. */ @@ -64,17 +75,17 @@ const typeTag = (type: string): string => `AssetType'${type}`; /** A token that looks like one loc-2 would know: no spaces, apostrophe-delimited. A plain sentence is not asked about. */ const isTag = (message: string): boolean => /^[A-Za-z]\w*'[^\s]+$/.test(message.trim()); -function sentenceOf(problem: Problem, label: string | null, related: string | null, localized: string | null, message: string): string { +function sentenceOf(problem: Problem, label: string | null, related: string | null, localized: string | null, message: string): { sentence: string; explained: boolean } { if (label) { switch (problem.rule) { - case "Required": return `${label} is required.`; - case "Invalid": return `${label} is not valid.`; - case "Unresolved": return `${label}: no ${related ?? "asset"} matches the value given.`; - case "Ambiguous": return `${label}: more than one ${related ?? "asset"} matches the value given.`; + case "Required": return { sentence: `${label} is required.`, explained: true }; + case "Invalid": return { sentence: `${label} is not valid.`, explained: true }; + case "Unresolved": return { sentence: `${label}: no ${related ?? "asset"} matches the value given.`, explained: true }; + case "Ambiguous": return { sentence: `${label}: more than one ${related ?? "asset"} matches the value given.`, explained: true }; } - return localized ?? `${label}: ${problem.rule ?? message}`; } - return localized ?? message; + // The server's own sentence where it has one; otherwise the message as it came, which explains nothing to a user. + return localized ? { sentence: localized, explained: true } : { sentence: message, explained: false }; } /** The failures to explain, from whatever the caller holds: an Outcome, a list of failures, or a thrown error. */ @@ -84,18 +95,17 @@ function failuresOf(input: unknown): CommandFailureDetail[] | null { return null; } -/** A sentence for an error that is not a list of failed commands, by its kind. */ -function sentenceForError(error: unknown): string { - if (!(error instanceof ApiError)) return error instanceof Error ? error.message : String(error); +/** A sentence for an error that is not a list of failed commands, by its kind, and whether it is one for a user. */ +function sentenceForError(error: unknown): { sentence: string; explained: boolean } { + if (!(error instanceof ApiError)) return { sentence: error instanceof Error ? error.message : String(error), explained: false }; switch (error.kind) { - case "auth": return "Agility did not accept the sign-in: the token is missing, wrong or no longer valid."; - case "forbidden": return "Agility refused: this member is not allowed to do that."; - case "notFound": return `Agility has nothing there: ${error.message}`; - case "transient": return `Agility could not be reached, or is busy (${error.message}). The same request may work in a moment.`; - case "aborted": return "The request was cancelled."; - case "protocol": return `Agility answered something unexpected: ${error.message}`; - // usage, invalid, conflict and the rest: the message is already a sentence (the SDK's own, or the server's). - default: return error.message; + case "auth": return { sentence: "Agility did not accept the sign-in: the token is missing, wrong or no longer valid.", explained: true }; + case "forbidden": return { sentence: "Agility refused: this member is not allowed to do that.", explained: true }; + case "transient": return { sentence: "Agility could not be reached, or is busy. The same request may work in a moment.", explained: true }; + case "aborted": return { sentence: "The request was cancelled.", explained: true }; + case "conflict": return { sentence: "Someone else changed this since it was read; nothing was applied. Look at it again and decide.", explained: true }; + // notFound, invalid, usage, protocol and the rest: the message is the SDK's or the server's own, written for whoever made the call. + default: return { sentence: error.message, explained: false }; } } @@ -108,7 +118,7 @@ function sentenceForError(error: unknown): string { */ export async function explain(transport: Transport, input: unknown, options: loc2.LocalizeOptions = {}): Promise { const failures = failuresOf(input); - if (!failures) return [{ sentence: sentenceForError(input), index: null, rule: null, attribute: null, attributeLabel: null, typeLabel: null, localized: null, message: input instanceof Error ? input.message : String(input) }]; + if (!failures) return [{ ...sentenceForError(input), index: null, rule: null, attribute: null, attributeLabel: null, typeLabel: null, localized: null, message: input instanceof Error ? input.message : String(input) }]; const problems = failures.map((f) => problemOf(f.message)); const tags = new Set(); failures.forEach((f, i) => { @@ -130,6 +140,6 @@ export async function explain(transport: Transport, input: unknown, options: loc const typeLabel = type ? label(typeTag(type)) ?? type : null; const related = p.related ? label(typeTag(p.related)) ?? p.related : null; const localized = isTag(f.message) ? label(f.message.trim()) : null; - return { sentence: sentenceOf(p, attributeLabel, related, localized, f.message), index: f.index, rule: p.rule, attribute: p.attribute, attributeLabel, typeLabel, localized, message: f.message }; + return { ...sentenceOf(p, attributeLabel, related, localized, f.message), index: f.index, rule: p.rule, attribute: p.attribute, attributeLabel, typeLabel, localized, message: f.message }; }); } diff --git a/src/testing/index.ts b/src/testing/index.ts index 6caf5af..39809c2 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -58,7 +58,7 @@ type ListMatch = string | ((type: string, params: Record) => FakeRows) }[]; - metamodel: MetamodelDocument | null; + metamodel: FakeOptions["metamodel"] | null; queries: { match: QueryMatch; answer: QueryAnswer }[]; sends: SendAnswer[]; requests: { match: RequestMatch; answer: RequestAnswer }[]; @@ -253,17 +253,21 @@ function respond(script: Script, request: RequestOptions): unknown { export interface FakeOptions { /** - * A metamodel as meta.v1 delivers it (the document a consumer captures - * from `GET /meta.v1`, or this repository's `metamodel.json`). With it - * the fake's instance has those asset types: it serves `meta.v1/` - * from the document, so answers go through the real translation — a - * response captured from a server, scripted with `onRequest`, reads as - * it would live ("5" becomes 5, a sub-selected single relation one Ref) - * — for the fake and for any client built on `fake.transport`. Rows - * scripted in the model's shape still read as scripted. Without it, the - * instance has no types and nothing is translated. + * Asset types as meta.v1 delivers them, for the fake's instance to have: + * `{ AssetTypes: { Story: , … } }`. + * Only the types the code under test touches are needed — the ones its + * queries read from and select through — and those are small; the whole + * `GET /meta.v1` document (several megabytes) works too, `Version` + * included or not. With it the fake serves `meta.v1/` from these, + * so answers go through the real translation: a response captured from + * a server, scripted with `onRequest`, reads as it would live ("5" + * becomes 5, "False" false, a sub-selected single relation one Ref), + * for the fake and for any client built on `fake.transport`. A type that + * is not among them does not exist on the fake's instance, and its rows + * read as sent. Rows scripted in the model's shape still read as + * scripted. Without this option the instance has no types at all. */ - metamodel?: MetamodelDocument; + metamodel?: { Version?: string; AssetTypes: MetamodelDocument["AssetTypes"] }; } /** A model row as rest-1 would send it: what `onList` answers with, so the client's own translation reads it back. */ diff --git a/src/types/asset.ts b/src/types/asset.ts index f90648a..641062a 100644 --- a/src/types/asset.ts +++ b/src/types/asset.ts @@ -76,22 +76,25 @@ export interface Asset extends CustomAttributes { /** * What an AssetState means for someone deciding what to do with the asset, - * for the four states whose meaning is established against a server: - * "open" Active + * for the five states whose meaning is established against a server: + * "open" Active — and only Active + * "future" Future: not begun yet (a Timebox or a Scope ahead of its + * dates; the server sends the name) * "closed" Closed * "template" code 200, which the server sends as "200" (it has no name * for it; `Template` is this SDK's) * "deleted" Deleted - * and "other" for every other state — Future, Dead (the server's word for - * the whole range from 192 up, not a state rows are seen to carry), + * and "other" for every other state — Dead (the server's word for the + * whole range from 192 up, not a state rows are seen to carry), * OldBrokenDownStory (a story that was split: dead, not deleted), * Deprecated — and for a value it does not know. Null for no value. Takes * a name or a code, as assetStateOf does. */ -export function assetStateKind(value: unknown): "open" | "closed" | "template" | "deleted" | "other" | null { +export function assetStateKind(value: unknown): "open" | "future" | "closed" | "template" | "deleted" | "other" | null { switch (assetStateOf(value)) { case null: return null; case "Active": return "open"; + case "Future": return "future"; case "Closed": return "closed"; case "Template": return "template"; case "Deleted": return "deleted"; diff --git a/test/integration/batch.test.ts b/test/integration/batch.test.ts index 8a83a8a..5eef85b 100644 --- a/test/integration/batch.test.ts +++ b/test/integration/batch.test.ts @@ -69,7 +69,7 @@ describeInstance("batch (live)", () => { const receipt = await client.batch.run([{ from: b, update: { Estimate: 2 } }], { guard: true }); await assetApi.send(t, [{ from: b, update: { Estimate: 3 } }], { throwOnFailure: true }); // someone else const { commands, drifted } = await client.batch.reversible(receipt); - expect(drifted.map((d) => d.oid)).toEqual([b]); + expect(drifted.map((d) => d._oid)).toEqual([b]); expect(commands).toEqual([]); expect((await client.batch.reversible(receipt, { force: true })).commands).toEqual([{ from: b, update: { Estimate: null } }]); }); diff --git a/test/integration/client.test.ts b/test/integration/client.test.ts index 8e48ebc..89e4517 100644 --- a/test/integration/client.test.ts +++ b/test/integration/client.test.ts @@ -136,6 +136,9 @@ describeInstance("client reads (live)", () => { // A template is state 200, which query.v1 sends as "200" and the model names Template. (None on an empty instance: then nothing is asserted.) const [template] = await client.query<{ _oid: string; AssetState: string }>({ from: "Story", select: ["AssetState"], filter: ["AssetState='200'"], page: { size: 1, start: 0 } }); if (template) expect(assetStateKind(template.AssetState)).toBe("template"); + // Future is a state the server names (a Timebox ahead of its dates); it is its own kind, not "open". + const [future] = await client.query<{ _oid: string; AssetState: string }>({ from: "Timebox", select: ["AssetState"], filter: ["AssetState='Future'"], page: { size: 1, start: 0 } }); + if (future) expect([future.AssetState, assetStateKind(future.AssetState)]).toEqual(["Future", "future"]); }); it("the asset page URL answers for a real asset (assetdetail.v1 redirects to the type's detail page)", async () => { diff --git a/test/unit/batch.test.ts b/test/unit/batch.test.ts index 37e3327..aaab356 100644 --- a/test/unit/batch.test.ts +++ b/test/unit/batch.test.ts @@ -63,8 +63,8 @@ group("batch", () => { it("describe reads creates and queries off the request, and updates and executes per asset off the projection", () => { const d = describe(REQUEST, PREVIEW); expect(d.creates).toEqual([{ index: 0, alias: "@t", type: "Task", name: "new task" }]); - expect(d.updates.map((u) => u.oid)).toEqual(["Story:1", "Story:2"]); - expect(d.executes).toEqual([{ oid: "Epic:9", op: "Inactivate", args: {} }]); + expect(d.updates.map((u) => u._oid)).toEqual(["Story:1", "Story:2"]); + expect(d.executes).toEqual([{ _oid: "Epic:9", op: "Inactivate", args: {} }]); }); it("runBatch: preview, name, snapshot, send guarded on the snapshot's Moments, then a receipt — created with alias and number, touched, conflicts, after-stamps, reverse", async () => { @@ -263,8 +263,8 @@ group("batch", () => { const t = server({ preview: [], lookup: (q) => q.with!.$oids!.flatMap((oid) => (now[oid] ? [{ _oid: oid, ...now[oid] }] : [])), send: () => envelope() }); const r = await reversible(t, receipt); expect(r.drifted).toEqual([ - { oid: "Story:1", was: "101", now: "140", wasChangedAt: "2026-11-04T17:00:00.1", nowChangedAt: "2026-11-04T18:00:00.9" }, - { oid: "Task:5", was: "77", now: null, wasChangedAt: null, nowChangedAt: null } + { _oid: "Story:1", was: "101", now: "140", wasChangedAt: "2026-11-04T17:00:00.1", nowChangedAt: "2026-11-04T18:00:00.9" }, + { _oid: "Task:5", was: "77", now: null, wasChangedAt: null, nowChangedAt: null } ]); expect(r.commands).toEqual([{ from: "Epic:9", execute: "Reactivate" }]); expect((await reversible(t, receipt, { force: true })).commands).toHaveLength(3); diff --git a/test/unit/client.test.ts b/test/unit/client.test.ts index bef03d7..95caa2a 100644 --- a/test/unit/client.test.ts +++ b/test/unit/client.test.ts @@ -53,13 +53,14 @@ describe("unmatched, asset state kinds and the fetch a transport calls", () => { expect(unmatchedOf([{ from: "Story:1", execute: "QuickClose" }], { modified: ["Story:1"], operated: [], failures: [] })).toEqual([0]); }); - it("assetStateKind names the four states whose meaning is established against a server, by name or code, and calls everything else other", () => { + it("assetStateKind names the five states whose meaning is established against a server, by name or code, and calls everything else other", () => { expect(["Active", 64, "64"].map(assetStateKind)).toEqual(["open", "open", "open"]); expect(["Closed", 128].map(assetStateKind)).toEqual(["closed", "closed"]); expect(["200", 200, "Template"].map(assetStateKind)).toEqual(["template", "template", "template"]); // the server sends "200"; Template is this SDK's name for it expect(["Deleted", 255].map(assetStateKind)).toEqual(["deleted", "deleted"]); - // Not claimed: Future, Dead (a range, not a state rows carry), a split story (dead, not deleted), Deprecated, the unknown. - expect(["Future", 0, "Dead", 192, "OldBrokenDownStory", 208, "Deprecated", "Whatever"].map(assetStateKind)).toEqual(Array(8).fill("other")); + expect(["Future", 0].map(assetStateKind)).toEqual(["future", "future"]); // not begun: not "open", which is Active alone + // Not claimed: Dead (a range, not a state rows carry), a split story (dead, not deleted), Deprecated, the unknown. + expect(["Dead", 192, "OldBrokenDownStory", 208, "Deprecated", "Whatever"].map(assetStateKind)).toEqual(Array(6).fill("other")); expect([null, undefined].map(assetStateKind)).toEqual([null, null]); }); diff --git a/test/unit/explain.test.ts b/test/unit/explain.test.ts index a7f5fe2..6e62ff5 100644 --- a/test/unit/explain.test.ts +++ b/test/unit/explain.test.ts @@ -42,7 +42,7 @@ describe("explain", () => { "Agility Warning: Attempting to delete a closed item. This change was not saved." ]); expect(explained[0]).toEqual({ - sentence: "Project is required.", index: 0, rule: "Required", attribute: "Story.Scope", attributeLabel: "Project", typeLabel: "Backlog Item", + sentence: "Project is required.", explained: true, index: 0, rule: "Required", attribute: "Story.Scope", attributeLabel: "Project", typeLabel: "Backlog Item", localized: LOC2["Violation'Required'AttributeDefinition'Scope'Story"], message: "Violation'Required'AttributeDefinition'Scope'Story" }); // A Resolution failure names the attribute as a token and then the related type; loc-2 has no label for these here, so their own names stand in. @@ -50,6 +50,10 @@ describe("explain", () => { // A plain sentence is not a tag: nothing is asked about it and nothing is invented. expect(explained[2]).toMatchObject({ rule: null, attribute: null, attributeLabel: null, localized: null }); expect(explained[4]).toMatchObject({ rule: "AssetCannotDeleteClosed", attribute: null }); + // Which sentences are fit to show a user: the ones made for one. The raw server text is not. + expect(explained.map((e) => e.explained)).toEqual([true, true, false, true, true]); + // A rule the instance has no words for (seen live: closing a closed story) stays a token, and says it explains nothing. + expect((await explain(loc2(), [failure(0, "Violation'AssetCannotInactivateClosed")]))[0]).toMatchObject({ sentence: "Violation'AssetCannotInactivateClosed", explained: false, rule: "AssetCannotInactivateClosed", localized: null }); }); it("takes an Outcome, a CommandFailureError or its failures alike; no failures, no request", async () => { @@ -67,12 +71,16 @@ describe("explain", () => { const say = async (e: unknown) => (await explain(t, e))[0]!.sentence; expect(await say(new ApiError("Unauthorized", 401))).toBe("Agility did not accept the sign-in: the token is missing, wrong or no longer valid."); expect(await say(new ApiError("Forbidden", 403))).toBe("Agility refused: this member is not allowed to do that."); - expect(await say(new ApiError("fetch failed", 0, "NETWORK_ERROR"))).toBe("Agility could not be reached, or is busy (fetch failed). The same request may work in a moment."); + expect(await say(new ApiError("fetch failed", 0, "NETWORK_ERROR"))).toBe("Agility could not be reached, or is busy. The same request may work in a moment."); expect(await say(new ApiError("Request aborted", 0, "ABORTED"))).toBe("The request was cancelled."); // The SDK's own sentences and the server's (a rejected query) are said as they are. expect(await say(new UsageError("query of Story without a page: every read must be bounded"))).toBe("query of Story without a page: every read must be bounded"); expect(await say(new ApiError("Invalid WHERE parameter; Invalid QueryFilter2 token Nope=1", 400, "QUERY_REJECTED"))).toBe("Invalid WHERE parameter; Invalid QueryFilter2 token Nope=1"); expect(await say(new Error("boom"))).toBe("boom"); + // A developer's message is passed through and marked as not for a user; a consumer can call explain on anything and show only what is explained. + const fit = async (e: unknown) => (await explain(t, e))[0]!.explained; + expect([await fit(new ApiError("Unauthorized", 401)), await fit(new ApiError("down", 503)), await fit(new ApiError("x", 200, "CONFLICT"))]).toEqual([true, true, true]); + expect([await fit(new UsageError("query of Story without a page")), await fit(new ApiError("Invalid WHERE parameter", 400, "QUERY_REJECTED")), await fit(new ApiError("not JSON", 200, "BAD_JSON")), await fit(new Error("boom"))]).toEqual([false, false, false, false]); expect(t.calls).toHaveLength(0); const down: Transport = { request: async () => { throw new ApiError("down", 503); } }; expect((await explain(down, [failure(0, "Violation'Required'AttributeDefinition'Scope'Story")]))[0]).toMatchObject({ sentence: "Scope is required.", attributeLabel: "Scope", typeLabel: "Story", localized: null }); diff --git a/test/unit/testing.test.ts b/test/unit/testing.test.ts index fae0479..4dd0192 100644 --- a/test/unit/testing.test.ts +++ b/test/unit/testing.test.ts @@ -172,6 +172,10 @@ describe("FakeAgilityClient", () => { expect(await scripted.query({ from: "Story", select: ["Name", "Estimate", "IsClosed", "Status"], page: { size: 1, start: 0 } })).toEqual([{ _oid: "Story:1", Name: "n", Estimate: 3, IsClosed: false, Status: null }]); expect(scripted.requests.map((r) => r.path)).toEqual(["/query.v1"]); expect((await scripted.meta.assetType("Story")).Token).toBe("Story"); + // A subset is enough: only the types the code under test touches, with no Version. A type left out does not exist there. + const { Story, StoryStatus } = metamodel.AssetTypes; + const subset = new FakeAgilityClient({ metamodel: { AssetTypes: { Story: Story!, StoryStatus: StoryStatus! } } }).onRequest("/query.v1", captured); + expect(await subset.query(q)).toEqual(expected); await expect(scripted.meta.assetType("NoSuchType")).rejects.toMatchObject({ kind: "notFound" }); }); @@ -202,7 +206,7 @@ describe("FakeAgilityClient", () => { expect((await fake.batch.reversible(receipt)).drifted).toEqual([]); fake.touch("Story:2"); const undo = await fake.batch.reversible(receipt); - expect(undo.drifted).toMatchObject([{ oid: "Story:2", was: "2", now: "3" }]); + expect(undo.drifted).toMatchObject([{ _oid: "Story:2", was: "2", now: "3" }]); expect(undo.commands).toEqual([{ from: "Story:1", update: { Estimate: 3 } }, { from: "Task:1000", execute: "Delete" }]); // A conflict at send time is on the receipt, and a dry run sends nothing. fake.onQuery("Epic", [{ _oid: "Epic:9", Name: "Nine" }]); From b1942bf5da3d7c31ee4c14976f5b04d1cf1bdd42 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:57:18 +0000 Subject: [PATCH 13/17] alpha.8: an opt-in resend of a refused write, explanations that say who they are for, and the fake matching the server - onUnauthorized may answer "retry-write": after re-authenticating, the refused request is sent once more even when it is a plain write. The default is unchanged (a write is never resent; "retry" resends idempotent requests only). The hook asserts that on its server such a refusal means nothing was executed; the SDK cannot verify that, since its tests run where every request is authenticated, and says so in the type's doc, the spec and the changelog. Tested: resent once on retry-write, not on retry, not for a status outside unauthorizedStatuses, never twice, and never with reauthorize: false. - Explanation: `audience` ("user" or "developer") and `echoed` replace the flag added in the previous commit; a rule the instance has no words for gets a sentence, never its bare token; a Resolution failure's related type is answered with its label. - described.updates / executes and drifted entries keep `oid`, as before the previous commit: they mention an asset and are not rows. Spec 000 and the README say why rows carry `_oid` (the server's key, underscored so it cannot collide with an attribute) and where plain `oid` appears. - The fake: what a scripted Ref carries stays on it in a rest-1 list, as rest-1's display columns do live; a preview projects a scalar update and an operation in the server's form. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 30 ++++++++++----- README.md | 2 + specs/000-layers.md | 14 ++++++- src/core/fetchTransport.ts | 33 ++++++++++++---- src/services/batch.ts | 48 +++++++++++------------ src/services/explain.ts | 70 ++++++++++++++++++++-------------- src/testing/index.ts | 18 +++++++-- test/integration/batch.test.ts | 2 +- test/unit/batch.test.ts | 8 ++-- test/unit/explain.test.ts | 27 ++++++++----- test/unit/retry.test.ts | 23 +++++++++++ test/unit/testing.test.ts | 8 +++- 12 files changed, 195 insertions(+), 88 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c686cc4..8529fae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -78,9 +78,7 @@ Each entry has the line a consumer follows to migrate. defaulted to true). Migration: `client.batch.run(commands)` → `client.batch.run(commands, { guard: true })`. - **Receipts are `receipt: 2`**: `skipped` → `conflicts`; new `stamps`, - `changedAt` and `stopped`; `described.updates[i]`, - `described.executes[i]` and `batch.reversible`'s `drifted[i]` name - their asset as `_oid` (was `oid`); and the assets a receipt names are rows, + `changedAt` and `stopped`; and the assets a receipt names are rows, like every other asset the SDK answers: in `created` and `touched`, `oid` → `_oid`, `type` → `AssetType`, `number` → `Number`, `name` → `Name` (`touched` gains `AssetType`); in `names[oid]`, `number` → @@ -169,6 +167,15 @@ Each entry has the line a consumer follows to migrate. that finally failed, after any resend, with any Transport. It observes: the error is still thrown. For an app-wide toast or a log line, without a wrapper Transport. +- **`onUnauthorized` may answer `"retry-write"`**: after + re-authenticating, send the refused request once more even when it is + a plain write. Opt-in, and the default is unchanged: a write is never + resent, and `"retry"` still resends idempotent requests only. By + answering it the hook asserts that on its server a refusal with one of + `unauthorizedStatuses` (an expired session) means nothing in the + request was executed. **The SDK does not and cannot check that**: its + tests run where every request is authenticated, so this premise is the + consumer's to hold, for its own server. Honoured once per request. - **`RequestOptions.reauthorize: false`**: a refusal of that request is answered straight away, without calling the transport's `onUnauthorized` hook. For the request a hook itself sends to ask @@ -182,11 +189,14 @@ Each entry has the line a consumer follows to migrate. the attribute and the asset type, the parts it was made from (`rule`, `attribute`, `attributeLabel`, `typeLabel`), and the server's own `localized` sentence where it has one. `Resolution'…` failures are read - too. `explained` says whether the sentence is fit to show a user: false - when it is only the message as it came (a token the instance has no - words for, raw server text, a message for a developer), so a caller - can explain any error and show only what is explained. One loc-2 request at most. Migration: a consumer's own failure - patterns and three-tag loc-2 lookups can go. + too, with the related type they name (`relatedType`, + `relatedTypeLabel`). `audience` says who the sentence is for — + `"user"` when it was made for a person and can be shown, `"developer"` + when it is about the call itself or is the server's raw text — and + `echoed` is true when nothing was explained, so a caller can explain + any error and show only what is for a user. A rule the instance has no + words for is never answered as its bare token. Migration: a consumer's + own failure patterns and three-tag loc-2 lookups can go. - **`transportConformance(make)`** from `@versionone/agility-sdk/testing`: the SDK's expectations of a `Transport` as a list of named checks, runnable against a custom transport with any test runner (path inside @@ -212,7 +222,9 @@ Each entry has the line a consumer follows to migrate. work on the fake for assets addressed by OID that a row was scripted for: it keeps a moment per asset, `fake.touch(oid)` is someone else changing it (a conflict for a write stamped earlier, drift for a - receipt's reverse) and `fake.remove(oid)` is it being deleted. (a + receipt's reverse) and `fake.remove(oid)` is it being deleted. Its + preview projects a scalar update as the server does (`{ add, remove + }`), and what a scripted Ref carries stays on it in a rest-1 list. (a chat-bot consumer and a CLI consumer, whose tests replay captured responses and fake a batch by hand.) - **`client.resolve.refs(specs)`**: numbers and OID tokens mixed, each diff --git a/README.md b/README.md index f071ac5..529fef4 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,8 @@ npm test Every row follows one rule, whichever call read it: **a relation you select is a Ref (`{ _oid }`); a path you select by name is at `row[path]` (`row["Status.Name"]`); nothing arrives that you did not select.** Select both `Owners` and `Owners.Name` and you get the Refs and, beside them, a parallel array at `"Owners.Name"`. To get attributes on the related rows themselves, use a sub-select: `{ from: "Owners", select: ["Name"] }` gives `row.Owners[i].Name`. (rest-1 also puts the display attributes it sends unasked on the Refs of a relation you selected.) +A row's identity is `_oid`: it is the key the server sends, underscored so it cannot collide with an attribute (the identity attribute is `ID`). Rows, Refs, resolved assets, attachments and the assets on a receipt all carry it; a record that only mentions an asset (a receipt's `described` entries, a `drifted` entry) says `oid`. + Rows are typed from what you select, against the product's metamodel: a selected key is its value or `null`, never `undefined`. For an attribute your instance has and the generated model does not (a custom field's relation, a product module's attribute), name your own row type at the call: `client.query(q)` needs only `_oid` on `MyRow`. ### Reference diff --git a/specs/000-layers.md b/specs/000-layers.md index a843f33..0cd03b8 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -48,6 +48,13 @@ pulled through) in a create, in an update, and in a query result alike. in `Attributes` and rendering `AssetState` as a number — is translated in that endpoint's wire module, once, on the way in and on the way out. +A row's identity is `_oid`: the key the server sends for it, underscored +so that it can never collide with an attribute (an asset's own identity +attribute is `ID`). Every row has it, and so does anything that is a row +or stands for one (a Ref, a resolved asset, an attachment, the assets on +a receipt). A record that is not a row but mentions an asset — a +described update, a drifted entry — says plain `oid`. + One rule for a row, on every read path (query.v1, api/asset, rest-1): **a relation you select is a Ref; a path you select by name is at `row[path]`; nothing arrives that you did not select.** A sub-select is @@ -211,7 +218,12 @@ Re-authentication follows the same rule. On a 401 (or a status the caller lists) the transport calls `onUnauthorized` once per request; "retry" resends an idempotent request one more time, outside the `retries` count. A plain write is never resent: the hook still runs, so the session can be repaired, -and the caller decides. A request sent with `reauthorize: false` skips +and the caller decides. There is one way round that, and it is the +consumer's assertion, not the SDK's: a hook that answers "retry-write" +has the refused request sent once more, a plain write included, on its +own word that on its server such a refusal means nothing in the request +was executed. The SDK cannot verify that premise (its tests run where +every request is authenticated) and never assumes it. A request sent with `reauthorize: false` skips the hook: it is how a hook asks whether the session is alive without waiting on itself. A caller's abort (`signal`) ends the request as `ABORTED` and is never retried. diff --git a/src/core/fetchTransport.ts b/src/core/fetchTransport.ts index 317d7dd..168b461 100644 --- a/src/core/fetchTransport.ts +++ b/src/core/fetchTransport.ts @@ -51,22 +51,41 @@ export interface FetchTransportConfig { * the place to re-authenticate — open a login popup, re-run setup. Resolve * "retry" to send the request once more, "fail" to throw the error. * - * A retry is offered only for an idempotent request (every GET; a write the - * caller marked idempotent). A plain api/asset write is never resent - * automatically, even after a 401: the hook still runs, so the session - * can be repaired, and the caller decides whether to send again. + * "retry" is honoured only for an idempotent request (every GET; a write + * the caller marked idempotent). A plain api/asset write is never resent + * on it, even after a 401: the hook still runs, so the session can be + * repaired, and the caller decides whether to send again. "retry-write" + * resends a plain write too, once, on the hook's own assertion that the + * refusal means nothing ran (see UnauthorizedDecision). */ onUnauthorized?: (context: UnauthorizedContext) => UnauthorizedDecision | Promise; /** Which statuses call onUnauthorized. Default [401]; a cookie-session app may add 403. */ unauthorizedStatuses?: readonly number[]; } -export type UnauthorizedDecision = "retry" | "fail"; +/** + * What the hook decides after re-authenticating: + * "fail" throw the refusal. + * "retry" send the request once more if it is idempotent; a plain + * write is not resent and its refusal is thrown. + * "retry-write" send the request once more whatever it is, a plain + * write included. By answering this the hook ASSERTS that + * on its server a refusal with one of + * `unauthorizedStatuses` means nothing in the request was + * executed — the sign-in was checked before any command + * ran — so sending it again cannot apply anything twice. + * The SDK cannot know that and does not check it: its own + * tests run where every request is authenticated. Answer + * it only where that holds (a session that expired; not a + * permission problem, which api/asset reports per command + * inside a 200). Honoured once per request, like "retry". + */ +export type UnauthorizedDecision = "retry" | "retry-write" | "fail"; export interface UnauthorizedContext { error: ApiError; request: RequestOptions; - /** Whether a "retry" will be honoured: false for a non-idempotent write. */ + /** Whether a "retry" will be honoured: false for a non-idempotent write (which only "retry-write" resends). */ retryable: boolean; } @@ -220,7 +239,7 @@ export function createFetchTransport(config: FetchTransportConfig): Transport { reauthorized = true; const decision = await config.onUnauthorized({ error: lastError as ApiError, request: options, retryable: idempotent }); if (callerSignal?.aborted) throw abortedError(callerSignal); - if (decision === "retry" && idempotent) { + if ((decision === "retry" && idempotent) || decision === "retry-write") { // Not counted against `retries`: those are for failures to get an answer. attempt -= 1; continue; diff --git a/src/services/batch.ts b/src/services/batch.ts index 8ca4eed..dc6ea0b 100644 --- a/src/services/batch.ts +++ b/src/services/batch.ts @@ -41,8 +41,8 @@ export const CHUNK = 100; export interface Described { creates: { index: number; alias: string | null; type: string; name: string | null }[]; queries: { index: number; from: string }[]; - updates: { _oid: Oid; attributes: Record }[]; - executes: { _oid: Oid; op: string; args: Record }[]; + updates: { oid: Oid; attributes: Record }[]; + executes: { oid: Oid; op: string; args: Record }[]; /** * Aliased updates and executes: preview does not expand them, so they * have no per-asset entry above, no snapshot and no reverse. They are @@ -66,10 +66,10 @@ export function describe(commands: Command[], projected: Command[]): Described { const body = bodyOf(p); if (typeof body.oid !== "string") continue; const oid = momentless(body.oid); - if (body.update && typeof body.update === "object") out.updates.push({ _oid: oid, attributes: body.update as Record }); + if (body.update && typeof body.update === "object") out.updates.push({ oid, attributes: body.update as Record }); else if (body.execute !== undefined) { const e = body.execute as string | { op: string; args?: Record }; - out.executes.push({ _oid: oid, op: typeof e === "string" ? e : e.op, args: typeof e === "string" ? {} : e.args ?? {} }); + out.executes.push({ oid, op: typeof e === "string" ? e : e.op, args: typeof e === "string" ? {} : e.args ?? {} }); } } return out; @@ -131,8 +131,8 @@ export async function namesOf(transport: Transport, schema: Schema, oids: Iterab export async function snapshot(transport: Transport, described: Described): Promise>> { const wanted = new Map>(); const want = (oid: Oid, attrs: string[]) => { const s = wanted.get(oid) ?? new Set(); attrs.forEach((a) => s.add(a)); wanted.set(oid, s); }; - for (const u of described.updates) want(u._oid, [...Object.keys(u.attributes), "Moment", "ChangeDate"]); - for (const e of described.executes) want(e._oid, ["AssetState", "Moment", "ChangeDate"]); + for (const u of described.updates) want(u.oid, [...Object.keys(u.attributes), "Moment", "ChangeDate"]); + for (const e of described.executes) want(e.oid, ["AssetState", "Moment", "ChangeDate"]); const before: Record> = {}; for (const [type, oids] of byType(wanted.keys())) { const select = [...new Set(oids.flatMap((o) => [...wanted.get(o)!]))]; @@ -225,9 +225,9 @@ export function reverseOf(described: Described, before: Record context.canOperate?.(typeOfOid(oid), op) === false; const modified = new Set(done.modified.map(momentless)), operated = new Set(done.operated.map(momentless)); for (const u of described.updates) { - if (!modified.has(u._oid)) continue; - const was = before[u._oid]; - if (!was) { notes.push(`${u._oid}: no snapshot, cannot restore`); continue; } + if (!modified.has(u.oid)) continue; + const was = before[u.oid]; + if (!was) { notes.push(`${u.oid}: no snapshot, cannot restore`); continue; } const update: Record = {}; for (const [attr, change] of Object.entries(u.attributes)) { const prior = was[attr]; @@ -236,29 +236,29 @@ export function reverseOf(described: Described, before: Record !prior.includes(v)), removed = remove.filter((v) => prior.includes(v)); if (added.length || removed.length) update[attr] = { add: removed, remove: added }; - } else if (prior === undefined) notes.push(`${u._oid}.${attr}: not in snapshot, cannot restore`); + } else if (prior === undefined) notes.push(`${u.oid}.${attr}: not in snapshot, cannot restore`); else update[attr] = prior as CommandValue; // a scalar or single relation: put the old value back (null clears) } - if (Object.keys(update).length) commands.push({ from: u._oid, update }); + if (Object.keys(update).length) commands.push({ from: u.oid, update }); } for (const e of described.executes) { - if (!operated.has(e._oid)) continue; + if (!operated.has(e.oid)) continue; const inverse = INVERSE[e.op]; - if (!inverse) { notes.push(`${e._oid}: ${e.op} has no known inverse (was ${String(before[e._oid]?.AssetState ?? "?")})`); continue; } - if (cannot(e._oid, inverse)) { notes.push(`${e._oid}: ${typeOfOid(e._oid)} has no ${inverse} operation, so its ${e.op} is not reversed`); continue; } - commands.push({ from: e._oid, execute: inverse }); + if (!inverse) { notes.push(`${e.oid}: ${e.op} has no known inverse (was ${String(before[e.oid]?.AssetState ?? "?")})`); continue; } + if (cannot(e.oid, inverse)) { notes.push(`${e.oid}: ${typeOfOid(e.oid)} has no ${inverse} operation, so its ${e.op} is not reversed`); continue; } + commands.push({ from: e.oid, execute: inverse }); if (!CASCADING.has(e.op)) continue; - const open = context.openDescendants?.[e._oid] ?? []; - const closed = context.cascaded ? context.cascaded[e._oid] ?? [] : undefined; + const open = context.openDescendants?.[e.oid] ?? []; + const closed = context.cascaded ? context.cascaded[e.oid] ?? [] : undefined; if (closed === undefined) { - if (open.length) notes.push(`${e._oid}: ${e.op} may also have closed ${open.length} open descendant${open.length === 1 ? "" : "s"} (${open.join(", ")}); they could not be read back, so they are not reopened`); + if (open.length) notes.push(`${e.oid}: ${e.op} may also have closed ${open.length} open descendant${open.length === 1 ? "" : "s"} (${open.join(", ")}); they could not be read back, so they are not reopened`); continue; } for (const d of closed) { - if (cannot(d, "Reactivate")) notes.push(`${d}: closed with ${e._oid}, but ${typeOfOid(d)} has no Reactivate operation`); + if (cannot(d, "Reactivate")) notes.push(`${d}: closed with ${e.oid}, but ${typeOfOid(d)} has no Reactivate operation`); else commands.push({ from: d, execute: "Reactivate" }); } - if (closed.length) notes.push(`${e._oid}: ${e.op} also closed ${closed.join(", ")}; reopened after it`); + if (closed.length) notes.push(`${e.oid}: ${e.op} also closed ${closed.join(", ")}; reopened after it`); } for (const oid of [...done.created].reverse().map(momentless)) { if (cannot(oid, "Delete")) notes.push(`${oid}: ${typeOfOid(oid)} has no Delete operation, so it is not deleted${typeOfOid(oid) === "Conversation" ? " (the server removes a Conversation once its last Expression is deleted)" : ""}`); @@ -386,7 +386,7 @@ export async function runBatch(transport: Transport, schema: Schema, commands: C for (const d of described.deferred) notes.push(`command ${d.index} (${d.alias}): an aliased ${d.kind}, which preview does not expand; sent as written, not snapshotted, not reversible`); receipt.snapshotAt = now(); receipt.before = await snapshot(transport, described); - const closing = described.executes.filter((e) => CASCADING.has(e.op)).map((e) => e._oid); + const closing = described.executes.filter((e) => CASCADING.has(e.op)).map((e) => e.oid); if (closing.length) receipt.openDescendants = await openDescendantsOf(transport, schema, closing); if (options.dryRun) return { ...receipt, stopped: "dryRun" }; if (options.confirm && !(await options.confirm(receipt))) return { ...receipt, stopped: "declined" }; @@ -513,7 +513,7 @@ export class ReceiptVersionError extends ApiError { export const isReceipt = (value: unknown): value is Receipt => !!value && typeof value === "object" && (value as { receipt?: unknown }).receipt === 2 && typeof (value as Receipt).reverse === "object"; /** An asset a reverse leaves alone because someone changed it since the batch: its Moment then and now (null: gone), and the same as readable times when known. */ -export interface Drifted { _oid: Oid; was: string; now: string | null; wasChangedAt: string | null; nowChangedAt: string | null } +export interface Drifted { oid: Oid; was: string; now: string | null; wasChangedAt: string | null; nowChangedAt: string | null } /** * What `reversible` reads of a receipt: pass the receipt itself. A caller @@ -544,8 +544,8 @@ export async function reversible(transport: Transport, receipt: ReversibleReceip if (!current && !options.force) throw new ReceiptVersionError(receipt.receipt, targets); // An old receipt's stamps are not Moments: with force there is nothing to compare, and nothing is. const now = current ? await versionsOf(transport, targets.filter((oid) => receipt.after[oid] !== undefined)) : {}; - const drifted: Drifted[] = current ? targets.flatMap((oid) => (receipt.after[oid] !== undefined && now[oid]?.moment !== receipt.after[oid] ? [{ _oid: oid, was: receipt.after[oid]!, now: now[oid]?.moment ?? null, wasChangedAt: receipt.changedAt?.[oid] ?? null, nowChangedAt: now[oid]?.changedAt ?? null }] : [])) : []; - const skip = new Set(options.force ? [] : drifted.map((d) => d._oid)); + const drifted: Drifted[] = current ? targets.flatMap((oid) => (receipt.after[oid] !== undefined && now[oid]?.moment !== receipt.after[oid] ? [{ oid, was: receipt.after[oid]!, now: now[oid]?.moment ?? null, wasChangedAt: receipt.changedAt?.[oid] ?? null, nowChangedAt: now[oid]?.changedAt ?? null }] : [])) : []; + const skip = new Set(options.force ? [] : drifted.map((d) => d.oid)); const kept = receipt.reverse.commands.filter((c) => !skip.has(momentless(String(bodyOf(c).from)))); const deletes = kept.flatMap((c) => (bodyOf(c).execute === "Delete" ? [momentless(String(bodyOf(c).from))] : [])); const states = deletes.length ? await statesOf(transport, deletes) : {}; diff --git a/src/services/explain.ts b/src/services/explain.ts index 82d8615..ec78cb1 100644 --- a/src/services/explain.ts +++ b/src/services/explain.ts @@ -33,16 +33,16 @@ export interface Explanation { /** One short sentence. English, with the instance's own labels for attributes and asset types. */ sentence: string; /** - * Is `sentence` fit to show a person using the consumer's product? True - * when it was made for one: from a rule and the instance's labels, from - * the server's own localized sentence, or from the kind of error - * ("Agility could not be reached…"). False when it is only the message - * as it came — a token the instance has no words for - * (`Violation'AssetCannotInactivateClosed`), the server's raw text, or a - * message written for a developer (a usage error, a protocol error): - * log those, and show the user something of your own. + * Who the sentence is for. "user": it was made for a person using the + * consumer's product — from a rule and the instance's labels, from the + * server's own localized sentence, or from the kind of error — and can + * be shown as it is. "developer": it is a message about the call itself + * (a usage error, a rejected query, a protocol error) or the server's + * raw text; log it, and show the user something of your own. */ - explained: boolean; + audience: "user" | "developer"; + /** True when `sentence` is nothing more than the message as the server (or the SDK) sent it: nothing was explained. */ + echoed: boolean; /** The failed command's index in the batch, when this explains one; null otherwise. */ index: number | null; /** What was violated: Required, Invalid, Unresolved, Ambiguous, AssetCannotDeleteClosed, …; null when the message is not such a token. */ @@ -53,6 +53,10 @@ export interface Explanation { attributeLabel: string | null; /** The asset type as the instance labels it ("Backlog Item"); its token when the instance has no label. */ typeLabel: string | null; + /** The related asset type a Resolution failure names ("Member": the value given matched none, or several, of these); null otherwise. */ + relatedType: string | null; + /** That type as the instance labels it; its token when the instance has no label. */ + relatedTypeLabel: string | null; /** The server's own sentence for the whole message, when loc-2 has one; null when it only echoes the token. */ localized: string | null; /** The message as the server sent it. */ @@ -75,18 +79,28 @@ const typeTag = (type: string): string => `AssetType'${type}`; /** A token that looks like one loc-2 would know: no spaces, apostrophe-delimited. A plain sentence is not asked about. */ const isTag = (message: string): boolean => /^[A-Za-z]\w*'[^\s]+$/.test(message.trim()); -function sentenceOf(problem: Problem, label: string | null, related: string | null, localized: string | null, message: string): { sentence: string; explained: boolean } { +type Said = Pick; +const forUser = (sentence: string): Said => ({ sentence, audience: "user", echoed: false }); + +function sentenceOf(problem: Problem, label: string | null, related: string | null, localized: string | null, message: string): Said { if (label) { switch (problem.rule) { - case "Required": return { sentence: `${label} is required.`, explained: true }; - case "Invalid": return { sentence: `${label} is not valid.`, explained: true }; - case "Unresolved": return { sentence: `${label}: no ${related ?? "asset"} matches the value given.`, explained: true }; - case "Ambiguous": return { sentence: `${label}: more than one ${related ?? "asset"} matches the value given.`, explained: true }; + case "Required": return forUser(`${label} is required.`); + case "Invalid": return forUser(`${label} is not valid.`); + case "Unresolved": return forUser(`${label}: no ${related ?? "asset"} matches the value given.`); + case "Ambiguous": return forUser(`${label}: more than one ${related ?? "asset"} matches the value given.`); } } - // The server's own sentence where it has one; otherwise the message as it came, which explains nothing to a user. - return localized ? { sentence: localized, explained: true } : { sentence: message, explained: false }; + // The server's own sentence where it has one. + if (localized) return forUser(localized); + // A rule the instance has no words for (seen live: Violation'AssetCannotInactivateClosed): never the bare token. + // What it means is in the rule's name, which a person can read; the token stays in `message` and `rule`. + if (problem.rule) return forUser(`Agility did not accept this change${label ? ` to ${label}` : ""} (${words(problem.rule)}).`); + // Anything else is the server's own text, as it came. + return { sentence: message, audience: "developer", echoed: true }; } +/** A rule's name as words: AssetCannotInactivateClosed → "asset cannot inactivate closed". */ +const words = (rule: string): string => rule.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase(); /** The failures to explain, from whatever the caller holds: an Outcome, a list of failures, or a thrown error. */ function failuresOf(input: unknown): CommandFailureDetail[] | null { @@ -95,17 +109,17 @@ function failuresOf(input: unknown): CommandFailureDetail[] | null { return null; } -/** A sentence for an error that is not a list of failed commands, by its kind, and whether it is one for a user. */ -function sentenceForError(error: unknown): { sentence: string; explained: boolean } { - if (!(error instanceof ApiError)) return { sentence: error instanceof Error ? error.message : String(error), explained: false }; +/** A sentence for an error that is not a list of failed commands, by its kind, and who it is for. */ +function sentenceForError(error: unknown): Said { + if (!(error instanceof ApiError)) return { sentence: error instanceof Error ? error.message : String(error), audience: "developer", echoed: true }; switch (error.kind) { - case "auth": return { sentence: "Agility did not accept the sign-in: the token is missing, wrong or no longer valid.", explained: true }; - case "forbidden": return { sentence: "Agility refused: this member is not allowed to do that.", explained: true }; - case "transient": return { sentence: "Agility could not be reached, or is busy. The same request may work in a moment.", explained: true }; - case "aborted": return { sentence: "The request was cancelled.", explained: true }; - case "conflict": return { sentence: "Someone else changed this since it was read; nothing was applied. Look at it again and decide.", explained: true }; - // notFound, invalid, usage, protocol and the rest: the message is the SDK's or the server's own, written for whoever made the call. - default: return { sentence: error.message, explained: false }; + case "auth": return forUser("Agility did not accept the sign-in: the token is missing, wrong or no longer valid."); + case "forbidden": return forUser("Agility refused: this member is not allowed to do that."); + case "transient": return forUser("Agility could not be reached, or is busy. The same request may work in a moment."); + case "aborted": return forUser("The request was cancelled."); + case "conflict": return forUser("Someone else changed this since it was read; nothing was applied. Look at it again and decide."); + // notFound, invalid, usage, protocol and the rest: the message is the SDK's or the server's own, about the call. + default: return { sentence: error.message, audience: "developer", echoed: true }; } } @@ -118,7 +132,7 @@ function sentenceForError(error: unknown): { sentence: string; explained: boolea */ export async function explain(transport: Transport, input: unknown, options: loc2.LocalizeOptions = {}): Promise { const failures = failuresOf(input); - if (!failures) return [{ ...sentenceForError(input), index: null, rule: null, attribute: null, attributeLabel: null, typeLabel: null, localized: null, message: input instanceof Error ? input.message : String(input) }]; + if (!failures) return [{ ...sentenceForError(input), index: null, rule: null, attribute: null, attributeLabel: null, typeLabel: null, relatedType: null, relatedTypeLabel: null, localized: null, message: input instanceof Error ? input.message : String(input) }]; const problems = failures.map((f) => problemOf(f.message)); const tags = new Set(); failures.forEach((f, i) => { @@ -140,6 +154,6 @@ export async function explain(transport: Transport, input: unknown, options: loc const typeLabel = type ? label(typeTag(type)) ?? type : null; const related = p.related ? label(typeTag(p.related)) ?? p.related : null; const localized = isTag(f.message) ? label(f.message.trim()) : null; - return { ...sentenceOf(p, attributeLabel, related, localized, f.message), index: f.index, rule: p.rule, attribute: p.attribute, attributeLabel, typeLabel, localized, message: f.message }; + return { ...sentenceOf(p, attributeLabel, related, localized, f.message), index: f.index, rule: p.rule, attribute: p.attribute, attributeLabel, typeLabel, relatedType: p.related, relatedTypeLabel: related, localized, message: f.message }; }); } diff --git a/src/testing/index.ts b/src/testing/index.ts index 39809c2..4752adc 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -219,7 +219,11 @@ function respond(script: Script, request: RequestOptions): unknown { const aliased = body !== (c as unknown); if (aliased || !("update" in body || "execute" in body)) return c; if (typeof body.from !== "string" || !isOidToken(body.from)) throw new UsageError(`FakeAgilityClient cannot preview command ${i}: it is scoped by a query (from ${String(body.from)}), and the fake evaluates no filter. Address the assets by OID, or script the preview with fake.onRequest((r) => r.query?.previewOnly === "true", projection)`); - return { [`@fake-${i}`]: { oid: momentless(body.from), ...("update" in body ? { update: body.update } : { execute: body.execute }) } } as unknown as Command; + // As the server projects them: a scalar becomes { add: ["value"], remove: [] }, an operation { op, args }. + const scalar = (v: unknown) => (v === null || typeof v !== "object" ? { add: v === null ? [] : [String(v)], remove: [] } : v); + const update = "update" in body ? Object.fromEntries(Object.entries(body.update as Record).map(([k, v]) => [k, scalar(v)])) : undefined; + const execute = typeof body.execute === "string" ? { op: body.execute, args: {} } : body.execute; + return { [`@fake-${i}`]: { oid: momentless(body.from), ...(update ? { update } : { execute }) } } as unknown as Command; }); 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)); @@ -275,10 +279,18 @@ function toAssetDocument(row: FakeRow): Record { const isRef = (v: unknown): v is { _oid: string } => !!v && typeof v === "object" && typeof (v as { _oid?: unknown })._oid === "string"; const ref = (r: { _oid: string }) => ({ _type: "Asset", href: "", idref: r._oid }); const Attributes: Record = {}; + // What a scripted Ref carries beyond its OID goes out as rest-1 sends a relation's display columns (`Owners.Name`, a + // parallel array for a multi-value relation), so the client folds it back onto the Ref, as it does live. + const columns = (name: string, refs: Record[], many: boolean) => { + for (const key of new Set(refs.flatMap((r) => Object.keys(r).filter((k) => k !== "_oid")))) { + const path = `${name}.${key}`; + if (!(path in row)) Attributes[path] = { _type: "Attribute", name: path, value: many ? refs.map((r) => r[key] ?? null) : refs[0]![key] ?? null }; + } + }; for (const [name, value] of Object.entries(row)) { if (name === "_oid") continue; - if (isRef(value)) Attributes[name] = { _type: "Relation", name, value: ref(value) }; - else if (Array.isArray(value) && value.length && value.every(isRef)) Attributes[name] = { _type: "Relation", name, value: value.map(ref) }; + if (isRef(value)) { Attributes[name] = { _type: "Relation", name, value: ref(value) }; columns(name, [value as Record], false); } + else if (Array.isArray(value) && value.length && value.every(isRef)) { Attributes[name] = { _type: "Relation", name, value: value.map(ref) }; columns(name, value as Record[], true); } else Attributes[name] = { _type: "Attribute", name, value }; } return { _type: "Asset", href: "", id: row._oid, Attributes }; diff --git a/test/integration/batch.test.ts b/test/integration/batch.test.ts index 5eef85b..8a83a8a 100644 --- a/test/integration/batch.test.ts +++ b/test/integration/batch.test.ts @@ -69,7 +69,7 @@ describeInstance("batch (live)", () => { const receipt = await client.batch.run([{ from: b, update: { Estimate: 2 } }], { guard: true }); await assetApi.send(t, [{ from: b, update: { Estimate: 3 } }], { throwOnFailure: true }); // someone else const { commands, drifted } = await client.batch.reversible(receipt); - expect(drifted.map((d) => d._oid)).toEqual([b]); + expect(drifted.map((d) => d.oid)).toEqual([b]); expect(commands).toEqual([]); expect((await client.batch.reversible(receipt, { force: true })).commands).toEqual([{ from: b, update: { Estimate: null } }]); }); diff --git a/test/unit/batch.test.ts b/test/unit/batch.test.ts index aaab356..37e3327 100644 --- a/test/unit/batch.test.ts +++ b/test/unit/batch.test.ts @@ -63,8 +63,8 @@ group("batch", () => { it("describe reads creates and queries off the request, and updates and executes per asset off the projection", () => { const d = describe(REQUEST, PREVIEW); expect(d.creates).toEqual([{ index: 0, alias: "@t", type: "Task", name: "new task" }]); - expect(d.updates.map((u) => u._oid)).toEqual(["Story:1", "Story:2"]); - expect(d.executes).toEqual([{ _oid: "Epic:9", op: "Inactivate", args: {} }]); + expect(d.updates.map((u) => u.oid)).toEqual(["Story:1", "Story:2"]); + expect(d.executes).toEqual([{ oid: "Epic:9", op: "Inactivate", args: {} }]); }); it("runBatch: preview, name, snapshot, send guarded on the snapshot's Moments, then a receipt — created with alias and number, touched, conflicts, after-stamps, reverse", async () => { @@ -263,8 +263,8 @@ group("batch", () => { const t = server({ preview: [], lookup: (q) => q.with!.$oids!.flatMap((oid) => (now[oid] ? [{ _oid: oid, ...now[oid] }] : [])), send: () => envelope() }); const r = await reversible(t, receipt); expect(r.drifted).toEqual([ - { _oid: "Story:1", was: "101", now: "140", wasChangedAt: "2026-11-04T17:00:00.1", nowChangedAt: "2026-11-04T18:00:00.9" }, - { _oid: "Task:5", was: "77", now: null, wasChangedAt: null, nowChangedAt: null } + { oid: "Story:1", was: "101", now: "140", wasChangedAt: "2026-11-04T17:00:00.1", nowChangedAt: "2026-11-04T18:00:00.9" }, + { oid: "Task:5", was: "77", now: null, wasChangedAt: null, nowChangedAt: null } ]); expect(r.commands).toEqual([{ from: "Epic:9", execute: "Reactivate" }]); expect((await reversible(t, receipt, { force: true })).commands).toHaveLength(3); diff --git a/test/unit/explain.test.ts b/test/unit/explain.test.ts index 6e62ff5..307c6f1 100644 --- a/test/unit/explain.test.ts +++ b/test/unit/explain.test.ts @@ -42,18 +42,25 @@ describe("explain", () => { "Agility Warning: Attempting to delete a closed item. This change was not saved." ]); expect(explained[0]).toEqual({ - sentence: "Project is required.", explained: true, index: 0, rule: "Required", attribute: "Story.Scope", attributeLabel: "Project", typeLabel: "Backlog Item", + sentence: "Project is required.", audience: "user", echoed: false, index: 0, rule: "Required", attribute: "Story.Scope", attributeLabel: "Project", typeLabel: "Backlog Item", relatedType: null, relatedTypeLabel: null, localized: LOC2["Violation'Required'AttributeDefinition'Scope'Story"], message: "Violation'Required'AttributeDefinition'Scope'Story" }); // A Resolution failure names the attribute as a token and then the related type; loc-2 has no label for these here, so their own names stand in. - expect(explained[1]).toMatchObject({ rule: "Unresolved", attribute: "Story.Status", attributeLabel: "Status", typeLabel: "Backlog Item", localized: null }); + expect(explained[1]).toMatchObject({ rule: "Unresolved", attribute: "Story.Status", attributeLabel: "Status", typeLabel: "Backlog Item", relatedType: "StoryStatus", relatedTypeLabel: "StoryStatus", localized: null }); // A plain sentence is not a tag: nothing is asked about it and nothing is invented. expect(explained[2]).toMatchObject({ rule: null, attribute: null, attributeLabel: null, localized: null }); expect(explained[4]).toMatchObject({ rule: "AssetCannotDeleteClosed", attribute: null }); - // Which sentences are fit to show a user: the ones made for one. The raw server text is not. - expect(explained.map((e) => e.explained)).toEqual([true, true, false, true, true]); - // A rule the instance has no words for (seen live: closing a closed story) stays a token, and says it explains nothing. - expect((await explain(loc2(), [failure(0, "Violation'AssetCannotInactivateClosed")]))[0]).toMatchObject({ sentence: "Violation'AssetCannotInactivateClosed", explained: false, rule: "AssetCannotInactivateClosed", localized: null }); + // Who each sentence is for: the ones made for a person, and the server's raw text, which is echoed for a developer. + expect(explained.map((e) => [e.audience, e.echoed])).toEqual([["user", false], ["user", false], ["developer", true], ["user", false], ["user", false]]); + // A rule the instance has no words for (seen live: closing a closed story) is never answered as its bare token. + expect((await explain(loc2(), [failure(0, "Violation'AssetCannotInactivateClosed")]))[0]).toMatchObject({ sentence: "Agility did not accept this change (asset cannot inactivate closed).", audience: "user", echoed: false, rule: "AssetCannotInactivateClosed", localized: null, message: "Violation'AssetCannotInactivateClosed" }); + // A Resolution failure names the related type, labelled when the instance has a label for it. + const labelled = loc2(); + LOC2["AssetType'Member"] = "Member"; + LOC2["AttributeDefinition'Owners'Story"] = "Owner"; + try { + expect((await explain(labelled, [failure(0, "Resolution'Ambiguous'Story.Owners'Member")]))[0]).toMatchObject({ sentence: "Owner: more than one Member matches the value given.", rule: "Ambiguous", attribute: "Story.Owners", relatedType: "Member", relatedTypeLabel: "Member" }); + } finally { delete LOC2["AssetType'Member"]; delete LOC2["AttributeDefinition'Owners'Story"]; } }); it("takes an Outcome, a CommandFailureError or its failures alike; no failures, no request", async () => { @@ -77,10 +84,10 @@ describe("explain", () => { expect(await say(new UsageError("query of Story without a page: every read must be bounded"))).toBe("query of Story without a page: every read must be bounded"); expect(await say(new ApiError("Invalid WHERE parameter; Invalid QueryFilter2 token Nope=1", 400, "QUERY_REJECTED"))).toBe("Invalid WHERE parameter; Invalid QueryFilter2 token Nope=1"); expect(await say(new Error("boom"))).toBe("boom"); - // A developer's message is passed through and marked as not for a user; a consumer can call explain on anything and show only what is explained. - const fit = async (e: unknown) => (await explain(t, e))[0]!.explained; - expect([await fit(new ApiError("Unauthorized", 401)), await fit(new ApiError("down", 503)), await fit(new ApiError("x", 200, "CONFLICT"))]).toEqual([true, true, true]); - expect([await fit(new UsageError("query of Story without a page")), await fit(new ApiError("Invalid WHERE parameter", 400, "QUERY_REJECTED")), await fit(new ApiError("not JSON", 200, "BAD_JSON")), await fit(new Error("boom"))]).toEqual([false, false, false, false]); + // A consumer can call explain on anything and show only what is for a user: a developer's message is passed through and marked. + const about = async (e: unknown) => { const x = (await explain(t, e))[0]!; return [x.audience, x.echoed]; }; + for (const e of [new ApiError("Unauthorized", 401), new ApiError("down", 503), new ApiError("x", 200, "CONFLICT")]) expect(await about(e)).toEqual(["user", false]); + for (const e of [new UsageError("query of Story without a page"), new ApiError("Invalid WHERE parameter", 400, "QUERY_REJECTED"), new ApiError("not JSON", 200, "BAD_JSON"), new Error("boom")]) expect(await about(e)).toEqual(["developer", true]); expect(t.calls).toHaveLength(0); const down: Transport = { request: async () => { throw new ApiError("down", 503); } }; expect((await explain(down, [failure(0, "Violation'Required'AttributeDefinition'Scope'Story")]))[0]).toMatchObject({ sentence: "Scope is required.", attributeLabel: "Scope", typeLabel: "Story", localized: null }); diff --git a/test/unit/retry.test.ts b/test/unit/retry.test.ts index f02e9cb..c71f779 100644 --- a/test/unit/retry.test.ts +++ b/test/unit/retry.test.ts @@ -102,4 +102,27 @@ describe("onError and reauthorize", () => { expect(onUnauthorized).toHaveBeenCalledOnce(); expect(fetchImpl).toHaveBeenCalledTimes(3); }); + + it("a plain write refused as unauthorized is resent once only when the hook answers retry-write: not on retry, not for another status, never twice", async () => { + const run = async (statuses: number[], decision: "retry" | "retry-write" | "fail", options: { unauthorizedStatuses?: number[]; reauthorize?: boolean } = {}) => { + const answers = [...statuses]; + const fetchImpl = vi.fn(async () => { const status = answers.shift() ?? 200; return new Response(status === 200 ? JSON.stringify({ ok: true }) : "Forbidden", { status, headers: { "content-type": status === 200 ? "application/json" : "text/plain" } }); }); + const onUnauthorized = vi.fn(async () => decision); + const transport = createFetchTransport({ baseUrl: "https://x", retries: 3, fetchImpl: fetchImpl as unknown as typeof fetch, onUnauthorized, unauthorizedStatuses: options.unauthorizedStatuses ?? [401, 403] }); + const result = await transport.request({ method: "POST", path: "/api/asset", body: [{ from: "Story:1", update: { Name: "x" } }], responseType: "json", reauthorize: options.reauthorize }).catch((e: unknown) => e); + return { result, sends: fetchImpl.mock.calls.length, hooks: onUnauthorized.mock.calls.length, retryable: (onUnauthorized.mock.calls as unknown as [{ retryable: boolean }][])[0]?.[0].retryable }; + }; + // The session had expired: the hook re-authenticated and vouches that the refusal ran nothing. + expect(await run([403], "retry-write")).toMatchObject({ result: { ok: true }, sends: 2, hooks: 1, retryable: false }); + // "retry" keeps its meaning: a plain write is not resent. + expect(await run([403], "retry")).toMatchObject({ result: { kind: "forbidden" }, sends: 1, hooks: 1 }); + expect(await run([403], "fail")).toMatchObject({ result: { kind: "forbidden" }, sends: 1, hooks: 1 }); + // Only for a status the transport treats as "not signed in"; a 5xx on a write is never resent, whatever `retries` says. + expect(await run([403], "retry-write", { unauthorizedStatuses: [401] })).toMatchObject({ result: { kind: "forbidden" }, sends: 1, hooks: 0 }); + expect(await run([502], "retry-write")).toMatchObject({ result: { kind: "transient" }, sends: 1, hooks: 0 }); + // Never twice: a second refusal is final, and the hook is not asked again. + expect(await run([403, 403], "retry-write")).toMatchObject({ result: { kind: "forbidden" }, sends: 2, hooks: 1 }); + // And a request sent with reauthorize: false never reaches the hook. + expect(await run([403], "retry-write", { reauthorize: false })).toMatchObject({ result: { kind: "forbidden" }, sends: 1, hooks: 0 }); + }); }); diff --git a/test/unit/testing.test.ts b/test/unit/testing.test.ts index 4dd0192..9628779 100644 --- a/test/unit/testing.test.ts +++ b/test/unit/testing.test.ts @@ -150,6 +150,9 @@ describe("FakeAgilityClient", () => { expect(page.rows).toEqual([{ ...found[0], Owners: [{ _oid: "Member:20", Name: "Dana" }] }, found[1]]); expect(page).toMatchObject({ total: 3, more: true }); expect((await fake.data.list("BaseAsset", { page: { size: 2, start: 2 }, needTotal: true })).rows).toEqual([found[2]]); + // What a scripted Ref carries stays on it, as rest-1's display columns do live, whether or not the dotted path was selected. + fake.onList("Story", [{ _oid: "Story:1", Status: { _oid: "StoryStatus:1", Name: "Dev" }, Owners: [{ _oid: "Member:1", Name: "a", Nickname: "A" }, { _oid: "Member:2", Name: "b", Nickname: "B" }] }]); + expect((await fake.data.list("Story", { select: ["Status", "Owners"], page: { size: 1, start: 0 } })).rows).toEqual([{ _oid: "Story:1", Status: { _oid: "StoryStatus:1", Name: "Dev" }, Owners: [{ _oid: "Member:1", Name: "a", Nickname: "A" }, { _oid: "Member:2", Name: "b", Nickname: "B" }] }]); expect(fake.requests[0]).toMatchObject({ method: "GET", path: "/rest-1.v1/Data/BaseAsset", query: { find: "logon", findin: "Name", page: "2,0" } }); // A function sees the type and rest-1's own query string, and answers one page. fake.onList((type, q) => type === "Story" && q.deleted === "true", () => ({ rows: [{ _oid: "Story:7", Name: "gone" }], total: 12 })); @@ -201,12 +204,15 @@ describe("FakeAgilityClient", () => { const receipt = await fake.batch.run([{ from: "Story:1", update: { Estimate: 8 } }, { from: "Story:2", update: { Estimate: 8 } }, { "@t": { AssetType: "Task", Name: "new", Parent: "Story:1" } }], { guard: true }); expect(receipt).toMatchObject({ receipt: 2, sent: true, guarded: true, stopped: null, conflicts: [], failed: [], stamps: { "Story:1": "1", "Story:2": "1" }, after: { "Story:1": "2", "Story:2": "2", "Task:1000": "1" } }); expect(receipt.before["Story:1"]).toMatchObject({ Estimate: 3, Moment: "1" }); + // The projection is in the server's form: a scalar as { add, remove }, which is what a listing of the preview shows live. + expect(receipt.described.updates[0]).toEqual({ oid: "Story:1", attributes: { Estimate: { add: ["8"], remove: [] } } }); + expect(await fake.preview([{ from: "Story:1", execute: "QuickClose" }])).toEqual([{ "@fake-0": { oid: "Story:1", execute: { op: "QuickClose", args: {} } } }]); expect(receipt.created).toMatchObject([{ alias: "@t", AssetType: "Task", _oid: "Task:1000" }]); expect(receipt.reverse.commands).toEqual([{ from: "Story:1", update: { Estimate: 3 } }, { from: "Story:2", update: { Estimate: 3 + 2 } }, { from: "Task:1000", execute: "Delete" }]); expect((await fake.batch.reversible(receipt)).drifted).toEqual([]); fake.touch("Story:2"); const undo = await fake.batch.reversible(receipt); - expect(undo.drifted).toMatchObject([{ _oid: "Story:2", was: "2", now: "3" }]); + expect(undo.drifted).toMatchObject([{ oid: "Story:2", was: "2", now: "3" }]); expect(undo.commands).toEqual([{ from: "Story:1", update: { Estimate: 3 } }, { from: "Task:1000", execute: "Delete" }]); // A conflict at send time is on the receipt, and a dry run sends nothing. fake.onQuery("Epic", [{ _oid: "Epic:9", Name: "Nine" }]); From c38f3d2c9e8c10f46e5a707c51319a427f0b1cf7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:00:16 +0000 Subject: [PATCH 14/17] alpha.8: the package's manifest is reachable through the exports map @versionone/agility-sdk/package.json resolves by require and by import; a tool reading a dependency's version that way was refused. The CommonJS consumer test checks both. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 3 +++ package.json | 3 ++- test/unit/cjs.test.ts | 5 +++++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8529fae..02073c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -247,6 +247,9 @@ Each entry has the line a consumer follows to migrate. later is used without passing `fetchImpl`. - A read's explicit row type can be the caller's own: `client.query(…)` needs only `_oid` on `Card`, not the SDK's `Asset`. +- `@versionone/agility-sdk/package.json` resolves, by `require` and by + `import`: the exports map did not list it, so a tool reading the + package's version that way was refused. - `ReadResult.more` on rest-1 reads, as on `queryPage`. - `toBase64` / `fromBase64` on the root; an inline attachment read also answers `base64`, the content as it arrived. diff --git a/package.json b/package.json index d2f54ed..89df342 100644 --- a/package.json +++ b/package.json @@ -56,7 +56,8 @@ "types": "./dist/testing.d.cts", "default": "./dist/testing.cjs" } - } + }, + "./package.json": "./package.json" }, "files": [ "dist", diff --git a/test/unit/cjs.test.ts b/test/unit/cjs.test.ts index 643bd16..7945c74 100644 --- a/test/unit/cjs.test.ts +++ b/test/unit/cjs.test.ts @@ -69,6 +69,10 @@ const fetchImpl = async (url) => { assert.equal(services.guard.ConflictError, sdk.ConflictError); assert.equal(services.schema.TypeCache, sdk.TypeCache); assert.equal(sdk.toBase64(new Uint8Array([104, 105])), "aGk="); + // The package's own manifest is reachable, for tools that read a dependency's version: by require and by import. + assert.equal(require("@versionone/agility-sdk/package.json").name, "@versionone/agility-sdk"); + const manifest = await import("@versionone/agility-sdk/package.json", { with: { type: "json" } }); + assert.equal(manifest.default.version, require("@versionone/agility-sdk/package.json").version); 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" }]); @@ -92,6 +96,7 @@ 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" }); + expect((pkg.exports as unknown as Record)["./package.json"]).toBe("./package.json"); for (const path of ["wire", "services", "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` } }); } From f0c161530b207a1652d57427a18252f6b7272e71 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:01:24 +0000 Subject: [PATCH 15/17] alpha.8: every explanation of a failed command states the reason alone MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sentence for a rule the instance has no words for carried its own framing ("Agility did not accept this change (…)") while the others gave the reason only, so a consumer that frames the reply said it twice. It is now "Refused (asset cannot inactivate closed).", and the field's doc says the sentence is the reason and the framing is the caller's. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- src/services/explain.ts | 10 ++++++++-- test/unit/explain.test.ts | 2 +- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/services/explain.ts b/src/services/explain.ts index ec78cb1..9e0c8d6 100644 --- a/src/services/explain.ts +++ b/src/services/explain.ts @@ -30,7 +30,13 @@ import { parseViolation } from "../types/command"; import * as loc2 from "../wire/loc2"; export interface Explanation { - /** One short sentence. English, with the instance's own labels for attributes and asset types. */ + /** + * One short sentence. English, with the instance's own labels for + * attributes and asset types. For a failed command it states the reason + * and nothing else ("Project is required.", "Refused (asset cannot + * inactivate closed)."), so a caller can put its own words around it + * ("Agility didn't accept that: …") without saying anything twice. + */ sentence: string; /** * Who the sentence is for. "user": it was made for a person using the @@ -95,7 +101,7 @@ function sentenceOf(problem: Problem, label: string | null, related: string | nu if (localized) return forUser(localized); // A rule the instance has no words for (seen live: Violation'AssetCannotInactivateClosed): never the bare token. // What it means is in the rule's name, which a person can read; the token stays in `message` and `rule`. - if (problem.rule) return forUser(`Agility did not accept this change${label ? ` to ${label}` : ""} (${words(problem.rule)}).`); + if (problem.rule) return forUser(`${label ? `${label}: refused` : "Refused"} (${words(problem.rule)}).`); // Anything else is the server's own text, as it came. return { sentence: message, audience: "developer", echoed: true }; } diff --git a/test/unit/explain.test.ts b/test/unit/explain.test.ts index 307c6f1..3aae557 100644 --- a/test/unit/explain.test.ts +++ b/test/unit/explain.test.ts @@ -53,7 +53,7 @@ describe("explain", () => { // Who each sentence is for: the ones made for a person, and the server's raw text, which is echoed for a developer. expect(explained.map((e) => [e.audience, e.echoed])).toEqual([["user", false], ["user", false], ["developer", true], ["user", false], ["user", false]]); // A rule the instance has no words for (seen live: closing a closed story) is never answered as its bare token. - expect((await explain(loc2(), [failure(0, "Violation'AssetCannotInactivateClosed")]))[0]).toMatchObject({ sentence: "Agility did not accept this change (asset cannot inactivate closed).", audience: "user", echoed: false, rule: "AssetCannotInactivateClosed", localized: null, message: "Violation'AssetCannotInactivateClosed" }); + expect((await explain(loc2(), [failure(0, "Violation'AssetCannotInactivateClosed")]))[0]).toMatchObject({ sentence: "Refused (asset cannot inactivate closed).", audience: "user", echoed: false, rule: "AssetCannotInactivateClosed", localized: null, message: "Violation'AssetCannotInactivateClosed" }); // A Resolution failure names the related type, labelled when the instance has a label for it. const labelled = loc2(); LOC2["AssetType'Member"] = "Member"; From 0d8676ae028102ba605e57c61ab488a7ccc781cd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:07:11 +0000 Subject: [PATCH 16/17] attachments.add answers the attachment without the stamps it never read CreateDate and "CreatedBy.Name" were always null on what add answers, which in a closed row reads as "this attachment has none". The answer is now AddedAttachment (AttachmentInfo without those two), and so is AttachmentUploadError.attachment. Reported by a browser app consumer. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 7 +++++++ src/index.ts | 2 +- src/services/attachments.ts | 17 ++++++++++++----- test/unit/attachment.test.ts | 5 ++++- test/unit/errors.test.ts | 2 +- 5 files changed, 25 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 02073c7..880772c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -156,6 +156,13 @@ Each entry has the line a consumer follows to migrate. a required single relation without a null check gets a compile error and needs the check. +- **`client.attachments.add` no longer answers `CreateDate` and + `"CreatedBy.Name"`.** They were always null there (the server's stamps + are not read back after a create), which in a row read as "this + attachment has no creator or date". The answer's type is + `AddedAttachment`, and so is `AttachmentUploadError.attachment`. + Migration: read them with `client.attachments.info(id)` or from a + `list`. (a browser app consumer.) - **A resolved asset is a row**: `client.resolve.numbers` and `ref` answer `{ _oid, AssetType, Number, Name, AssetState }`, the names every row uses. Migration: `oid` → `_oid`; `type` → `AssetType`; `number` → diff --git a/src/index.ts b/src/index.ts index fc2bf1a..6218ee4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -38,7 +38,7 @@ export { importantName } from "./services/fields"; export { TypeCache } from "./services/schema"; export type { Schema } from "./services/schema"; export { AttachmentUploadError, INLINE_LIMIT } from "./services/attachments"; -export type { AddOptions as AttachmentAddOptions, AttachmentFile, AttachmentInfo, GetOptions as AttachmentGetOptions, ListOptions as AttachmentListOptions, ListedAttachment } from "./services/attachments"; +export type { AddOptions as AttachmentAddOptions, AddedAttachment, AttachmentFile, AttachmentInfo, GetOptions as AttachmentGetOptions, ListOptions as AttachmentListOptions, ListedAttachment } from "./services/attachments"; export { fromBase64, toBase64 } from "./wire/attachment"; export type { Explanation } from "./services/explain"; export { isAssetNumber } from "./services/resolve"; diff --git a/src/services/attachments.ts b/src/services/attachments.ts index 6b50378..1feb159 100644 --- a/src/services/attachments.ts +++ b/src/services/attachments.ts @@ -161,24 +161,31 @@ export interface AddOptions { inlineLimit?: number; } +/** + * What `add` answers: the attachment as it was written. The server's own + * stamps (when it was created, and by whom) are not read back, so they are + * not in the type at all — a null there would read as "it has none". Read + * the attachment with `info` for those. + */ +export type AddedAttachment = Omit; + /** 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) { + constructor(readonly attachment: AddedAttachment, 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); this.name = "AttachmentUploadError"; } } -/** 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 { +/** Attach a file to an asset. Inline up to `inlineLimit` bytes, two-step above it. Answers the attachment as written, without the server's own stamps (read it with `info` for its `CreateDate` and creator). */ +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"); const inline = bytes.length <= (options.inlineLimit ?? INLINE_LIMIT); 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]!; - // 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 }; + const created: AddedAttachment = { _oid: oid, id: numericId(oid), Name: String(create.Name), Filename: options.filename, ContentType: contentType, Description: options.description ?? null }; if (!inline) { try { await putBytes(transport, created.id, bytes, contentType); diff --git a/test/unit/attachment.test.ts b/test/unit/attachment.test.ts index e513f05..0f15d25 100644 --- a/test/unit/attachment.test.ts +++ b/test/unit/attachment.test.ts @@ -71,7 +71,10 @@ 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).toEqual({ _oid: "Attachment:77", id: "77", Name: "a.txt", Filename: "a.txt", ContentType: "text/plain", Description: null, CreateDate: null, "CreatedBy.Name": null }); + expect(created).toEqual({ _oid: "Attachment:77", id: "77", Name: "a.txt", Filename: "a.txt", ContentType: "text/plain", Description: null }); + // The server's stamps were not read back, so the type does not offer them: null would read as "it has none". + // @ts-expect-error not on what add answers; read the attachment with info + void created.CreateDate; }); it("a large file goes in two steps: create with empty Content, then POST the bytes", async () => { diff --git a/test/unit/errors.test.ts b/test/unit/errors.test.ts index e5d836f..74a9f36 100644 --- a/test/unit/errors.test.ts +++ b/test/unit/errors.test.ts @@ -53,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.Name": 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 }, new ApiError("too big", 413, "TOO_LARGE")).kind).toBe("invalid"); }); it("a command failure is kind commandFailure, and its violations are parsed", () => { From 4df24106cd31e49b1fb88d6c31212e96adeef4f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:08:08 +0000 Subject: [PATCH 17/17] Live test: attachments.add answers no stamps; info has them Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- test/integration/attachments.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/integration/attachments.test.ts b/test/integration/attachments.test.ts index 90511e6..d80d76f 100644 --- a/test/integration/attachments.test.ts +++ b/test/integration/attachments.test.ts @@ -33,6 +33,14 @@ describeInstance("attachments (live)", () => { 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); + // add answers what it wrote and not the server's stamps, which it never read: they are absent, not null. + for (const added of [small, large]) { + expect(added).not.toHaveProperty("CreateDate"); + expect(added).not.toHaveProperty("CreatedBy.Name"); + } + const read = await client.attachments.info(small.id); + expect(typeof read?.CreateDate).toBe("string"); + expect(typeof read?.["CreatedBy.Name"]).toBe("string"); expect(decode((await client.attachments.get(small.id)).bytes)).toBe("hello attachment\n"); const got = await client.attachments.get(large._oid); expect(decode(got.bytes)).toBe("two-step bytes\n");