diff --git a/AGENTS.md b/AGENTS.md
index 3ccc241..bcf75c2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -38,6 +38,7 @@ src/testing What a consumer's tests import: a fake client and the Transport c
src/index.ts The root's public exports.
test/unit Runs with nothing. A fake Transport answering what the server answers.
test/integration The same modules against a real instance. Writes fixtures.
+examples One runnable program per task, as a consumer would write it (examples/README.md).
scripts Metamodel download, type generation, the integration launcher.
metamodel.json The product's metamodel for one release; the generated types come from it.
```
@@ -85,7 +86,9 @@ change, by design: `layers.test.ts` (imports point down the layer table),
- **Live calls go only where fixtures may be written**: a local dev
instance, or a hosted instance set aside for API testing and named in
`SDK_TEST_ALLOWED_INSTANCES`. Fixtures are named `sdk-integration …` and
- deleted by exact OID by the test that made them. Every query is paged.
+ deleted by exact OID by the test that made them, with `deleteFixtures`
+ (test/integration/instance.ts), which fails the suite if one is left.
+ Every query is paged.
- **Nothing private in the tree.** See `CONTRIBUTING.md`. A URL in an
example uses `agility.example.com`.
- **A failure never reads as an empty result**, and no read is unbounded
@@ -95,6 +98,10 @@ change, by design: `layers.test.ts` (imports point down the layer table),
- **One shape for a row** on every read path (spec 000 §2): a selected
relation is a Ref, a path selected by name is at `row[path]`, nothing
unselected arrives, and a row's identity is `_oid`.
+- **The examples stay true.** `npm run typecheck` compiles `examples/`
+ against the source and the integration tier runs each one. A change to
+ the public API that an example uses changes the example in the same
+ pull request; a new task a consumer would do gets a new numbered file.
- **A change a consumer can see gets a changelog entry with its migration
line.** Until 1.0.0, breaking changes are allowed between alphas and are
listed under "Breaking".
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 880772c..a5dd68c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,13 @@
# Changelog
+## Unreleased
+
+Nothing in the package changes.
+
+- The repository has runnable examples, one per task, in `examples/`
+ (they are not in the published package). They are compiled by
+ `npm run typecheck` and run by the integration tier.
+
## 1.0.0-alpha.8 — the last breaking batch before 1.0
Each entry has the line a consumer follows to migrate.
diff --git a/README.md b/README.md
index 529fef4..13ec445 100644
--- a/README.md
+++ b/README.md
@@ -20,6 +20,8 @@ const stories = await client.query({ from: "Story", select: ["Name", "Estimate"]
// stories[0].Estimate is a number | null; stories[0].Nmae does not compile
```
+Runnable examples, one per task (a first read, a write, a guarded write, a batch with an undo, errors, attachments, testing your own code, a transport of your own, a browser session that expires), are in [`examples/`](examples/README.md).
+
## Working on the SDK
```bash
diff --git a/examples/01-read.ts b/examples/01-read.ts
new file mode 100644
index 0000000..decd455
--- /dev/null
+++ b/examples/01-read.ts
@@ -0,0 +1,48 @@
+/**
+ * Reading: typed rows, relations, a page with its total, one asset, and
+ * the member the credentials belong to. Writes nothing.
+ *
+ * V1_URL=https://agility.example.com/MyInstance V1_ACCESS_TOKEN=… node examples/01-read.ts
+ */
+import { AgilityApiClient } from "@versionone/agility-sdk";
+
+const { V1_URL, V1_ACCESS_TOKEN } = process.env;
+if (!V1_URL || !V1_ACCESS_TOKEN) throw new Error("set V1_URL and V1_ACCESS_TOKEN");
+const client = new AgilityApiClient({ baseUrl: V1_URL, accessToken: V1_ACCESS_TOKEN });
+
+const me = await client.me();
+console.log(`signed in as ${me.Name} (${me._oid})`);
+
+// Every read is paged: an unpaged query does not compile. The rows are
+// typed by what was selected, so `story.Estimate` is number | null and a
+// misspelt attribute is a compile error.
+const stories = await client.query({
+ from: "Story",
+ select: [
+ "Name",
+ "Number",
+ "Estimate",
+ "Scope", // a relation you select is a Ref: { _oid }
+ "Status.Name", // a path you select by name is at row["Status.Name"]
+ { from: "Owners", select: ["Name"] } // a sub-select gives rows of the related type
+ ],
+ sort: ["-ChangeDate"],
+ page: { size: 5, start: 0 }
+});
+for (const story of stories) {
+ const owners = story.Owners.map((owner) => owner.Name).join(", ") || "nobody";
+ console.log(`${story.Number} ${story.Name} estimate ${story.Estimate ?? "-"} status ${story["Status.Name"] ?? "-"} scope ${story.Scope?._oid} owners: ${owners}`);
+}
+
+// The same query with the total, and whether more rows follow.
+const page = await client.queryPage({ from: "Story", select: ["Name"], where: { "AssetState": "64" }, page: { size: 5, start: 0 } });
+console.log(`${page.rows.length} of ${page.total ?? "an unknown number of"} open stories; more: ${page.more}`);
+
+// One asset by OID: null when nothing has that OID, never an error.
+const first = stories[0];
+if (first) {
+ const again = await client.get(first._oid, ["Name", "ChangeDate"]);
+ console.log(`${first._oid} was last changed ${again?.ChangeDate}`);
+ console.log(`open it at ${client.urls.asset(first._oid)}`);
+}
+console.log(`Story:0 is ${await client.get("Story:0", ["Name"])}`);
diff --git a/examples/02-write.ts b/examples/02-write.ts
new file mode 100644
index 0000000..9ed2cb3
--- /dev/null
+++ b/examples/02-write.ts
@@ -0,0 +1,43 @@
+/**
+ * Writing: create, update, run an operation, read the Outcome, delete.
+ *
+ * This example WRITES: it creates one Story named "sdk-integration example …"
+ * in the system scope and deletes it before it ends. Run it only against an
+ * instance where that is acceptable, and say so with V1_EXAMPLES_WRITE=1.
+ *
+ * V1_URL=… V1_ACCESS_TOKEN=… V1_EXAMPLES_WRITE=1 node examples/02-write.ts
+ */
+import { AgilityApiClient } from "@versionone/agility-sdk";
+
+const { V1_URL, V1_ACCESS_TOKEN, V1_EXAMPLES_WRITE } = process.env;
+if (!V1_URL || !V1_ACCESS_TOKEN) throw new Error("set V1_URL and V1_ACCESS_TOKEN");
+if (V1_EXAMPLES_WRITE !== "1") throw new Error("this example creates and deletes a Story; set V1_EXAMPLES_WRITE=1 on an instance where that is acceptable");
+const client = new AgilityApiClient({ baseUrl: V1_URL, accessToken: V1_ACCESS_TOKEN });
+const name = `sdk-integration example write ${new Date().toISOString()}`;
+
+// A create is a command with an AssetType. `throwOnFailure` turns a refused
+// command into a thrown CommandFailureError; without it, read `failures`.
+const made = await client.send([{ AssetType: "Story", Name: name, Scope: { _oid: "Scope:0" }, Estimate: 2 }], { throwOnFailure: true });
+const story = made.created[0]!;
+console.log(`created ${story}`);
+
+try {
+ // An update and an operation, in one request, in order.
+ const outcome = await client.send([
+ { from: story, update: { Estimate: 3, Description: "
written by an example
" } },
+ { from: story, execute: "QuickClose" }
+ ]);
+ console.log(`modified ${outcome.modified.join(", ")}; operated ${outcome.operated.join(", ")}; failures ${outcome.failures.length}`);
+
+ const read = await client.get(story, ["Estimate", "AssetState"]);
+ console.log(`estimate is now ${read?.Estimate}, state ${read?.AssetState}`);
+
+ // `send` is unguarded: it writes whatever is there. A command addressed to
+ // an asset that is gone is answered by the server with success; `unmatched`
+ // is how you find out.
+ const gone = await client.send([{ from: "Story:0", update: { Estimate: 1 } }]);
+ console.log(`commands that matched no asset: ${JSON.stringify(gone.unmatched)}`);
+} finally {
+ await client.send([{ from: story, execute: "Reactivate" }, { from: story, execute: "Delete" }], { throwOnFailure: true });
+ console.log(`deleted ${story}`);
+}
diff --git a/examples/03-guarded-write.ts b/examples/03-guarded-write.ts
new file mode 100644
index 0000000..078f53c
--- /dev/null
+++ b/examples/03-guarded-write.ts
@@ -0,0 +1,50 @@
+/**
+ * A guarded write: change an asset only if nobody changed it since you read
+ * it. What matched nothing is a conflict, never a silent success.
+ *
+ * This example WRITES: one Story named "sdk-integration example …", deleted
+ * before it ends. See 02-write.ts for V1_EXAMPLES_WRITE.
+ *
+ * V1_URL=… V1_ACCESS_TOKEN=… V1_EXAMPLES_WRITE=1 node examples/03-guarded-write.ts
+ */
+import { AgilityApiClient, ConflictError } from "@versionone/agility-sdk";
+
+const { V1_URL, V1_ACCESS_TOKEN, V1_EXAMPLES_WRITE } = process.env;
+if (!V1_URL || !V1_ACCESS_TOKEN) throw new Error("set V1_URL and V1_ACCESS_TOKEN");
+if (V1_EXAMPLES_WRITE !== "1") throw new Error("this example creates and deletes a Story; set V1_EXAMPLES_WRITE=1 on an instance where that is acceptable");
+const client = new AgilityApiClient({ baseUrl: V1_URL, accessToken: V1_ACCESS_TOKEN });
+const name = `sdk-integration example guarded ${new Date().toISOString()}`;
+
+const story = (await client.send([{ AssetType: "Story", Name: name, Scope: { _oid: "Scope:0" }, Estimate: 1 }], { throwOnFailure: true })).created[0]!;
+try {
+ // A person opens the story in a form. Keep the Moment they saw: it names
+ // that exact version of the asset.
+ const seen = await client.get(story, ["Estimate", "Moment"]);
+ const moments = { [story]: String(seen!.Moment) };
+
+ // Meanwhile someone else edits it.
+ await client.send([{ from: story, update: { Estimate: 8 } }], { throwOnFailure: true });
+
+ // The person saves. Guarded on what they saw, the write is left out and
+ // the story is listed in `conflicts`; the other edit survives.
+ const stale = await client.sendGuarded([{ from: story, update: { Estimate: 2 } }], { moments });
+ console.log(`conflicts: ${stale.conflicts.join(", ")}; modified: ${stale.modified.length}`);
+ console.log(`estimate is still ${(await client.get(story, ["Estimate"]))?.Estimate}`);
+
+ // With throwOnFailure a conflict is thrown, carrying the same result.
+ try {
+ await client.sendGuarded([{ from: story, update: { Estimate: 2 } }], { moments, throwOnFailure: true });
+ } catch (error) {
+ if (!(error instanceof ConflictError)) throw error;
+ console.log(`thrown: kind ${error.kind}: ${error.message}`);
+ }
+
+ // Without `moments` the guard reads each asset's Moment just before it
+ // writes: protection against a writer racing this call, not against
+ // everything since a person looked.
+ const fresh = await client.sendGuarded([{ from: story, update: { Estimate: 2 } }]);
+ console.log(`modified: ${fresh.modified.join(", ")}; conflicts: ${fresh.conflicts.length}`);
+} finally {
+ await client.send([{ from: story, execute: "Delete" }], { throwOnFailure: true });
+ console.log(`deleted ${story}`);
+}
diff --git a/examples/04-batch-undo.ts b/examples/04-batch-undo.ts
new file mode 100644
index 0000000..16184cb
--- /dev/null
+++ b/examples/04-batch-undo.ts
@@ -0,0 +1,49 @@
+/**
+ * A batch with a record and an undo: preview what it would touch, send it,
+ * keep the receipt, and later reverse it unless someone changed the assets
+ * in between.
+ *
+ * This example WRITES: two Stories named "sdk-integration example …",
+ * deleted before it ends. See 02-write.ts for V1_EXAMPLES_WRITE.
+ *
+ * V1_URL=… V1_ACCESS_TOKEN=… V1_EXAMPLES_WRITE=1 node examples/04-batch-undo.ts
+ */
+import { AgilityApiClient } from "@versionone/agility-sdk";
+
+const { V1_URL, V1_ACCESS_TOKEN, V1_EXAMPLES_WRITE } = process.env;
+if (!V1_URL || !V1_ACCESS_TOKEN) throw new Error("set V1_URL and V1_ACCESS_TOKEN");
+if (V1_EXAMPLES_WRITE !== "1") throw new Error("this example creates and deletes two Stories; set V1_EXAMPLES_WRITE=1 on an instance where that is acceptable");
+const client = new AgilityApiClient({ baseUrl: V1_URL, accessToken: V1_ACCESS_TOKEN });
+const stamp = new Date().toISOString();
+
+const made = await client.send(["a", "b"].map((x) => ({ AssetType: "Story", Name: `sdk-integration example batch ${x} ${stamp}`, Scope: { _oid: "Scope:0" }, Estimate: 1 })), { throwOnFailure: true });
+const [a, b] = made.created as [string, string];
+try {
+ const commands = [
+ { from: a, update: { Estimate: 5 } },
+ { from: b, execute: "QuickClose" }
+ ];
+
+ // dryRun stops after the preview: what would be touched, by name.
+ const plan = await client.batch.run(commands, { guard: true, dryRun: true });
+ console.log(`would update ${plan.described.updates.length}, execute ${plan.described.executes.length}; sent: ${plan.sent}`);
+
+ // `guard` has no default: true is a compare-and-set on each asset, false
+ // sends the batch as written. `confirm` sees the receipt before anything
+ // is sent and can decline.
+ const receipt = await client.batch.run(commands, { guard: true, confirm: (r) => Object.keys(r.names).length === 2 });
+ console.log(`sent: ${receipt.sent}; touched ${receipt.touched.map((t) => `${t.Number} ${t.Name}`).join(" | ")}; conflicts ${receipt.conflicts.length}`);
+
+ // A receipt is plain JSON: store it, and reverse it later.
+ const stored = JSON.parse(JSON.stringify(receipt));
+ const undo = await client.batch.reversible(stored);
+ console.log(`undo has ${undo.commands.length} commands; changed since by someone else: ${undo.drifted.length}`);
+ const undone = await client.batch.run(undo.commands, { guard: true });
+ console.log(`undone: ${undone.sent}`);
+
+ const now = await client.query({ from: "Story", select: ["Estimate", "AssetState"], filter: ["ID=$ids"], with: { $ids: [a, b] }, sort: ["Name"], page: { size: 2, start: 0 } });
+ console.log(now.map((s) => `${s._oid}: estimate ${s.Estimate}, state ${s.AssetState}`).join("; "));
+} finally {
+ await client.send([a, b].map((oid) => ({ from: oid, execute: "Delete" })), { throwOnFailure: true });
+ console.log(`deleted ${a} and ${b}`);
+}
diff --git a/examples/05-errors.ts b/examples/05-errors.ts
new file mode 100644
index 0000000..1bfc59c
--- /dev/null
+++ b/examples/05-errors.ts
@@ -0,0 +1,38 @@
+/**
+ * Errors: everything thrown is an ApiError with a `kind` to branch on, and
+ * `client.explain` says a failure to a person in the instance's own words.
+ * Creates nothing: every write here is one the server refuses.
+ *
+ * V1_URL=… V1_ACCESS_TOKEN=… node examples/05-errors.ts
+ */
+import { AgilityApiClient, ApiError } from "@versionone/agility-sdk";
+
+const { V1_URL, V1_ACCESS_TOKEN } = process.env;
+if (!V1_URL || !V1_ACCESS_TOKEN) throw new Error("set V1_URL and V1_ACCESS_TOKEN");
+const client = new AgilityApiClient({ baseUrl: V1_URL, accessToken: V1_ACCESS_TOKEN });
+
+const attempt = async (what: string, run: () => Promise): Promise => {
+ try {
+ await run();
+ console.log(`${what}: no error`);
+ } catch (error) {
+ if (!(error instanceof ApiError)) throw error;
+ // `kind` is what to branch on; `code` and `status` are detail.
+ console.log(`${what}: kind ${error.kind}, code ${error.code}, status ${error.status}`);
+ for (const e of await client.explain(error)) console.log(` for the ${e.audience}: ${e.sentence}`);
+ }
+};
+
+// A mistake in the call is caught before any request: kind "usage", status 0.
+await attempt("an empty batch", () => client.batch.run([], { guard: true }));
+
+// A query the server refuses throws; it never reads as an empty result.
+// (The cast is what it takes to get a misspelt attribute past the compiler.)
+await attempt("an attribute that does not exist", () => client.query({ from: "Story", select: ["Nmae" as "Name"], page: { size: 1, start: 0 } }));
+
+// A command the server refuses: a Story needs a Name and a Scope.
+await attempt("a create missing what is required", () => client.send([{ AssetType: "Story", Estimate: 1 }], { throwOnFailure: true }));
+
+// Without throwOnFailure the same refusal is data, on the Outcome.
+const outcome = await client.send([{ AssetType: "Story", Estimate: 1 }]);
+console.log(`failures: ${outcome.failures.length}; created: ${outcome.created.length}`);
diff --git a/examples/06-attachments.ts b/examples/06-attachments.ts
new file mode 100644
index 0000000..2314db1
--- /dev/null
+++ b/examples/06-attachments.ts
@@ -0,0 +1,38 @@
+/**
+ * Attachments: add a file to an asset, list, read it back, remove it.
+ *
+ * This example WRITES: one Story named "sdk-integration example …" with one
+ * attachment, both deleted before it ends. See 02-write.ts for
+ * V1_EXAMPLES_WRITE.
+ *
+ * V1_URL=… V1_ACCESS_TOKEN=… V1_EXAMPLES_WRITE=1 node examples/06-attachments.ts
+ */
+import { AgilityApiClient } from "@versionone/agility-sdk";
+
+const { V1_URL, V1_ACCESS_TOKEN, V1_EXAMPLES_WRITE } = process.env;
+if (!V1_URL || !V1_ACCESS_TOKEN) throw new Error("set V1_URL and V1_ACCESS_TOKEN");
+if (V1_EXAMPLES_WRITE !== "1") throw new Error("this example creates and deletes a Story and an attachment; set V1_EXAMPLES_WRITE=1 on an instance where that is acceptable");
+const client = new AgilityApiClient({ baseUrl: V1_URL, accessToken: V1_ACCESS_TOKEN });
+const name = `sdk-integration example attachment ${new Date().toISOString()}`;
+
+const story = (await client.send([{ AssetType: "Story", Name: name, Scope: { _oid: "Scope:0" } }], { throwOnFailure: true })).created[0]!;
+let attachment: string | undefined;
+try {
+ // Bytes are a Uint8Array, an ArrayBuffer or a Blob. `add` answers the
+ // attachment as written; `id` is the number its bytes are addressed by.
+ const added = await client.attachments.add(story, new TextEncoder().encode("hello from an example\n"), { filename: "sdk-integration example.txt", contentType: "text/plain", description: "written by an example" });
+ attachment = added._oid;
+ console.log(`added ${added._oid} (${added.Filename}, ${added.ContentType})`);
+
+ // A list answers metadata only: no bytes travel until you ask for a file.
+ for (const a of await client.attachments.list(story)) console.log(`listed ${a._oid}: ${a.Filename}, created ${a.CreateDate} by ${a["CreatedBy.Name"]}`);
+
+ // `inline: true` reads a small file's metadata and bytes in one request.
+ const file = await client.attachments.get(added.id, { inline: true });
+ console.log(`read ${file.bytes.byteLength} bytes: ${JSON.stringify(new TextDecoder().decode(file.bytes))}`);
+ console.log(`a browser opens it at ${client.urls.attachment(added.id)}`);
+} finally {
+ if (attachment) await client.attachments.remove(attachment.split(":")[1]!);
+ await client.send([{ from: story, execute: "Delete" }], { throwOnFailure: true });
+ console.log(`deleted ${story} and its attachment`);
+}
diff --git a/examples/07-testing.ts b/examples/07-testing.ts
new file mode 100644
index 0000000..3d77a7e
--- /dev/null
+++ b/examples/07-testing.ts
@@ -0,0 +1,48 @@
+/**
+ * Testing code that uses the SDK, with no instance: FakeAgilityClient is a
+ * real client over a transport that sends nothing and answers what the
+ * test scripted. Needs no credentials and no network.
+ *
+ * node examples/07-testing.ts
+ */
+import assert from "node:assert/strict";
+import type { AgilityApiClient } from "@versionone/agility-sdk";
+import { FakeAgilityClient } from "@versionone/agility-sdk/testing";
+
+// The code under test: yours. It takes a client, so a test can hand it the fake.
+async function closeIfEstimated(client: AgilityApiClient, oid: string): Promise<"closed" | "needs an estimate" | "changed by someone else"> {
+ const story = await client.get(oid, ["Estimate", "Moment"]);
+ if (story?.Estimate == null) return "needs an estimate";
+ const result = await client.sendGuarded([{ from: oid, execute: "QuickClose" }], { moments: { [oid]: String(story.Moment) } });
+ return result.conflicts.length ? "changed by someone else" : "closed";
+}
+
+// It closes an estimated story, and what it sent is on the fake.
+{
+ const fake = new FakeAgilityClient().onQuery("Story", [{ _oid: "Story:1", Name: "Logon", Estimate: 2 }]);
+ assert.equal(await closeIfEstimated(fake, "Story:1"), "closed");
+ assert.equal(fake.sent.length, 1); // one batch was sent,
+ assert.match(JSON.stringify(fake.sent[0]), /Story:1.*QuickClose/); // as the guard wrote it for the server
+}
+
+// It leaves an unestimated story alone: nothing was sent.
+{
+ const fake = new FakeAgilityClient().onQuery("Story", [{ _oid: "Story:2", Name: "Logoff", Estimate: null }]);
+ assert.equal(await closeIfEstimated(fake, "Story:2"), "needs an estimate");
+ assert.equal(fake.sent.length, 0);
+}
+
+// Someone else changes the story between the read and the write: `touch`
+// is that other writer, and the guarded write is a conflict.
+{
+ const fake = new FakeAgilityClient().onQuery("Story", [{ _oid: "Story:3", Name: "Search", Estimate: 5 }]);
+ const racing = new Proxy(fake, { get: (target, key) => key === "sendGuarded"
+ ? (...args: Parameters) => { target.touch("Story:3"); return target.sendGuarded(...args); }
+ : Reflect.get(target, key) });
+ assert.equal(await closeIfEstimated(racing, "Story:3"), "changed by someone else");
+}
+
+// A read nothing was scripted for throws; it never looks like an empty result.
+await assert.rejects(new FakeAgilityClient().query({ from: "Defect", select: ["Name"], page: { size: 1, start: 0 } }));
+
+console.log("all four checks passed");
diff --git a/examples/08-custom-transport.ts b/examples/08-custom-transport.ts
new file mode 100644
index 0000000..7c4b439
--- /dev/null
+++ b/examples/08-custom-transport.ts
@@ -0,0 +1,66 @@
+/**
+ * A Transport of your own: here, the SDK's fetch transport wrapped to time
+ * every request, the way an app adds tracing or metrics. The conformance
+ * suite says whether a transport does everything the SDK expects of one;
+ * run it in your tests.
+ *
+ * The checks need no instance. With V1_URL and V1_ACCESS_TOKEN set, the
+ * example also makes one live read through the transport. Writes nothing.
+ *
+ * node examples/08-custom-transport.ts
+ */
+import { AgilityApiClient, createFetchTransport } from "@versionone/agility-sdk";
+import type { Transport } from "@versionone/agility-sdk";
+import { CONFORMANCE_BASE_URL, fetchFrom, transportConformance } from "@versionone/agility-sdk/testing";
+
+const timings: { path: string; ms: number; failed: boolean }[] = [];
+
+// A Transport is one method. This one hands the work to the fetch transport
+// and records how long each request took, whether it resolved or threw.
+function timed(inner: Transport): Transport {
+ return {
+ async request(options) {
+ const started = performance.now();
+ let failed = false;
+ try {
+ return await inner.request(options);
+ } catch (error) {
+ failed = true;
+ throw error; // rethrown untouched: everything a transport throws is an ApiError
+ } finally {
+ timings.push({ path: options.path, ms: Math.round(performance.now() - started), failed });
+ }
+ }
+ };
+}
+
+// In a test file this is `for (const check of …) it(check.name, check.run)`.
+// The suite hands your factory a stand-in for the network; `fetchFrom`
+// turns it into a fetch. A transport built on another HTTP client passes
+// the server to that client instead.
+const checks = transportConformance((server) => timed(createFetchTransport({ baseUrl: CONFORMANCE_BASE_URL, fetchImpl: fetchFrom(server) })));
+let broken = 0;
+for (const check of checks) {
+ try {
+ await check.run();
+ } catch (error) {
+ broken += 1;
+ console.log(`BROKEN: ${check.name}: ${(error as Error).message}`);
+ }
+}
+console.log(`${checks.length - broken} of ${checks.length} conformance checks pass`);
+if (broken) process.exitCode = 1;
+
+// The client takes the transport as an option. The resend rule and
+// `onError` are the client's, so they apply to any transport; `baseUrl` in
+// the config is then used only for the links the client builds.
+const { V1_URL, V1_ACCESS_TOKEN } = process.env;
+if (V1_URL && V1_ACCESS_TOKEN) {
+ timings.length = 0;
+ const transport = timed(createFetchTransport({ baseUrl: V1_URL, accessToken: V1_ACCESS_TOKEN }));
+ const client = new AgilityApiClient({ baseUrl: V1_URL }, { transport });
+ const stories = await client.query({ from: "Story", select: ["Name"], page: { size: 3, start: 0 } });
+ console.log(`read ${stories.length} stories in ${timings.length} requests: ${timings.map((t) => `${t.path.split("?")[0]} ${t.ms} ms`).join(", ")}`);
+} else {
+ console.log("set V1_URL and V1_ACCESS_TOKEN to also make a live read through the transport");
+}
diff --git a/examples/09-browser-session.ts b/examples/09-browser-session.ts
new file mode 100644
index 0000000..aff65d9
--- /dev/null
+++ b/examples/09-browser-session.ts
@@ -0,0 +1,76 @@
+/**
+ * A browser app on the instance's own origin: no token, the browser's
+ * session cookie authenticates, and the session can expire under the user.
+ * `onUnauthorized` is where the app signs in again; its answer decides
+ * whether the refused request is sent once more.
+ *
+ * So that it runs anywhere, this example replaces `fetch` with a small
+ * stand-in for the server, whose session expires on demand. It needs no
+ * instance and writes nothing; in a browser, delete the stand-in.
+ *
+ * node examples/09-browser-session.ts
+ */
+import { AgilityApiClient, ApiError } from "@versionone/agility-sdk";
+
+// ---- the stand-in server: a session that can expire, and a log of what ran ----
+let session = true;
+const ran: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL, init: RequestInit = {}) => {
+ const path = new URL(String(input)).pathname.replace("/MyInstance", "");
+ const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+ if (!session) return json({ error: "session expired" }, 401); // refused before anything ran
+ ran.push(`${init.method ?? "GET"} ${path}`);
+ if (path === "/loc-2.v1") return json({ "AssetType'Story": "Story" });
+ if (path === "/api/asset") return json({ requestId: "example", createdDate: "", completedDate: "", duration: "", durationSeconds: 0, commandFailures: { commands: [], count: 0 }, assetsCreated: { oidTokens: [], count: 0 }, assetsModified: { oidTokens: ["Story:1"], count: 1 }, assetsOperatedOn: { oidTokens: [], count: 0 }, queryResult: { results: [], count: 0 } });
+ return json({}, 404);
+}) as typeof fetch;
+
+// ---- the app ----
+let signIns = 0;
+async function signInAgain(): Promise {
+ // In an app: a silent refresh, or a sign-in dialog the user completes.
+ signIns += 1;
+ session = true;
+ return true;
+}
+
+const client = new AgilityApiClient({
+ baseUrl: "https://agility.example.com/MyInstance",
+ credentials: "include", // send the session cookie; no accessToken
+ onUnauthorized: async ({ retryable }) => {
+ if (!(await signInAgain())) return "fail";
+ // "retry" resends what is safe to send twice: a read, a GET, a guarded
+ // batch with no creates. `retryable` says whether this request is one.
+ if (retryable) return "retry";
+ // A plain write is never resent by "retry": if it ran before the
+ // refusal, sending it again would apply it twice. "retry-write" resends
+ // it anyway, and is YOUR assertion that on your server a refusal for an
+ // expired session means nothing in the request was executed. Answer it
+ // only if you know that; otherwise answer "fail" and let the user retry.
+ return "retry-write";
+ }
+});
+
+// A read while the session is good.
+console.log(await client.localize(["AssetType'Story"]));
+
+// The session expires. The next read is refused, the hook signs in again,
+// and the read is sent once more: the caller never sees the refusal.
+session = false;
+console.log(await client.localize(["AssetType'Story"]), `after ${signIns} sign-in`);
+
+// It expires again, under a write. With "retry-write" the write is resent.
+session = false;
+const outcome = await client.send([{ from: "Story:1", update: { Estimate: 3 } }]);
+console.log(`modified ${outcome.modified.join(", ")} after ${signIns} sign-ins; the server ran: ${ran.join(" | ")}`);
+
+// A hook that cannot sign in answers "fail", and the caller gets the
+// refusal: an ApiError of kind "auth".
+session = false;
+const strict = new AgilityApiClient({ baseUrl: "https://agility.example.com/MyInstance", credentials: "include", onUnauthorized: () => "fail" });
+try {
+ await strict.localize(["AssetType'Story"]);
+} catch (error) {
+ if (!(error instanceof ApiError)) throw error;
+ console.log(`not signed in: kind ${error.kind}, status ${error.status}`);
+}
diff --git a/examples/README.md b/examples/README.md
new file mode 100644
index 0000000..0bc28d5
--- /dev/null
+++ b/examples/README.md
@@ -0,0 +1,53 @@
+# Examples
+
+Nine short programs, one per task, each runnable as it stands. Read them
+in order; each says at the top what it does.
+
+| File | Shows | Writes? |
+| --- | --- | --- |
+| `01-read.ts` | Typed rows, relations and paths, a page with its total, one asset by OID, `me()` | no |
+| `02-write.ts` | `client.send`: create, update, an operation, the `Outcome`, `unmatched` | yes |
+| `03-guarded-write.ts` | `client.sendGuarded`: write only if nobody changed it; a conflict as data and as an error | yes |
+| `04-batch-undo.ts` | `client.batch.run` with a preview, a confirmation and a receipt; `batch.reversible` to undo | yes |
+| `05-errors.ts` | `kind` on everything thrown; `client.explain` says a failure to a person | no |
+| `06-attachments.ts` | Add a file, list, read it back in one request, remove it | yes |
+| `07-testing.ts` | `FakeAgilityClient`: test your own code with no instance | no instance at all |
+| `08-custom-transport.ts` | A `Transport` of your own (a timed wrapper), checked with `transportConformance` | no; a live read only if an instance is set |
+| `09-browser-session.ts` | Cookie auth for a browser app: `credentials`, `onUnauthorized`, and when `"retry-write"` is yours to answer | no instance at all (a stand-in server) |
+
+## Running one
+
+In this repository (Node 22.18 or later runs a `.ts` file directly):
+
+```bash
+npm install # builds dist/, which the examples import by the package's name
+export V1_URL=https://agility.example.com/MyInstance
+export V1_ACCESS_TOKEN=…
+node examples/01-read.ts
+```
+
+In a project of your own, `npm install @versionone/agility-sdk@alpha`, copy
+a file and run it the same way; the imports are already the ones a consumer
+writes.
+
+## The ones that write
+
+An example marked "yes" creates what it needs (a Story or two in the system
+scope, named `sdk-integration example …`), and deletes it by exact OID
+before it ends, whether it succeeded or not. It still refuses to start
+until you say the instance is one where that is acceptable:
+
+```bash
+V1_EXAMPLES_WRITE=1 node examples/02-write.ts
+```
+
+Use a development or testing instance, never one people work in.
+
+## Keeping them true
+
+`npm run typecheck` compiles every example against the source, so an API
+change that breaks one fails before it is pushed. The integration tier
+(`test/integration/examples.test.ts`) runs each one against an instance and
+fails if it exits non-zero or takes more than thirty seconds. A new example
+is a new numbered file here and a row in the table above; nothing else
+needs registering.
diff --git a/test/integration/assetApi.test.ts b/test/integration/assetApi.test.ts
index daf1942..82802f0 100644
--- a/test/integration/assetApi.test.ts
+++ b/test/integration/assetApi.test.ts
@@ -4,7 +4,7 @@ import { CommandFailureError } from "../../src/wire/assetApi";
import type { Member } from "../../src/types/assets/Member";
import type { Story } from "../../src/types/assets/Story";
import { assetApi } from "../../src/wire";
-import { describeInstance, fixtureName, instance } from "./instance";
+import { deleteFixtures, describeInstance, fixtureName, instance } from "./instance";
/**
* The api/asset wire module against a real instance: what the fakes cannot
@@ -15,8 +15,7 @@ describeInstance("assetApi (live)", () => {
const name = fixtureName("story");
const created: string[] = [];
afterAll(async () => {
- if (!created.length) return;
- await assetApi.send(t, created.map((oid) => ({ from: oid, execute: "Delete" })));
+ await deleteFixtures(t, created);
});
it("a create with a Ref relation is written as an OID token, the read-back speaks the model's shape, and results are positional", async () => {
diff --git a/test/integration/attachments.test.ts b/test/integration/attachments.test.ts
index d80d76f..25ed699 100644
--- a/test/integration/attachments.test.ts
+++ b/test/integration/attachments.test.ts
@@ -1,7 +1,7 @@
import { afterAll, beforeAll, expect, it } from "vitest";
import { AgilityApiClient } from "../../src/client";
import { assetApi } from "../../src/wire";
-import { describeInstance, fixtureName, instance } from "./instance";
+import { deleteFixtures, describeInstance, fixtureName, instance } from "./instance";
/**
* Attachments against a real instance: add inline and in two steps, list,
@@ -26,7 +26,7 @@ describeInstance("attachments (live)", () => {
made.push(story);
});
afterAll(async () => {
- for (const oid of [...made].reverse()) await assetApi.send(t, [{ from: oid, execute: "Delete" }]);
+ await deleteFixtures(t, [...made].reverse());
});
it("a small file inline and a large one in two steps both store their bytes; list sees both, metadata only", async () => {
diff --git a/test/integration/batch.test.ts b/test/integration/batch.test.ts
index 8a83a8a..7d563b8 100644
--- a/test/integration/batch.test.ts
+++ b/test/integration/batch.test.ts
@@ -1,7 +1,7 @@
import { afterAll, beforeAll, expect, it } from "vitest";
import { AgilityApiClient } from "../../src/client";
import { assetApi } from "../../src/wire";
-import { describeInstance, fixtureName, instance } from "./instance";
+import { deleteFixtures, describeInstance, fixtureName, instance } from "./instance";
/**
* batch against a real instance, round trip: a batch that updates two
@@ -27,7 +27,7 @@ describeInstance("batch (live)", () => {
created.push(a, b);
});
afterAll(async () => {
- for (const oid of created) await assetApi.send(t, [{ from: oid, execute: "Delete" }]);
+ await deleteFixtures(t, created);
});
it("a guarded batch's receipt names what it created and touched, and its reverse puts everything back", async () => {
diff --git a/test/integration/customFields.test.ts b/test/integration/customFields.test.ts
index ab5f380..4c8d2a6 100644
--- a/test/integration/customFields.test.ts
+++ b/test/integration/customFields.test.ts
@@ -4,7 +4,7 @@ import { Schema } from "../../src/services/schema";
import type { Story } from "../../src/types/assets/Story";
import { assetApi } from "../../src/wire";
import { createCustomFields, customTokenOf, deleteCustomFields, findCustomField } from "./customFields";
-import { describeLocalInstance, fixtureName, instance } from "./instance";
+import { deleteFixtures, describeLocalInstance, fixtureName, instance } from "./instance";
/**
* Custom attributes end to end: definitions created through the classic
@@ -26,7 +26,7 @@ describeLocalInstance("custom fields (live, via the classic UI gadget)", () => {
}, SLOW);
afterAll(async () => {
- if (created.length) await assetApi.send(t, created.map((oid) => ({ from: oid, execute: "Delete" })));
+ await deleteFixtures(t, created);
await deleteCustomFields(t, [numeric, flag]);
expect(await findCustomField(t, numeric)).toBeNull();
}, SLOW);
diff --git a/test/integration/examples.test.ts b/test/integration/examples.test.ts
new file mode 100644
index 0000000..d74e825
--- /dev/null
+++ b/test/integration/examples.test.ts
@@ -0,0 +1,42 @@
+import { spawnSync } from "node:child_process";
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { describeInstance, instance } from "./instance";
+
+/**
+ * Every file in examples/ runs as a consumer would run it (plain `node`,
+ * importing the built package by name), exits 0, and takes well under a
+ * minute. This is what keeps the examples true: an API change that breaks
+ * one fails here, and `npm run typecheck` compiles them on every push.
+ *
+ * The examples read V1_URL and V1_ACCESS_TOKEN, so the suite needs the
+ * instance as a URL and a token (it skips for a profile with a password),
+ * a build in dist/, and a Node that runs TypeScript files directly.
+ */
+const root = join(import.meta.dirname, "..", "..");
+const examples = readdirSync(join(root, "examples")).filter((f) => /^\d\d-.*\.ts$/.test(f)).sort();
+const token = process.env.SDK_TEST_URL ? process.env.SDK_TEST_ACCESS_TOKEN : process.env.V1_ACCESS_TOKEN;
+const built = existsSync(join(root, "dist", "index.js")) && existsSync(join(root, "dist", "testing.js"));
+const runsTypeScript = Boolean((process.features as { typescript?: unknown }).typescript);
+const why = !token ? "needs the instance as SDK_TEST_URL + SDK_TEST_ACCESS_TOKEN or V1_URL + V1_ACCESS_TOKEN" : !built ? "run `npm run build` first" : !runsTypeScript ? "this Node does not run .ts files" : null;
+
+describeInstance("examples (live)", () => {
+ it("there are examples to run", () => expect(examples.length).toBeGreaterThan(0));
+
+ for (const file of examples) {
+ it.skipIf(why !== null)(`${file} runs to the end${why ? ` [skipped: ${why}]` : ""}`, () => {
+ const started = Date.now();
+ const run = spawnSync(process.execPath, [join("examples", file)], {
+ cwd: root,
+ encoding: "utf8",
+ timeout: 60_000,
+ env: { ...process.env, V1_URL: instance!.url, V1_ACCESS_TOKEN: token!, V1_EXAMPLES_WRITE: "1" }
+ });
+ // The output goes into the failure message, minus where it ran.
+ const output = `${run.stdout}\n${run.stderr}`.split(instance!.url).join("");
+ expect(run.status, output).toBe(0);
+ expect(Date.now() - started).toBeLessThan(30_000);
+ }, 65_000);
+ }
+});
diff --git a/test/integration/guard.test.ts b/test/integration/guard.test.ts
index 31abd1f..7dfdd52 100644
--- a/test/integration/guard.test.ts
+++ b/test/integration/guard.test.ts
@@ -1,7 +1,7 @@
import { afterAll, beforeAll, expect, it } from "vitest";
import { ConflictError, sendGuarded } from "../../src/services/guard";
import { assetApi } from "../../src/wire";
-import { describeInstance, fixtureName, instance } from "./instance";
+import { deleteFixtures, describeInstance, fixtureName, instance } from "./instance";
/**
* The guard against a real instance. Brings its own Stories (deleted
@@ -25,7 +25,7 @@ describeInstance("guard (live)", () => {
[a, b] = res.assetsCreated.oidTokens.map(assetApi.momentless) as [string, string];
created.push(a, b);
});
- afterAll(async () => { for (const oid of created) await assetApi.send(t, [{ from: oid, execute: "Delete" }]); });
+ afterAll(() => deleteFixtures(t, created));
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.
diff --git a/test/integration/instance.ts b/test/integration/instance.ts
index 2d32d97..5ec5c45 100644
--- a/test/integration/instance.ts
+++ b/test/integration/instance.ts
@@ -25,6 +25,7 @@ import { join } from "node:path";
import { describe } from "vitest";
import { createFetchTransport } from "../../src/core/fetchTransport";
import type { Transport } from "../../src/core/transport";
+import { send } from "../../src/wire/assetApi";
import { apiTestInstances, isHosted, permitted, trim } from "./instanceGuard";
export interface Instance {
@@ -85,3 +86,22 @@ export const describeLocalInstance: typeof describe = ((name: string, fn: () =>
/** A fixture name nobody will mistake for real data, unique per run. */
export const fixtureName = (what: string): string => `sdk-integration ${what} ${new Date().toISOString().replace(/[:.]/g, "-")}`;
+
+/**
+ * Deletes a suite's fixtures by exact OID, in the order given, and throws
+ * if any is still there: a fixture left behind is a failure, not a shrug.
+ * Agility refuses to delete a closed asset, so one that would not delete
+ * is reactivated and deleted again. An asset already gone is fine (the
+ * server answers a command for it with success).
+ */
+export async function deleteFixtures(transport: Transport, oids: readonly string[]): Promise {
+ const left: string[] = [];
+ for (const oid of oids) {
+ const first = await send(transport, [{ from: oid, execute: "Delete" }]);
+ if (!first.commandFailures?.count) continue;
+ const second = await send(transport, [{ from: oid, execute: "Reactivate" }, { from: oid, execute: "Delete" }]);
+ const failed = second.commandFailures?.commands ?? [];
+ if (failed.some((c) => JSON.stringify(c).includes("Delete"))) left.push(`${oid}: ${JSON.stringify(failed.at(-1)?.error)}`);
+ }
+ if (left.length) throw new Error(`fixtures left behind:\n${left.join("\n")}`);
+}
diff --git a/test/integration/resolve.test.ts b/test/integration/resolve.test.ts
index af82d1e..e56df20 100644
--- a/test/integration/resolve.test.ts
+++ b/test/integration/resolve.test.ts
@@ -1,7 +1,7 @@
import { afterAll, beforeAll, expect, it } from "vitest";
import { AgilityApiClient } from "../../src/client";
import { assetApi } from "../../src/wire";
-import { describeInstance, fixtureName, instance } from "./instance";
+import { deleteFixtures, describeInstance, fixtureName, instance } from "./instance";
/**
* resolve against a real instance. Brings its own data: a Story (resolved
@@ -28,7 +28,7 @@ describeInstance("resolve (live)", () => {
issue = { oid: assetApi.momentless(i!._oid), number: i!.Number };
});
afterAll(async () => {
- for (const oid of created) await assetApi.send(t, [{ from: oid, execute: "Delete" }]);
+ await deleteFixtures(t, created);
});
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 () => {
diff --git a/test/integration/schema.test.ts b/test/integration/schema.test.ts
index b2f9989..f5687b8 100644
--- a/test/integration/schema.test.ts
+++ b/test/integration/schema.test.ts
@@ -3,7 +3,7 @@ import { AgilityApiClient } from "../../src/client";
import { Schema } from "../../src/services/schema";
import type { Story } from "../../src/types/assets/Story";
import { assetApi } from "../../src/wire";
-import { describeInstance, fixtureName, instance } from "./instance";
+import { deleteFixtures, describeInstance, fixtureName, instance } from "./instance";
/**
* The schema service and schema-driven translation against a real
@@ -32,7 +32,7 @@ describeInstance("schema (live)", () => {
afterAll(async () => {
// Children before parents; the status last, once nothing points at it.
const order = (oid: string) => (oid.startsWith("Task:") ? 0 : oid.startsWith("Story:") ? 1 : 2);
- for (const oid of [...created].sort((a, b) => order(a) - order(b))) await assetApi.send(t, [{ from: oid, execute: "Delete" }]);
+ await deleteFixtures(t, [...created].sort((a, b) => order(a) - order(b)));
});
it("loads a type from meta.v1 once, and a type the instance does not have is null — the expect-zero control", async () => {
diff --git a/tsconfig.json b/tsconfig.json
index 755f2f9..0a6cca1 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -15,8 +15,12 @@
"resolveJsonModule": true,
"verbatimModuleSyntax": true,
"outDir": "dist",
- "types": ["node", "vitest/globals"]
+ "types": ["node", "vitest/globals"],
+ "paths": {
+ "@versionone/agility-sdk": ["./src/index.ts"],
+ "@versionone/agility-sdk/testing": ["./src/testing/index.ts"]
+ }
},
- "include": ["src", "test", "vitest.config.ts", "tsup.config.ts"],
+ "include": ["src", "test", "examples", "vitest.config.ts", "tsup.config.ts"],
"exclude": ["dist", "node_modules"]
}
\ No newline at end of file