openvibers/openvibe.sdk Commits

0.53.0: openvibe-sdk/inventory, the network-wide inventory in the SDK (kinds, definitions, what people own and wear, equip, issuers' grants, consume and revoke) (#64)

OP OpenVibers committed 24 days ago · dc28728fc5 · 17 files, +260 −13

Changes

ddiff --git a/CHANGELOG.md b/CHANGELOG.md
iindex eab3a90..281ba8e 100644
---- a/CHANGELOG.md
++++ b/CHANGELOG.md
@@@ -3,6 +3,16 @@
All notable changes to `openvibe-sdk`. The package follows semver; while it is `0.x`, a minor
release may change an API and says so here.
++## 0.53.0 (2026-10-20)
++
++- **`openvibe-sdk/inventory`**: OpenVibe.Inventory through the SDK, as the owner asked of it ("cross site network wide
++ shared multi purpose modular system … through sdk / api"). `createInventoryClient(client)` covers its `/api/v1`: the
++ public reads (`kinds`, `definitions`, a person's `items` and `equipped`, `equipped([subjects])` for up to 100 at once),
++ the person's own (`me.items`, `me.equip`, `instance_id: null` clears a slot), and an issuer's (`definitions.create` /
++ `update`, `grants.create` → `{ instance, created }`, `instances.consume` / `revoke`). A grant is retried safely: its
++ body's `idempotency_key` is what Inventory dedupes on. `forPerson(usr_…)` is the same client sending `X-OV-Subject`
++ for a service acting for a person. Ids are checked against Inventory's own rules before any call.
++
## 0.52.0 (2026-10-20)
- **`openvibe-sdk/live`**: OpenVibe.Live in the SDK, its flagship product had no module. `createLiveClient(client)`
ddiff --git a/README.md b/README.md
iindex 34fe947..a1ce00b 100644
---- a/README.md
++++ b/README.md
@@@ -2,14 +2,14 @@
> Supported browser and server clients for the OpenVibe platform.
--**Status:** alpha, v0.52.0 (roadmap Wave 2; developer apps from Wave 20; Media objects v2 from Wave 4; the Tools platform API; Search, Chat and AI clients from WS-F task 4; per-actor limits from WS-R task 4). Every release is tagged (see [CHANGELOG.md](CHANGELOG.md)). Tested against local stub servers and the built-in mock platform only, never against the live platform. Services pin release tags; each repository's `STATUS.json` names the one it uses.
++**Status:** alpha, v0.53.0 (roadmap Wave 2; developer apps from Wave 20; Media objects v2 from Wave 4; the Tools platform API; Search, Chat and AI clients from WS-F task 4; per-actor limits from WS-R task 4). Every release is tagged (see [CHANGELOG.md](CHANGELOG.md)). Tested against local stub servers and the built-in mock platform only, never against the live platform. Services pin release tags; each repository's `STATUS.json` names the one it uses.
**Plan:** OpenVibe End-to-End Realignment & Implementation Plan, revision 3 (20 Sep 2026), §3.2; roadmap §30.
**License:** MIT ([LICENSE](LICENSE)). This package is a library that apps outside the network embed, so it uses MIT. The OpenVibe services themselves stay AGPL-3.0.
**If a capability is not in the SDK, it is not public.** Apps call services through `openvibe-sdk` and never build internal routes themselves. A route with no SDK wrapper is internal, even when you can reach it, and it can change without notice. To make a capability public, first define it in OpenVibe.Contracts, then wrap it here.
```bash
--npm install https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.52.0
++npm install https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.53.0
```
It has no runtime dependencies. It needs Node ≥ 20, or any browser with `fetch`, Web Crypto and `TextDecoder`. There is no build step. The package is CommonJS with ESM entry points (`import` works). Each subpath has its own `.d.ts`. For a page with no bundler, `browser/openvibe-sdk.mjs` is one self-contained ES module of the browser-safe subpaths (see [Browser without a bundler](#browser-without-a-bundler)). It does not depend on `openvibe-contracts` at runtime: it copies the contract types it uses (from Contracts v0.86.0, a devDependency the tests check them against).
@@@ -188,6 +188,7 @@ Until OpenVibe.Tools serves the gateway facade (Tools S6), point the jobs client
| `openvibe-sdk/download` | server | `createDownloadClient({ key })`: OpenVibe.Download, a person's drive — `files.list/all/get/remove`, `folders.list/create/ensurePath(path)`, `upload({ path \| data, name, folderId })` in parts, `usage()`, and `sync(dir, { to, delete, dryRun, exclude })` backups. The `openvibe-download` command: `sync <folder> --to <drive/path>`, `ls`, `usage` (`OPENVIBE_DOWNLOAD_KEY`, a sync key from openvibe.download/sync) |
| `openvibe-sdk/quest` | server | `createQuestClient(client)`: `appQuests.define(slug, {title, why?, steps: [{event_type, count, label}], badge: {name}, url?})`, `appQuests.list()`, `appQuests.retire(slug)` with an app token (audience `openvibe.quest`, `quest.app_quest.manage`); `eventType(projectId, name)` gives the `app.<project_key>.<name>` type to publish at Events. Badges only, never OpenCoins; production events count |
| `openvibe-sdk/live` | server | `createLiveClient(client)`: OpenVibe.Live's documented routes. `streams.list/get/recentlyOnline/mine/update/end/heartbeat/endpoint`, `slots.list/create/update/remove/regenerateKey` (a slot is a saved setup with its own stream key), `goLive(slotId, {title, category, tags})` → `{ stream, endpoint }`, `channels.get/mine/update/toggleFollow/url`, `content.feed/moments({type, sort, window, cursor, limit})`; WHIP: `whip.url(streamKey)`, `whip.publish(url, offerSdp, {key?})` → `{ answer, location }` (the client's own token never goes to `/whip`), `whip.end(location)`. Writes are never retried |
++| `openvibe-sdk/inventory` | server | `createInventoryClient(client)`: OpenVibe.Inventory, the network-wide inventory (ADR-054). Public reads: `kinds.list/get`, `definitions.list({kind, issuer})/get`, `people.items(subject)`, `people.equipped(subject)`, `equipped([subjects])` (≤ 100, for chat renders). The person's own: `me.items()`, `me.equip({kind, slot, instance_id | null})`. An issuer's: `definitions.create/update`, `grants.create({definition_id, subject, idempotency_key})` → `{ instance, created }` (retry-safe on the key), `instances.consume/revoke`. `forPerson(usr_…)` sends `X-OV-Subject` for a service acting for a person. Audience `openvibe.inventory` |
| `openvibe-sdk/vip` | server | `createVipClient({baseUrl?, tokenClient \| getToken, fetch?, timeoutMs?})`: `evaluate({subject, resource, owner, fallback, mode})`, `checkEntitlement({subject, creator, product, mode})`, `isMember(subject, creator)`; every failure is a denial. `createVipCache({vip, ttlMs, denyTtlMs, unavailableTtlMs})`: `entitlement`, `peekEntitlement`, `evaluate`, `invalidate`, `handleEvent` (`vip.membership.changed` and Billing's entitlement events drop a member's answers at once), `clear`, `bounds` |
| `openvibe-sdk/usage` | server | `usageSample(fields)` builds a `platform.usage-sample@1` record (required `id`, `idempotency_key`, `service`, `operation`, `quantity`, `unit`; `at` defaults to now ISO, `source` to `openvibe-sdk/usage`; null fields stripped; money fields never invented); `usageKey(service, ...parts)` joins an idempotency key with `:`; `validateUsageSample(record)` → `{ok, errors}` (openvibe-contracts, required lazily). `createUsageReporter({ db, service, source, table, billingUrl, tokenClient, audience, requireProject, ... })` owns one service's readings: `key(...parts)`/`sample(fields)`, and `record(t, reading)` queues the reading idempotency-keyed in the outbox inside the caller's transaction, relayed to Billing's `billing.usage.record` with backoff (a retry is never dropped; only Billing refusing the reading itself — any 4xx but 401/403/404/408/425/429, which stay pending — marks a row rejected; a 401 drops the cached token). The reporter bills whatever reading it is given: never record first-party or sandbox traffic (pass `requireProject: true` to refuse a reading without a `prj_…` project). `openvibe-sdk/govern` builds its `onUsage` record with it |
| `openvibe-sdk/commerce` | server | `createCommerceClient(config, {caps, fetchImpl?, tokenClients?, timeoutMs?})`: the Billing client Tips and VIP share. `config` = `{billing: {url, audience, timeoutMs = 10000}, network: {internalUrl}, oauth: {clientId, clientSecret}}`; `caps` maps `intent`, `transfer`, `subscription`, `entitlement` (and optional `rates`, default `entitlement`) to capability strings, one lazily created `serviceAuth` token client per distinct string (`scope` = the string) unless `tokenClients` supplies one, keyed by logical key or capability. Methods: `createIntent` (`kind` purchase with `bits`, or subscription with `creator`/`tier`/`autoRenew`), `createTransfer`, `refundTransfer`, `subscribeWithCredit` (`tier`), `cancelSubscription`, `getSubscription`, `listSubscriptions`, `entitlement`, `rates`, `listTiers(creator)` and `setTier({creator, tier, priceCents, status?, key})` (a creator's tier prices, kept by Billing; optional `caps.tier` = `billing.tier.manage`, which `setTier` needs), `baseUrl`. `Idempotency-Key` is sent verbatim; a 401 invalidates the token and retries once with the same key; problem+json becomes `CommerceError` (`status`, `code`, `body`, `retryable`). `intentKey(prefix, parts)` joins the parts that are set; `receipt(kind, fields)` → `{kind, at, ...fields}` (null stripped, never posted). `openvibe-contracts` is required lazily |
ddiff --git a/STATUS.json b/STATUS.json
iindex f62d93a..41764da 100644
---- a/STATUS.json
++++ b/STATUS.json
@@@ -3,7 +3,7 @@
"stage": "alpha",
"code": true,
"wave": "W2",
-- "version": "0.52.0",
++ "version": "0.53.0",
"plan": "OpenVibe End-to-End Realignment & Implementation Plan, revision 3 (20 Sep 2026), §3.2; roadmap §30",
"deployed": false,
"deployment": "none: a package released as git tags; services and apps pin a tag",
ddiff --git a/browser/openvibe-sdk.mjs b/browser/openvibe-sdk.mjs
iindex a720d4a..e824a19 100644
---- a/browser/openvibe-sdk.mjs
++++ b/browser/openvibe-sdk.mjs
@@@ -1,4 +1,4 @@
--// Generated by scripts/browser-bundle.js from browser.js (openvibe-sdk 0.52.0, MIT). Do not edit.
++// Generated by scripts/browser-bundle.js from browser.js (openvibe-sdk 0.53.0, MIT). Do not edit.
// One self-contained ES module: core at the top level plus the browser-safe subpaths as namespaces
// (auth, registry, modules, realtime, media, community, bot, search, chat, ai, jobs, tools, projects, geo). No server-only code: no service tokens, JWT verification, events, identity.
/* eslint-disable */
@@@ -42,7 +42,7 @@ const { paginate, offsetPager } = __load(7);
const semver = __load(6);
/** The package version (test/version.test.js keeps it equal to package.json). */
--const SDK_VERSION = '0.52.0';
++const SDK_VERSION = '0.53.0';
module.exports = {
createClient,
ddiff --git a/esm/index.mjs b/esm/index.mjs
iindex 1e5afeb..8fe52e9 100644
---- a/esm/index.mjs
++++ b/esm/index.mjs
@@@ -8,7 +8,7 @@ export const {
registry, identity, modules, events, realtime, media,
community, bot, search, chat, ai, jobs,
tools, projects, resources, vip, quest, live,
-- play, download, openre, geo, usage, commerce,
-- telemetry,
++ inventory, play, download, openre, geo, usage,
++ commerce, telemetry,
} = cjs;
export default cjs;
ddiff --git a/esm/inventory.mjs b/esm/inventory.mjs
nnew file mode 100644
iindex 0000000..9541a7e
---- /dev/null
++++ b/esm/inventory.mjs
@@@ -0,0 +1,7 @@
++// Generated by scripts/esm.js from src/inventory.js. Do not edit.
++import cjs from '../src/inventory.js';
++
++export const {
++ createInventoryClient,
++} = cjs;
++export default cjs;
ddiff --git a/index.js b/index.js
iindex 9e421bd..4b09ec3 100644
---- a/index.js
++++ b/index.js
@@@ -27,6 +27,7 @@ module.exports = {
vip: require('./src/vip'),
quest: require('./src/quest'),
live: require('./src/live'),
++ inventory: require('./src/inventory'),
play: require('./src/play'),
download: require('./src/download'),
openre: require('./src/openre'),
ddiff --git a/package-lock.json b/package-lock.json
iindex 912caf8..cc20373 100644
---- a/package-lock.json
++++ b/package-lock.json
@@@ -1,12 +1,12 @@
{
"name": "openvibe-sdk",
-- "version": "0.52.0",
++ "version": "0.53.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openvibe-sdk",
-- "version": "0.52.0",
++ "version": "0.53.0",
"license": "MIT",
"bin": {
"openvibe-download": "bin/openvibe-download.js"
ddiff --git a/package.json b/package.json
iindex ceb3be2..cadc23d 100644
---- a/package.json
++++ b/package.json
@@@ -1,6 +1,6 @@
{
"name": "openvibe-sdk",
-- "version": "0.52.0",
++ "version": "0.53.0",
"description": "Supported browser and server clients for the OpenVibe platform: auth (incl. developer apps), registry discovery, identity, user modules, events, realtime, media, community, Bot robots, search, chat, AI runs, Tools (registry, run API and jobs), VIP memberships and developer projects, the async PostgreSQL data layer (db) and the Valkey cache, limits store, queue and pub/sub, with deadlines, safe retries, problem errors and trace propagation.",
"main": "index.js",
"types": "types/index.d.ts",
@@@ -260,6 +260,12 @@
"import": "./esm/live.mjs",
"default": "./src/live.js"
},
++ "./inventory": {
++ "types": "./types/inventory.d.ts",
++ "browser": null,
++ "import": "./esm/inventory.mjs",
++ "default": "./src/inventory.js"
++ },
"./vip": {
"types": "./types/vip.d.ts",
"browser": null,
ddiff --git a/scripts/esm.js b/scripts/esm.js
iindex f70cc83..3665114 100644
---- a/scripts/esm.js
++++ b/scripts/esm.js
@@@ -56,6 +56,7 @@ const ENTRIES = {
'download.mjs': '../src/download.js',
'quest.mjs': '../src/quest.js',
'live.mjs': '../src/live.js',
++ 'inventory.mjs': '../src/inventory.js',
'vip.mjs': '../src/vip.js',
'frame.mjs': '../src/frame.js',
'service.mjs': '../src/service/index.js',
ddiff --git a/src/core/index.js b/src/core/index.js
iindex cee4e62..3bfea17 100644
---- a/src/core/index.js
++++ b/src/core/index.js
@@@ -8,7 +8,7 @@ const { paginate, offsetPager } = require('./paginate');
const semver = require('./semver');
/** The package version (test/version.test.js keeps it equal to package.json). */
--const SDK_VERSION = '0.52.0';
++const SDK_VERSION = '0.53.0';
module.exports = {
createClient,
ddiff --git a/src/inventory.js b/src/inventory.js
nnew file mode 100644
iindex 0000000..d664a74
---- /dev/null
++++ b/src/inventory.js
@@@ -0,0 +1,95 @@
++'use strict';
++/**
++ * openvibe-sdk/inventory — OpenVibe.Inventory, the network-wide inventory (ADR-054): kinds, item definitions, what
++ * people own and wear, and, for an item's issuer, granting, consuming and revoking. The owner's ask (2026-10-08): "cross
++ * site network wide shared multi purpose modular system … through sdk / api". Sites, games and apps define their items
++ * here and render what people wear anywhere. Tokens are for audience openvibe.inventory.
++ *
++ * const inv = createInventoryClient(createClient({ tokenProvider }));
++ * const { kinds } = await inv.kinds.list(); // public
++ * const { equipped } = await inv.equipped(['usr_01…', 'usr_02…']); // up to 100, for chat renders
++ * const { definition } = await inv.definitions.create({ kind: 'game:mygame.badge', name: 'First Win', rarity: 'common', art: { emoji: '🏆' } });
++ * await inv.grants.create({ definition_id: definition.id, subject: 'usr_01…', idempotency_key: `win-${matchId}` });
++ * await inv.forPerson('usr_01…').me.equip({ kind: 'live.hat', slot: 'head', instance_id: 'inv_01…' }); // a service acting for a person
++ *
++ * Only a kind's issuer defines and grants its items (or a grantor it names on one item). A grant is idempotent per
++ * idempotency_key: the same key returns the first instance with created: false. Nothing is sold, bought or traded.
++ * Errors are OpenVibeError: inventory.supply_exhausted (409), inventory.unknown_kind, inventory.bad_slot,
++ * inventory.subject_required, capability.denied, …
++ */
++const enc = encodeURIComponent;
++const SUBJECT_RE = /^usr_[0-9A-HJKMNP-TV-Z]{26}$/;
++const ID_RE = { definition: /^itd_[0-9A-HJKMNP-TV-Z]{26}$/, instance: /^inv_[0-9A-HJKMNP-TV-Z]{26}$/ }; // Inventory's own rules
++
++function createInventoryClient(client, { baseUrl, subject } = {}) {
++ if (!client || typeof client.json !== 'function') throw new TypeError('createInventoryClient: pass an openvibe-sdk/core client');
++ if (subject != null && !SUBJECT_RE.test(String(subject))) throw new TypeError('createInventoryClient: subject is a usr_ subject id');
++ const at = { service: 'inventory', baseUrl, audience: 'openvibe.inventory' };
++ // A service acting for a person names them (X-OV-Subject); a person's own token needs nothing.
++ const headers = subject ? { 'X-OV-Subject': String(subject) } : undefined;
++ const call = (opts) => client.json({ ...at, ...(headers ? { headers } : {}), ...opts });
++ const check = (re, v, what) => {
++ if (!re.test(String(v || ''))) throw new TypeError(`inventory: ${what}`);
++ return enc(String(v));
++ };
++ const person = (s) => check(SUBJECT_RE, s, 'a person is a usr_ subject id');
++
++ const kinds = {
++ /** Every kind: its schema, slots and the surfaces that render it. */
++ list: ({ signal } = {}) => call({ path: '/api/v1/kinds', signal }),
++ get: (kindId, { signal } = {}) => call({ path: `/api/v1/kinds/${enc(String(kindId))}`, signal }),
++ };
++ const definitions = {
++ /** Published items, by kind and/or issuer. */
++ list: ({ kind, issuer, limit, signal } = {}) => call({ path: '/api/v1/definitions', query: { kind, issuer, limit }, signal }),
++ get: (id, { signal } = {}) => call({ path: `/api/v1/definitions/${check(ID_RE.definition, id, 'a definition is an itd_ id')}`, signal }),
++ /** Define an item of a kind you issue (inventory.definition-request@1). Rarity, attributes and the cap are fixed once published. */
++ create: (definition, { signal } = {}) => call({ method: 'POST', path: '/api/v1/definitions', json: definition, idempotencyKey: false, signal }),
++ update: (id, patch, { signal } = {}) => call({ method: 'PATCH', path: `/api/v1/definitions/${check(ID_RE.definition, id, 'a definition is an itd_ id')}`, json: patch, signal }),
++ };
++ const people = {
++ /** A person's owned items (public), newest first: { items, next }. */
++ items: (s, { kind, cursor, limit, signal } = {}) => call({ path: `/api/v1/people/${person(s)}/items`, query: { kind, cursor, limit }, signal }),
++ /** What a person wears: { subject, slots: { '<kind>:<slot>': { instance_id, definition_id, token?, media_id? } } }. */
++ equipped: (s, { signal } = {}) => call({ path: `/api/v1/people/${person(s)}/equipped`, signal }),
++ };
++ /** Up to 100 people's equipped sets in one call (what chat renders use). */
++ const equipped = (subjects, { signal } = {}) => {
++ const list = [...new Set((subjects || []).map(String))];
++ if (list.length > 100) throw new TypeError('inventory.equipped: at most 100 subjects per call');
++ list.forEach(person);
++ return call({ path: '/api/v1/equipped', query: { subjects: list.join(',') }, signal });
++ };
++ const me = {
++ /** The caller's own items, every state (owned, consumed, revoked). */
++ items: ({ kind, cursor, limit, signal } = {}) => call({ path: '/api/v1/me/items', query: { kind, cursor, limit }, signal }),
++ /** Wear an item in a slot, or clear the slot with instance_id: null (inventory.equip-request@1). */
++ equip: ({ kind, slot, instance_id: instanceId }, { signal } = {}) => {
++ if (instanceId !== null) check(ID_RE.instance, instanceId, 'instance_id is an inv_ id, or null to clear the slot');
++ return call({ method: 'PUT', path: '/api/v1/me/equipped', json: { kind, slot, instance_id: instanceId }, signal });
++ },
++ };
++ const grants = {
++ /** Give a person one of your items → { instance, created }. idempotency_key (8–128 characters) makes a retry safe. */
++ create: ({ definition_id: def, subject: to, idempotency_key: key, ...rest }, { signal } = {}) => {
++ check(ID_RE.definition, def, 'definition_id is an itd_ id');
++ person(to);
++ if (typeof key !== 'string' || key.length < 8 || key.length > 128) throw new TypeError('inventory.grants.create: idempotency_key is 8 to 128 characters');
++ // The body's own key is what Inventory dedupes on, so the call may be retried safely.
++ return call({ method: 'POST', path: '/api/v1/grants', json: { ...rest, definition_id: def, subject: to, idempotency_key: key }, idempotent: true, signal });
++ },
++ };
++ const instances = {
++ /** Use up an instance you issued (a ticket, a one-time item). */
++ consume: (id, { signal } = {}) => call({ method: 'POST', path: `/api/v1/instances/${check(ID_RE.instance, id, 'an instance is an inv_ id')}/consume`, idempotencyKey: false, signal }),
++ /** Take one back, with a reason the ledger keeps. */
++ revoke: (id, { reason, signal } = {}) => call({ method: 'POST', path: `/api/v1/instances/${check(ID_RE.instance, id, 'an instance is an inv_ id')}/revoke`, json: reason ? { reason: String(reason) } : {}, idempotencyKey: false, signal }),
++ };
++ return {
++ kinds, definitions, people, equipped, me, grants, instances,
++ /** The same client acting for one person (sends X-OV-Subject): for a service that holds the route's capability. */
++ forPerson: (s) => createInventoryClient(client, { baseUrl, subject: s }),
++ };
++}
++
++module.exports = { createInventoryClient };
ddiff --git a/test/browser-entries.test.js b/test/browser-entries.test.js
iindex c6e709e..0d2b188 100644
---- a/test/browser-entries.test.js
++++ b/test/browser-entries.test.js
@@@ -76,7 +76,7 @@ run([
for (const [re, why] of FORBIDDEN) if (re.test(src)) problems.push(`${path.relative(ROOT, file)}: ${why}`);
}
assert.deepEqual(problems, []);
-- assert.deepEqual(blocked.sort(), ['./account-data', './cache', './commerce', './cost', './db', './delivery', './download', './events', './govern', './identity', './limits', './live', './node', './notifications', './openre', './placement', './play', './pubsub', './quest', './queue', './resources', './runtime', './service', './sso', './storage', './telemetry', './testing', './usage', './valkey', './vip']);
++ assert.deepEqual(blocked.sort(), ['./account-data', './cache', './commerce', './cost', './db', './delivery', './download', './events', './govern', './identity', './inventory', './limits', './live', './node', './notifications', './openre', './placement', './play', './pubsub', './quest', './queue', './resources', './runtime', './service', './sso', './storage', './telemetry', './testing', './usage', './valkey', './vip']);
const rel = [...scanned].map((f) => path.relative(ROOT, f));
for (const must of ['browser.js', 'src/core/client.js', 'src/auth/browser.js', 'src/realtime.js', 'src/media.js', 'src/community.js', 'src/bot.js', 'src/modules.js', 'src/registry.js', 'src/jobs.js', 'src/tools.js', 'src/core/form.js', 'src/projects.js', 'browser/openvibe-sdk.mjs']) {
assert.ok(rel.includes(must), `${must} is scanned`);
ddiff --git a/test/inventory.test.js b/test/inventory.test.js
nnew file mode 100644
iindex 0000000..65325da
---- /dev/null
++++ b/test/inventory.test.js
@@@ -0,0 +1,90 @@
++'use strict';
++// openvibe-sdk/inventory: OpenVibe.Inventory's /api/v1 (ADR-054) through a real core client against a local stub: the
++// public reads, the person's own items and equip, an issuer's definitions, grants (retry-safe on the body's own key),
++// consume and revoke, a service acting for a person (X-OV-Subject), and the id checks done before any call.
++const assert = require('assert');
++const http = require('http');
++const { createClient } = require('../src/core');
++const { createInventoryClient } = require('../src/inventory');
++
++(async () => {
++ const seen = [];
++ let grantAttempts = 0;
++ const server = http.createServer((req, res) => {
++ let body = '';
++ req.on('data', (c) => { body += c; });
++ req.on('end', () => {
++ seen.push({ method: req.method, url: req.url, subject: req.headers['x-ov-subject'] || null, idem: req.headers['idempotency-key'] || null, body: body ? JSON.parse(body) : null });
++ const json = (status, obj) => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(obj)); };
++ if (req.url === '/api/v1/grants') {
++ grantAttempts++;
++ if (grantAttempts === 1) return json(503, { type: 'about:blank', title: 'busy', status: 503 }); // retried: the body's key makes it safe
++ return json(201, { instance: { id: 'inv_01JAB2C3D4E5F6G7H8J9K0MNPQ' }, created: true });
++ }
++ if (req.url === '/api/v1/definitions' && req.method === 'POST') return json(409, { type: 'about:blank', title: 'exhausted', status: 409, code: 'inventory.supply_exhausted' });
++ return json(200, { ok: true });
++ });
++ });
++ await new Promise((r) => server.listen(0, '127.0.0.1', r));
++ const base = `http://127.0.0.1:${server.address().port}`;
++ const client = createClient({ baseUrls: { inventory: base }, token: 'tok', retries: 2, retryDelayMs: 1, maxRetryDelayMs: 2 });
++ const inv = createInventoryClient(client);
++ const U1 = 'usr_01JAB2C3D4E5F6G7H8J9K0MNPQ', U2 = 'usr_01JAB2C3D4E5F6G7H8J9K0MNPR';
++ const DEF = 'itd_01JAB2C3D4E5F6G7H8J9K0MNPQ', INST = 'inv_01JAB2C3D4E5F6G7H8J9K0MNPQ';
++
++ try {
++ await inv.kinds.list();
++ await inv.kinds.get('live.hat');
++ await inv.definitions.list({ kind: 'live.hat', issuer: 'service:live' });
++ await inv.definitions.get(DEF);
++ await inv.people.items(U1, { kind: 'live.hat', limit: 10 });
++ await inv.people.equipped(U1);
++ await inv.equipped([U1, U2, U1]);
++ await inv.me.items({ cursor: 'c1' });
++ await inv.me.equip({ kind: 'live.hat', slot: 'head', instance_id: INST });
++ await inv.me.equip({ kind: 'live.hat', slot: 'head', instance_id: null });
++ await inv.definitions.update(DEF, { name: 'Renamed' });
++ await inv.instances.consume(INST);
++ await inv.instances.revoke(INST, { reason: 'refund' });
++ assert.deepStrictEqual(seen.map((s) => `${s.method} ${s.url}`), [
++ 'GET /api/v1/kinds', 'GET /api/v1/kinds/live.hat', 'GET /api/v1/definitions?kind=live.hat&issuer=service%3Alive',
++ `GET /api/v1/definitions/${DEF}`, `GET /api/v1/people/${U1}/items?kind=live.hat&limit=10`, `GET /api/v1/people/${U1}/equipped`,
++ `GET /api/v1/equipped?subjects=${U1}%2C${U2}`, 'GET /api/v1/me/items?cursor=c1', 'PUT /api/v1/me/equipped', 'PUT /api/v1/me/equipped',
++ `PATCH /api/v1/definitions/${DEF}`, `POST /api/v1/instances/${INST}/consume`, `POST /api/v1/instances/${INST}/revoke`,
++ ]);
++ assert.deepStrictEqual(seen[8].body, { kind: 'live.hat', slot: 'head', instance_id: INST });
++ assert.deepStrictEqual(seen[9].body, { kind: 'live.hat', slot: 'head', instance_id: null }, 'null clears the slot');
++ assert.deepStrictEqual(seen[12].body, { reason: 'refund' });
++ assert.ok(seen.every((s) => s.subject === null), 'a person\'s own client names nobody');
++
++ // Grants: the body's idempotency_key makes a retry safe, so a 503 is retried and the item is granted once.
++ seen.length = 0;
++ const out = await inv.grants.create({ definition_id: DEF, subject: U1, idempotency_key: 'win-match-42' });
++ assert.deepStrictEqual(out, { instance: { id: INST }, created: true });
++ assert.strictEqual(seen.length, 2, 'retried once');
++ assert.deepStrictEqual(seen[1].body, { definition_id: DEF, subject: U1, idempotency_key: 'win-match-42' });
++ assert.throws(() => inv.grants.create({ definition_id: DEF, subject: U1, idempotency_key: 'short' }), /8 to 128/);
++ assert.throws(() => inv.grants.create({ definition_id: 'itd_bad', subject: U1, idempotency_key: 'win-match-42' }), /itd_/);
++
++ // A new definition is never retried on its own, and Inventory's code reaches the error.
++ seen.length = 0;
++ await assert.rejects(inv.definitions.create({ kind: 'game:x.badge', name: 'First Win' }), (err) => err.status === 409 && err.code === 'inventory.supply_exhausted');
++ assert.strictEqual(seen.length, 1);
++ assert.strictEqual(seen[0].idem, null);
++
++ // A service acting for a person.
++ seen.length = 0;
++ await inv.forPerson(U2).me.equip({ kind: 'live.hat', slot: 'head', instance_id: INST });
++ assert.strictEqual(seen[0].subject, U2);
++ assert.throws(() => inv.forPerson('someone'), /usr_/);
++
++ // Checks before any call.
++ assert.throws(() => inv.people.items('../admin'), /usr_/);
++ assert.throws(() => inv.equipped(Array.from({ length: 101 }, (_, i) => `usr_01JAB2C3D4E5F6G7H8J9K0M${String(i).padStart(3, '0').replace(/[^0-9A-HJKMNP-TV-Z]/g, 'A')}`)), /100/);
++ assert.throws(() => inv.me.equip({ kind: 'live.hat', slot: 'head', instance_id: 'x' }), /inv_/);
++ assert.throws(() => createInventoryClient({}), /core client/);
++ console.log('inventory: all checks passed');
++ } finally {
++ server.close();
++ }
++})().catch((err) => { console.error(err); process.exit(1); });
ddiff --git a/test/pack.test.js b/test/pack.test.js
iindex 5bb7855..0506d50 100644
---- a/test/pack.test.js
++++ b/test/pack.test.js
@@@ -66,7 +66,7 @@ run([
})().catch((err) => { console.error(err); process.exit(1); });`;
const res = execFileSync(process.execPath, ['-e', script], { cwd: app, encoding: 'utf8' });
assert.match(res, new RegExp(`consumer ok: ${subpaths.length} subpaths \\+ the browser bundle`));
-- assert.equal(subpaths.length, 48);
++ assert.equal(subpaths.length, 49);
assert.ok(!fs.existsSync(path.join(app, 'node_modules/openvibe-contracts')), 'the optional peer is not installed');
} finally {
fs.rmSync(tmp, { recursive: true, force: true });
ddiff --git a/types/index.d.ts b/types/index.d.ts
iindex 7ea7f61..93b76a8 100644
---- a/types/index.d.ts
++++ b/types/index.d.ts
@@@ -18,6 +18,7 @@ export * as resources from './resources';
export * as vip from './vip';
export * as quest from './quest';
export * as live from './live';
++export * as inventory from './inventory';
export * as play from './play';
export * as download from './download';
export * as openre from './openre';
ddiff --git a/types/inventory.d.ts b/types/inventory.d.ts
nnew file mode 100644
iindex 0000000..020b759
---- /dev/null
++++ b/types/inventory.d.ts
@@@ -0,0 +1,35 @@
++/** openvibe-sdk/inventory: OpenVibe.Inventory — kinds, item definitions, what people own and wear, and issuers' grants (ADR-054). */
++type Opts = { signal?: AbortSignal };
++export type Rarity = 'common' | 'uncommon' | 'rare' | 'epic' | 'legendary';
++export interface Kind { id: string; name?: string; slots: string[]; surfaces?: string[]; schema?: Record<string, unknown>; [k: string]: unknown }
++export interface Definition {
++ id: string; kind: string; name: string; description?: string | null; rarity: Rarity; issuer: string;
++ art?: { media_id?: string; token?: string; emoji?: string }; attributes?: Record<string, unknown>; supply_cap?: number | null;
++ status?: 'draft' | 'in_review' | 'published' | 'retired'; [k: string]: unknown;
++}
++export interface DefinitionRequest { kind: string; name: string; description?: string; rarity?: Rarity; art?: Definition['art']; attributes?: Record<string, unknown>; supply_cap?: number; [k: string]: unknown }
++export interface Instance { id: string; definition_id: string; owner_subject?: string; state?: 'owned' | 'consumed' | 'revoked'; serial?: number | null; [k: string]: unknown }
++export interface EquippedSet { subject: string; slots: Record<string, { instance_id: string; definition_id: string; token?: string; media_id?: string }>; updated_at: string | null }
++export interface InventoryClient {
++ kinds: { list(opts?: Opts): Promise<{ kinds: Kind[] }>; get(kindId: string, opts?: Opts): Promise<{ kind: Kind }> };
++ definitions: {
++ list(opts?: Opts & { kind?: string; issuer?: string; limit?: number }): Promise<{ definitions: Definition[] }>;
++ get(id: string, opts?: Opts): Promise<{ definition: Definition }>;
++ create(definition: DefinitionRequest, opts?: Opts): Promise<{ definition: Definition }>;
++ update(id: string, patch: Partial<DefinitionRequest>, opts?: Opts): Promise<{ definition: Definition }>;
++ };
++ people: {
++ items(subject: string, opts?: Opts & { kind?: string; cursor?: string; limit?: number }): Promise<{ items: Instance[]; next: string | null; [k: string]: unknown }>;
++ equipped(subject: string, opts?: Opts): Promise<EquippedSet>;
++ };
++ equipped(subjects: string[], opts?: Opts): Promise<{ equipped: EquippedSet[] }>;
++ me: {
++ items(opts?: Opts & { kind?: string; cursor?: string; limit?: number }): Promise<{ items: Instance[]; next: string | null; [k: string]: unknown }>;
++ equip(req: { kind: string; slot: string; instance_id: string | null }, opts?: Opts): Promise<EquippedSet>;
++ };
++ grants: { create(req: { definition_id: string; subject: string; idempotency_key: string; [k: string]: unknown }, opts?: Opts): Promise<{ instance: Instance; created: boolean }> };
++ instances: { consume(id: string, opts?: Opts): Promise<{ instance: Instance }>; revoke(id: string, opts?: Opts & { reason?: string }): Promise<{ instance: Instance }> };
++ /** The same client acting for one person (sends X-OV-Subject). */
++ forPerson(subject: string): InventoryClient;
++}
++export function createInventoryClient(client: { json(opts: Record<string, unknown>): Promise<any> }, options?: { baseUrl?: string; subject?: string }): InventoryClient;