Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
```
Expand Down Expand Up @@ -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
Expand All @@ -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".
Expand Down
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
48 changes: 48 additions & 0 deletions examples/01-read.ts
Original file line number Diff line number Diff line change
@@ -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"])}`);
43 changes: 43 additions & 0 deletions examples/02-write.ts
Original file line number Diff line number Diff line change
@@ -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: "<p>written by an example</p>" } },
{ 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}`);
}
50 changes: 50 additions & 0 deletions examples/03-guarded-write.ts
Original file line number Diff line number Diff line change
@@ -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}`);
}
49 changes: 49 additions & 0 deletions examples/04-batch-undo.ts
Original file line number Diff line number Diff line change
@@ -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}`);
}
38 changes: 38 additions & 0 deletions examples/05-errors.ts
Original file line number Diff line number Diff line change
@@ -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<unknown>): Promise<void> => {
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}`);
38 changes: 38 additions & 0 deletions examples/06-attachments.ts
Original file line number Diff line number Diff line change
@@ -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`);
}
48 changes: 48 additions & 0 deletions examples/07-testing.ts
Original file line number Diff line number Diff line change
@@ -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<AgilityApiClient["sendGuarded"]>) => { 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");
Loading