@onlyworlds/sdk 2.2.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -529,12 +529,12 @@ var FIELD_SCHEMA = {
529
529
  subtype: { type: "text", required: false },
530
530
  image_url: { type: "text", required: false },
531
531
  // Details
532
- map: { type: "single_link", target: "map" },
533
- zone: { type: "single_link", target: "zone" },
534
- x: { type: "number" },
535
- y: { type: "number" },
532
+ map: { type: "single_link", target: "map", required: true },
533
+ zone: { type: "single_link", target: "zone", required: true },
534
+ x: { type: "number", required: true },
535
+ y: { type: "number", required: true },
536
536
  z: { type: "number" },
537
- order: { type: "number" }
537
+ order: { type: "number", required: true }
538
538
  },
539
539
  narrative: {
540
540
  // Base fields (shared by all elements)
@@ -627,13 +627,13 @@ var FIELD_SCHEMA = {
627
627
  subtype: { type: "text", required: false },
628
628
  image_url: { type: "text", required: false },
629
629
  // Details
630
- map: { type: "single_link", target: "map" },
631
- element_type: { type: "text" },
632
- // ElementType enum value
633
- element_id: { type: "single_link", target: "any" },
630
+ map: { type: "single_link", target: "map", required: true },
631
+ element_type: { type: "text", required: true },
632
+ // ElementType enum value; YAML 'element' generic-link is split into _type + _id
633
+ element_id: { type: "single_link", target: "any", required: true },
634
634
  // Can reference any element
635
- x: { type: "number" },
636
- y: { type: "number" },
635
+ x: { type: "number", required: true },
636
+ y: { type: "number", required: true },
637
637
  z: { type: "number" }
638
638
  },
639
639
  relation: {
@@ -1190,19 +1190,343 @@ function getElementIcon(type) {
1190
1190
  }
1191
1191
  return "help_outline";
1192
1192
  }
1193
+
1194
+ // src/v2/errors.ts
1195
+ var OwApiError = class extends Error {
1196
+ constructor(status, code, message, docUrl, detail, type = null, param = null) {
1197
+ super(message);
1198
+ this.name = "OwApiError";
1199
+ this.status = status;
1200
+ this.code = code;
1201
+ this.type = type;
1202
+ this.param = param;
1203
+ this.docUrl = docUrl;
1204
+ this.detail = detail;
1205
+ }
1206
+ get isAuthError() {
1207
+ return this.code === "invalid_credentials" || this.code === "key_revoked" || this.code === "world_gone";
1208
+ }
1209
+ /** 422s/400s name the offending param/field -- typos error loudly platform-wide. */
1210
+ get isValidationError() {
1211
+ return this.status === 422 || this.status === 400;
1212
+ }
1213
+ /** Same Idempotency-Key replayed with a different payload. */
1214
+ get isIdempotencyConflict() {
1215
+ return this.status === 409;
1216
+ }
1217
+ };
1218
+ var OwNetworkError = class extends Error {
1219
+ constructor(message, cause) {
1220
+ super(message);
1221
+ this.name = "OwNetworkError";
1222
+ this.cause2 = cause;
1223
+ }
1224
+ };
1225
+ function parseEnvelope(status, body) {
1226
+ const env = body && typeof body === "object" ? body : {};
1227
+ const nested = typeof env.error === "object" && env.error !== null ? env.error : void 0;
1228
+ const code = env.code ?? nested?.code ?? (typeof env.error === "string" ? env.error : null) ?? null;
1229
+ const type = env.type ?? nested?.type ?? null;
1230
+ const param = env.param ?? nested?.param ?? null;
1231
+ const docUrl = env.doc_url ?? nested?.doc_url ?? null;
1232
+ const message = env.message ?? nested?.message ?? (typeof env.detail === "string" ? env.detail : void 0) ?? `OnlyWorlds API error ${status}${code ? ` (${code})` : ""}`;
1233
+ return new OwApiError(status, code, message, docUrl, body, type, param);
1234
+ }
1235
+ async function errorFromResponse(res) {
1236
+ let body = null;
1237
+ let text = "";
1238
+ try {
1239
+ text = await res.text();
1240
+ body = text ? JSON.parse(text) : null;
1241
+ } catch {
1242
+ body = text || null;
1243
+ }
1244
+ return parseEnvelope(res.status, body);
1245
+ }
1246
+
1247
+ // src/v2/keys.ts
1248
+ var LEGACY_RE = /^[0-9]{10}$/;
1249
+ function isDemoKey(key) {
1250
+ return LEGACY_RE.test(key) && key >= "0000000000" && key <= "0000000009";
1251
+ }
1252
+ function detectKeyKind(key) {
1253
+ if (key.startsWith("ow_w_")) return "write";
1254
+ if (key.startsWith("ow_r_")) return "read";
1255
+ if (key.startsWith("ow_a_")) return "account";
1256
+ if (LEGACY_RE.test(key)) return "legacy";
1257
+ return "unknown";
1258
+ }
1259
+ function kindCanWrite(kind) {
1260
+ return kind === "write" || kind === "legacy";
1261
+ }
1262
+ function pinExpectation(kind) {
1263
+ switch (kind) {
1264
+ case "read":
1265
+ return "never";
1266
+ case "account":
1267
+ return "never";
1268
+ case "write":
1269
+ return "optional";
1270
+ case "legacy":
1271
+ return "required-for-private-reads";
1272
+ default:
1273
+ return "optional";
1274
+ }
1275
+ }
1276
+
1277
+ // src/v2/client.ts
1278
+ var DEFAULT_BASE_URL = "https://www.onlyworlds.com/api/v2";
1279
+ var DEFAULT_PAGE_SIZE = 100;
1280
+ var DEFAULT_CHANGES_PAGE_SIZE = 100;
1281
+ var OwV2Client = class {
1282
+ constructor(config) {
1283
+ if (!config.apiKey) throw new Error("OwV2Client: apiKey is required");
1284
+ this.apiKey = config.apiKey;
1285
+ this.apiPin = config.apiPin || void 0;
1286
+ this.keyKind = detectKeyKind(config.apiKey);
1287
+ this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
1288
+ this.pageSize = config.pageSize ?? DEFAULT_PAGE_SIZE;
1289
+ this.changesPageSize = config.changesPageSize ?? DEFAULT_CHANGES_PAGE_SIZE;
1290
+ this.fetchImpl = config.fetch ?? globalThis.fetch.bind(globalThis);
1291
+ if (typeof this.fetchImpl !== "function") {
1292
+ throw new Error("OwV2Client: no fetch available -- supply config.fetch");
1293
+ }
1294
+ }
1295
+ // -- Health & world meta -------------------------------------------------
1296
+ /** GET /health -- unauthenticated liveness pulse. */
1297
+ async health() {
1298
+ return this.request("GET", "/health/", { auth: false });
1299
+ }
1300
+ /**
1301
+ * GET /world -- world meta (name, calendar/time fields, public_read).
1302
+ * GOTCHA (by server design): world-meta edits do NOT appear in /changes and
1303
+ * do not bump change_seq. Poll getWorld().updated_at for meta freshness.
1304
+ */
1305
+ async getWorld() {
1306
+ return this.request("GET", "/world/");
1307
+ }
1308
+ /** PATCH /world -- partial world-meta update. */
1309
+ async patchWorld(partial) {
1310
+ return this.request("PATCH", "/world/", { body: sanitizePayload(partial) });
1311
+ }
1312
+ // -- Element CRUD --------------------------------------------------------
1313
+ /** GET /{type}/ -- one cursor page. */
1314
+ async list(type, params = {}) {
1315
+ const query = buildQuery({
1316
+ limit: params.limit ?? this.pageSize,
1317
+ cursor: params.cursor,
1318
+ expand: params.expand?.join(","),
1319
+ fields: params.fields?.join(","),
1320
+ ...params.filter
1321
+ });
1322
+ return this.request("GET", `/${type}/`, { query });
1323
+ }
1324
+ /** Cursor-walk every page of a type. Politeness: uses config pageSize. */
1325
+ async *listAll(type, params = {}) {
1326
+ let cursor;
1327
+ do {
1328
+ const page = await this.list(type, { ...params, cursor });
1329
+ for (const el of page.data) yield el;
1330
+ cursor = page.has_more && page.next_cursor ? page.next_cursor : void 0;
1331
+ } while (cursor);
1332
+ }
1333
+ /** GET /{type}/{id}/ -- optional one-level stub expansion / sparse fields. */
1334
+ async get(type, id, opts = {}) {
1335
+ const query = buildQuery({ expand: opts.expand?.join(","), fields: opts.fields?.join(",") });
1336
+ return this.request("GET", `/${type}/${id}/`, { query });
1337
+ }
1338
+ /**
1339
+ * POST /{type}/ -- create. Mints an RFC-4122 UUID for element.id when the
1340
+ * caller omits one (design ruling D29d) so a retry carrying the same
1341
+ * Idempotency-Key is structurally safe. Callers MAY still supply their own id.
1342
+ */
1343
+ async create(type, element, opts = {}) {
1344
+ const body = sanitizePayload(element);
1345
+ if (body.id === void 0 || body.id === null || body.id === "") {
1346
+ body.id = mintUuid();
1347
+ }
1348
+ return this.request("POST", `/${type}/`, {
1349
+ body,
1350
+ idempotencyKey: opts.idempotencyKey
1351
+ });
1352
+ }
1353
+ /** PUT /{type}/{id}/ -- upsert-by-client-id. The local-first write primitive. */
1354
+ async upsert(type, id, element) {
1355
+ return this.request("PUT", `/${type}/${id}/`, { body: sanitizePayload(element) });
1356
+ }
1357
+ /**
1358
+ * PATCH /{type}/{id}/ -- partial update. DESTRUCTIVE on sent fields: arrays
1359
+ * replace wholesale, omitted fields stay untouched. For link arrays prefer
1360
+ * editLinks() -- atomic server-side merge, no read-before-write.
1361
+ */
1362
+ async patch(type, id, partial) {
1363
+ return this.request("PATCH", `/${type}/${id}/`, { body: sanitizePayload(partial) });
1364
+ }
1365
+ /**
1366
+ * DELETE /{type}/{id}/ -- idempotent (204 on absent). Server writes a
1367
+ * tombstone AND scrubs the id from every other element's links in the same
1368
+ * transaction -- no client-side unlink pass needed, ever.
1369
+ */
1370
+ async delete(type, id) {
1371
+ await this.request("DELETE", `/${type}/${id}/`, { allowEmpty: true });
1372
+ }
1373
+ /**
1374
+ * POST /{type}/{id}/links/{field} with {add, remove} -- atomic link merge.
1375
+ * Dedupes, tolerates already-present/already-absent ids. Returns the FULL
1376
+ * updated element (fixture P5). Use this for all relationship editing; it
1377
+ * retires the read-merge-PATCH dance.
1378
+ */
1379
+ async editLinks(type, id, field, edit) {
1380
+ return this.request("POST", `/${type}/${id}/links/${field}`, { body: edit });
1381
+ }
1382
+ // -- Bulk ----------------------------------------------------------------
1383
+ /**
1384
+ * POST /bulk -- up to ~1000 items. Partial success by default (HTTP 200
1385
+ * always; inspect per-slot numeric `status` + top-level `errors` flag);
1386
+ * atomic:true for all-or-nothing. Link validation runs against batch U
1387
+ * database -- send in any order, cycles included; no client topo-sort.
1388
+ * Success slots echo server-authoritative timestamps: set your sync baseline
1389
+ * from this response alone. When an idempotencyKey is replayed, the returned
1390
+ * response carries wasReplay:true (read from the Idempotent-Replay header).
1391
+ */
1392
+ async bulk(items, opts = {}) {
1393
+ const body = {
1394
+ items: items.map((it) => ({ type: it.type, element: sanitizePayload(it.element) })),
1395
+ atomic: opts.atomic ?? false
1396
+ };
1397
+ return this.request("POST", "/bulk/", {
1398
+ body,
1399
+ idempotencyKey: opts.idempotencyKey,
1400
+ replayAware: true
1401
+ });
1402
+ }
1403
+ // -- Changes feed --------------------------------------------------------
1404
+ /**
1405
+ * GET /changes -- one page of the world's ordered change feed.
1406
+ * Cursor is OPAQUE and never expires: persist verbatim, never parse.
1407
+ * Zero/absent cursor = full export (byte-aligned with the Folder Format).
1408
+ * Rewind rule: if your persisted position is ahead of page.head, the server
1409
+ * was restored -- re-baseline from cursor zero; do not assume caught-up.
1410
+ * Citizenship: heaviest route on the platform; default page size is polite.
1411
+ */
1412
+ async changes(opts = {}) {
1413
+ const query = buildQuery({ since: opts.since, limit: opts.limit ?? this.changesPageSize });
1414
+ return this.request("GET", "/changes/", { query });
1415
+ }
1416
+ /**
1417
+ * Walk the feed from `since` (or from zero = full export) to the current
1418
+ * tail, yielding ops in order. Returns the final cursor via the generator's
1419
+ * return value; persist it for the next incremental pull.
1420
+ */
1421
+ async *changesAll(since) {
1422
+ let cursor = since;
1423
+ let page;
1424
+ do {
1425
+ page = await this.changes({ since: cursor });
1426
+ for (const op of page.changes) yield op;
1427
+ cursor = page.cursor;
1428
+ } while (page.has_more);
1429
+ return { cursor: page.cursor, head: page.head };
1430
+ }
1431
+ // -- Core request machinery ----------------------------------------------
1432
+ async request(method, path, opts = {}) {
1433
+ const url = `${this.baseUrl}${path}${opts.query ? `?${opts.query}` : ""}`;
1434
+ const headers = {};
1435
+ if (opts.auth !== false) {
1436
+ if (this.keyKind === "account") {
1437
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
1438
+ } else {
1439
+ headers["API-Key"] = this.apiKey;
1440
+ if (this.apiPin) headers["API-Pin"] = this.apiPin;
1441
+ }
1442
+ }
1443
+ if (opts.body !== void 0) headers["Content-Type"] = "application/json";
1444
+ if (opts.idempotencyKey) headers["Idempotency-Key"] = opts.idempotencyKey;
1445
+ let res;
1446
+ try {
1447
+ res = await this.fetchImpl(url, {
1448
+ method,
1449
+ headers,
1450
+ body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0
1451
+ });
1452
+ } catch (cause) {
1453
+ throw new OwNetworkError(`OnlyWorlds request failed: ${method} ${path}`, cause);
1454
+ }
1455
+ if (!res.ok) throw await errorFromResponse(res);
1456
+ if (res.status === 204 || opts.allowEmpty) {
1457
+ const text = await res.text();
1458
+ return text ? JSON.parse(text) : null;
1459
+ }
1460
+ const parsed = await res.json();
1461
+ if (opts.replayAware && parsed && typeof parsed === "object") {
1462
+ parsed.wasReplay = readReplayHeader(res.headers);
1463
+ }
1464
+ return parsed;
1465
+ }
1466
+ };
1467
+ var READ_ONLY_FIELDS = ["world", "type", "created_at", "updated_at", "change_seq"];
1468
+ function sanitizePayload(payload) {
1469
+ if (!payload || typeof payload !== "object") return payload;
1470
+ const rest = { ...payload };
1471
+ for (const field of READ_ONLY_FIELDS) delete rest[field];
1472
+ return rest;
1473
+ }
1474
+ function readReplayHeader(headers) {
1475
+ const v = headers.get("Idempotent-Replay");
1476
+ return v != null && v.toLowerCase() === "true";
1477
+ }
1478
+ function mintUuid() {
1479
+ const c = globalThis.crypto;
1480
+ if (c && typeof c.randomUUID === "function") return c.randomUUID();
1481
+ const bytes = new Uint8Array(16);
1482
+ if (c && typeof c.getRandomValues === "function") {
1483
+ c.getRandomValues(bytes);
1484
+ } else {
1485
+ for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
1486
+ }
1487
+ bytes[6] = bytes[6] & 15 | 64;
1488
+ bytes[8] = bytes[8] & 63 | 128;
1489
+ const hex = [];
1490
+ for (let i = 0; i < 256; i++) hex.push((i + 256).toString(16).slice(1));
1491
+ return hex[bytes[0]] + hex[bytes[1]] + hex[bytes[2]] + hex[bytes[3]] + "-" + hex[bytes[4]] + hex[bytes[5]] + "-" + hex[bytes[6]] + hex[bytes[7]] + "-" + hex[bytes[8]] + hex[bytes[9]] + "-" + hex[bytes[10]] + hex[bytes[11]] + hex[bytes[12]] + hex[bytes[13]] + hex[bytes[14]] + hex[bytes[15]];
1492
+ }
1493
+ function buildQuery(params) {
1494
+ const q = new URLSearchParams();
1495
+ for (const [k, v] of Object.entries(params)) {
1496
+ if (v !== void 0 && v !== null && v !== "") q.set(k, String(v));
1497
+ }
1498
+ return q.toString();
1499
+ }
1500
+
1501
+ // src/v2/types.generated.ts
1502
+ var ELEMENT_TYPES = ["ability", "character", "collective", "construct", "creature", "event", "family", "institution", "language", "law", "location", "map", "marker", "narrative", "object", "phenomenon", "pin", "relation", "species", "title", "trait", "zone"];
1503
+
1504
+ // src/v2/types.ts
1505
+ var SPATIAL_TYPES = ["map", "pin", "marker", "zone"];
1193
1506
  export {
1194
1507
  ELEMENT_ICONS,
1195
1508
  ELEMENT_LABELS,
1196
1509
  ELEMENT_SECTIONS,
1510
+ ELEMENT_TYPES,
1197
1511
  ElementType,
1198
1512
  FIELD_SCHEMA,
1199
1513
  GameTier,
1200
1514
  ONLYWORLDS_VERSION,
1201
1515
  OnlyWorldsClient,
1516
+ OwApiError,
1517
+ OwNetworkError,
1518
+ OwV2Client,
1519
+ SPATIAL_TYPES,
1202
1520
  createAnyElementId,
1203
1521
  createElementId,
1204
1522
  createElementIds,
1523
+ detectKeyKind,
1524
+ errorFromResponse,
1205
1525
  getElementIcon,
1206
1526
  getElementLabel,
1207
- getElementSections
1527
+ getElementSections,
1528
+ isDemoKey,
1529
+ kindCanWrite,
1530
+ parseEnvelope,
1531
+ pinExpectation
1208
1532
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onlyworlds/sdk",
3
- "version": "2.2.2",
3
+ "version": "3.0.0",
4
4
  "description": "TypeScript SDK for the OnlyWorlds API - build world-building applications with type safety",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -12,6 +12,8 @@
12
12
  "scripts": {
13
13
  "build": "tsup src/index.ts --format cjs,esm --dts --clean",
14
14
  "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
15
+ "pretest": "npm run build",
16
+ "test": "node --test \"test/**/*.test.mjs\"",
15
17
  "prepublishOnly": "npm run build"
16
18
  },
17
19
  "keywords": [