@schematichq/schematic-js 1.5.0 → 1.6.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.
@@ -34,9 +34,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
34
34
  ));
35
35
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
36
 
37
- // node_modules/cross-fetch/dist/browser-polyfill.js
37
+ // node_modules/.pnpm/cross-fetch@4.1.0/node_modules/cross-fetch/dist/browser-polyfill.js
38
38
  var require_browser_polyfill = __commonJS({
39
- "node_modules/cross-fetch/dist/browser-polyfill.js"(exports) {
39
+ "node_modules/.pnpm/cross-fetch@4.1.0/node_modules/cross-fetch/dist/browser-polyfill.js"(exports) {
40
40
  (function(self2) {
41
41
  var irrelevant = (function(exports2) {
42
42
  var g = typeof globalThis !== "undefined" && globalThis || typeof self2 !== "undefined" && self2 || // eslint-disable-next-line no-undef
@@ -578,16 +578,28 @@ __export(index_exports, {
578
578
  CheckFlagsResponseFromJSON: () => CheckFlagsResponseFromJSON,
579
579
  CheckPlanReturnFromJSON: () => CheckPlanReturnFromJSON,
580
580
  CreditBalancesFromJSON: () => CreditBalancesFromJSON,
581
+ DEFAULT_INVOICE_QUERY: () => DEFAULT_INVOICE_QUERY,
581
582
  DatastreamCompanyPlanFromJSON: () => DatastreamCompanyPlanFromJSON,
582
583
  EventBodyFlagCheckToJSON: () => EventBodyFlagCheckToJSON,
584
+ INVOICE_MAX_PAGE_SIZE: () => INVOICE_MAX_PAGE_SIZE,
585
+ INVOICE_PAGE_SIZE: () => INVOICE_PAGE_SIZE,
586
+ InvoiceStatus: () => InvoiceStatus,
583
587
  RuleType: () => RuleType,
584
588
  Schematic: () => Schematic,
589
+ SchematicApiError: () => SchematicApiError,
590
+ SchematicBillingClient: () => SchematicBillingClient,
591
+ SchematicSession: () => SchematicSession,
592
+ TOKEN_CACHE_SIZE: () => TOKEN_CACHE_SIZE,
585
593
  TrialStatus: () => TrialStatus,
586
- UsagePeriod: () => UsagePeriod
594
+ UsagePeriod: () => UsagePeriod,
595
+ billingApi: () => models_exports,
596
+ fetchBillingData: () => fetchBillingData,
597
+ normalizeInvoiceQuery: () => normalizeInvoiceQuery,
598
+ sessionKey: () => sessionKey
587
599
  });
588
600
  module.exports = __toCommonJS(index_exports);
589
601
 
590
- // node_modules/uuid/dist/stringify.js
602
+ // node_modules/.pnpm/uuid@14.0.2/node_modules/uuid/dist/stringify.js
591
603
  var byteToHex = [];
592
604
  for (let i = 0; i < 256; ++i) {
593
605
  byteToHex.push((i + 256).toString(16).slice(1));
@@ -596,13 +608,13 @@ function unsafeStringify(arr, offset = 0) {
596
608
  return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
597
609
  }
598
610
 
599
- // node_modules/uuid/dist/rng.js
611
+ // node_modules/.pnpm/uuid@14.0.2/node_modules/uuid/dist/rng.js
600
612
  var rnds8 = new Uint8Array(16);
601
613
  function rng() {
602
614
  return crypto.getRandomValues(rnds8);
603
615
  }
604
616
 
605
- // node_modules/uuid/dist/v4.js
617
+ // node_modules/.pnpm/uuid@14.0.2/node_modules/uuid/dist/v4.js
606
618
  function v4(options, buf, offset) {
607
619
  if (!buf && !options && crypto.randomUUID) {
608
620
  return crypto.randomUUID();
@@ -650,6 +662,20 @@ function MetricPeriodMonthResetFromJSONTyped(json, ignoreDiscriminator) {
650
662
  return json;
651
663
  }
652
664
 
665
+ // src/types/api/models/WarningTier.ts
666
+ function WarningTierFromJSON(json) {
667
+ return WarningTierFromJSONTyped(json, false);
668
+ }
669
+ function WarningTierFromJSONTyped(json, ignoreDiscriminator) {
670
+ if (json == null) {
671
+ return json;
672
+ }
673
+ return {
674
+ key: json["key"],
675
+ value: json["value"]
676
+ };
677
+ }
678
+
653
679
  // src/types/api/models/MetricPeriod.ts
654
680
  function MetricPeriodFromJSON(json) {
655
681
  return MetricPeriodFromJSONTyped(json, false);
@@ -684,7 +710,8 @@ function FeatureEntitlementFromJSONTyped(json, ignoreDiscriminator) {
684
710
  monthReset: json["month_reset"] == null ? void 0 : MetricPeriodMonthResetFromJSON(json["month_reset"]),
685
711
  softLimit: json["soft_limit"] == null ? void 0 : json["soft_limit"],
686
712
  usage: json["usage"] == null ? void 0 : json["usage"],
687
- valueType: EntitlementValueTypeFromJSON(json["value_type"])
713
+ valueType: EntitlementValueTypeFromJSON(json["value_type"]),
714
+ warningTiers: json["warning_tiers"] == null ? void 0 : json["warning_tiers"].map(WarningTierFromJSON)
688
715
  };
689
716
  }
690
717
 
@@ -1074,6 +1101,7 @@ function EventBodyFlagCheckToJSONTyped(value, ignoreDiscriminator = false) {
1074
1101
  error: value["error"],
1075
1102
  flag_id: value["flagId"],
1076
1103
  flag_key: value["flagKey"],
1104
+ preflight: value["preflight"],
1077
1105
  reason: value["reason"],
1078
1106
  req_company: value["reqCompany"],
1079
1107
  req_user: value["reqUser"],
@@ -1195,7 +1223,590 @@ function contextString(context) {
1195
1223
  }
1196
1224
 
1197
1225
  // src/version.ts
1198
- var version = "1.5.0";
1226
+ var version = "1.6.0";
1227
+
1228
+ // src/billing/api/generated/models/index.ts
1229
+ var models_exports = {};
1230
+ __export(models_exports, {
1231
+ ApiErrorFromJSON: () => ApiErrorFromJSON,
1232
+ ApiErrorFromJSONTyped: () => ApiErrorFromJSONTyped,
1233
+ ApiErrorToJSON: () => ApiErrorToJSON,
1234
+ ApiErrorToJSONTyped: () => ApiErrorToJSONTyped,
1235
+ CompanyInvoiceResponseDataFromJSON: () => CompanyInvoiceResponseDataFromJSON,
1236
+ CompanyInvoiceResponseDataFromJSONTyped: () => CompanyInvoiceResponseDataFromJSONTyped,
1237
+ CompanyInvoiceResponseDataToJSON: () => CompanyInvoiceResponseDataToJSON,
1238
+ CompanyInvoiceResponseDataToJSONTyped: () => CompanyInvoiceResponseDataToJSONTyped,
1239
+ CompanyInvoicesResponseDataFromJSON: () => CompanyInvoicesResponseDataFromJSON,
1240
+ CompanyInvoicesResponseDataFromJSONTyped: () => CompanyInvoicesResponseDataFromJSONTyped,
1241
+ CompanyInvoicesResponseDataToJSON: () => CompanyInvoicesResponseDataToJSON,
1242
+ CompanyInvoicesResponseDataToJSONTyped: () => CompanyInvoicesResponseDataToJSONTyped,
1243
+ GetCompanyInvoicesParamsFromJSON: () => GetCompanyInvoicesParamsFromJSON,
1244
+ GetCompanyInvoicesParamsFromJSONTyped: () => GetCompanyInvoicesParamsFromJSONTyped,
1245
+ GetCompanyInvoicesParamsToJSON: () => GetCompanyInvoicesParamsToJSON,
1246
+ GetCompanyInvoicesParamsToJSONTyped: () => GetCompanyInvoicesParamsToJSONTyped,
1247
+ GetCompanyInvoicesResponseFromJSON: () => GetCompanyInvoicesResponseFromJSON,
1248
+ GetCompanyInvoicesResponseFromJSONTyped: () => GetCompanyInvoicesResponseFromJSONTyped,
1249
+ GetCompanyInvoicesResponseToJSON: () => GetCompanyInvoicesResponseToJSON,
1250
+ GetCompanyInvoicesResponseToJSONTyped: () => GetCompanyInvoicesResponseToJSONTyped,
1251
+ InvoiceStatus: () => InvoiceStatus,
1252
+ InvoiceStatusFromJSON: () => InvoiceStatusFromJSON,
1253
+ InvoiceStatusFromJSONTyped: () => InvoiceStatusFromJSONTyped,
1254
+ InvoiceStatusToJSON: () => InvoiceStatusToJSON,
1255
+ InvoiceStatusToJSONTyped: () => InvoiceStatusToJSONTyped,
1256
+ instanceOfApiError: () => instanceOfApiError,
1257
+ instanceOfCompanyInvoiceResponseData: () => instanceOfCompanyInvoiceResponseData,
1258
+ instanceOfCompanyInvoicesResponseData: () => instanceOfCompanyInvoicesResponseData,
1259
+ instanceOfGetCompanyInvoicesParams: () => instanceOfGetCompanyInvoicesParams,
1260
+ instanceOfGetCompanyInvoicesResponse: () => instanceOfGetCompanyInvoicesResponse,
1261
+ instanceOfInvoiceStatus: () => instanceOfInvoiceStatus
1262
+ });
1263
+
1264
+ // src/billing/api/generated/models/ApiError.ts
1265
+ function instanceOfApiError(value) {
1266
+ if (!("error" in value) || value["error"] === void 0) return false;
1267
+ return true;
1268
+ }
1269
+ function ApiErrorFromJSON(json) {
1270
+ return ApiErrorFromJSONTyped(json, false);
1271
+ }
1272
+ function ApiErrorFromJSONTyped(json, ignoreDiscriminator) {
1273
+ if (json == null) {
1274
+ return json;
1275
+ }
1276
+ return {
1277
+ error: json["error"]
1278
+ };
1279
+ }
1280
+ function ApiErrorToJSON(json) {
1281
+ return ApiErrorToJSONTyped(json, false);
1282
+ }
1283
+ function ApiErrorToJSONTyped(value, ignoreDiscriminator = false) {
1284
+ if (value == null) {
1285
+ return value;
1286
+ }
1287
+ return {
1288
+ error: value["error"]
1289
+ };
1290
+ }
1291
+
1292
+ // src/billing/api/generated/models/InvoiceStatus.ts
1293
+ var InvoiceStatus = {
1294
+ Draft: "draft",
1295
+ Open: "open",
1296
+ Paid: "paid",
1297
+ Uncollectible: "uncollectible",
1298
+ Void: "void"
1299
+ };
1300
+ function instanceOfInvoiceStatus(value) {
1301
+ for (const key in InvoiceStatus) {
1302
+ if (Object.prototype.hasOwnProperty.call(InvoiceStatus, key)) {
1303
+ if (InvoiceStatus[key] === value) {
1304
+ return true;
1305
+ }
1306
+ }
1307
+ }
1308
+ return false;
1309
+ }
1310
+ function InvoiceStatusFromJSON(json) {
1311
+ return InvoiceStatusFromJSONTyped(json, false);
1312
+ }
1313
+ function InvoiceStatusFromJSONTyped(json, ignoreDiscriminator) {
1314
+ return json;
1315
+ }
1316
+ function InvoiceStatusToJSON(value) {
1317
+ return value;
1318
+ }
1319
+ function InvoiceStatusToJSONTyped(value, ignoreDiscriminator) {
1320
+ return value;
1321
+ }
1322
+
1323
+ // src/billing/api/generated/models/CompanyInvoiceResponseData.ts
1324
+ function instanceOfCompanyInvoiceResponseData(value) {
1325
+ if (!("amountDue" in value) || value["amountDue"] === void 0) return false;
1326
+ if (!("createdAt" in value) || value["createdAt"] === void 0) return false;
1327
+ if (!("currency" in value) || value["currency"] === void 0) return false;
1328
+ if (!("id" in value) || value["id"] === void 0) return false;
1329
+ return true;
1330
+ }
1331
+ function CompanyInvoiceResponseDataFromJSON(json) {
1332
+ return CompanyInvoiceResponseDataFromJSONTyped(json, false);
1333
+ }
1334
+ function CompanyInvoiceResponseDataFromJSONTyped(json, ignoreDiscriminator) {
1335
+ if (json == null) {
1336
+ return json;
1337
+ }
1338
+ return {
1339
+ amountDue: json["amount_due"],
1340
+ createdAt: new Date(json["created_at"]),
1341
+ currency: json["currency"],
1342
+ dueDate: json["due_date"] == null ? void 0 : new Date(json["due_date"]),
1343
+ id: json["id"],
1344
+ status: json["status"] == null ? void 0 : InvoiceStatusFromJSON(json["status"]),
1345
+ url: json["url"] == null ? void 0 : json["url"]
1346
+ };
1347
+ }
1348
+ function CompanyInvoiceResponseDataToJSON(json) {
1349
+ return CompanyInvoiceResponseDataToJSONTyped(json, false);
1350
+ }
1351
+ function CompanyInvoiceResponseDataToJSONTyped(value, ignoreDiscriminator = false) {
1352
+ if (value == null) {
1353
+ return value;
1354
+ }
1355
+ return {
1356
+ amount_due: value["amountDue"],
1357
+ created_at: value["createdAt"].toISOString(),
1358
+ currency: value["currency"],
1359
+ due_date: value["dueDate"] == null ? void 0 : value["dueDate"].toISOString(),
1360
+ id: value["id"],
1361
+ status: InvoiceStatusToJSON(value["status"]),
1362
+ url: value["url"]
1363
+ };
1364
+ }
1365
+
1366
+ // src/billing/api/generated/models/CompanyInvoicesResponseData.ts
1367
+ function instanceOfCompanyInvoicesResponseData(value) {
1368
+ if (!("count" in value) || value["count"] === void 0) return false;
1369
+ if (!("invoices" in value) || value["invoices"] === void 0) return false;
1370
+ return true;
1371
+ }
1372
+ function CompanyInvoicesResponseDataFromJSON(json) {
1373
+ return CompanyInvoicesResponseDataFromJSONTyped(json, false);
1374
+ }
1375
+ function CompanyInvoicesResponseDataFromJSONTyped(json, ignoreDiscriminator) {
1376
+ if (json == null) {
1377
+ return json;
1378
+ }
1379
+ return {
1380
+ count: json["count"],
1381
+ invoices: json["invoices"].map(
1382
+ CompanyInvoiceResponseDataFromJSON
1383
+ )
1384
+ };
1385
+ }
1386
+ function CompanyInvoicesResponseDataToJSON(json) {
1387
+ return CompanyInvoicesResponseDataToJSONTyped(json, false);
1388
+ }
1389
+ function CompanyInvoicesResponseDataToJSONTyped(value, ignoreDiscriminator = false) {
1390
+ if (value == null) {
1391
+ return value;
1392
+ }
1393
+ return {
1394
+ count: value["count"],
1395
+ invoices: value["invoices"].map(
1396
+ CompanyInvoiceResponseDataToJSON
1397
+ )
1398
+ };
1399
+ }
1400
+
1401
+ // src/billing/api/generated/models/GetCompanyInvoicesParams.ts
1402
+ function instanceOfGetCompanyInvoicesParams(value) {
1403
+ return true;
1404
+ }
1405
+ function GetCompanyInvoicesParamsFromJSON(json) {
1406
+ return GetCompanyInvoicesParamsFromJSONTyped(json, false);
1407
+ }
1408
+ function GetCompanyInvoicesParamsFromJSONTyped(json, ignoreDiscriminator) {
1409
+ if (json == null) {
1410
+ return json;
1411
+ }
1412
+ return {
1413
+ includePending: json["include_pending"] == null ? void 0 : json["include_pending"],
1414
+ limit: json["limit"] == null ? void 0 : json["limit"],
1415
+ offset: json["offset"] == null ? void 0 : json["offset"]
1416
+ };
1417
+ }
1418
+ function GetCompanyInvoicesParamsToJSON(json) {
1419
+ return GetCompanyInvoicesParamsToJSONTyped(json, false);
1420
+ }
1421
+ function GetCompanyInvoicesParamsToJSONTyped(value, ignoreDiscriminator = false) {
1422
+ if (value == null) {
1423
+ return value;
1424
+ }
1425
+ return {
1426
+ include_pending: value["includePending"],
1427
+ limit: value["limit"],
1428
+ offset: value["offset"]
1429
+ };
1430
+ }
1431
+
1432
+ // src/billing/api/generated/models/GetCompanyInvoicesResponse.ts
1433
+ function instanceOfGetCompanyInvoicesResponse(value) {
1434
+ if (!("data" in value) || value["data"] === void 0) return false;
1435
+ if (!("params" in value) || value["params"] === void 0) return false;
1436
+ return true;
1437
+ }
1438
+ function GetCompanyInvoicesResponseFromJSON(json) {
1439
+ return GetCompanyInvoicesResponseFromJSONTyped(json, false);
1440
+ }
1441
+ function GetCompanyInvoicesResponseFromJSONTyped(json, ignoreDiscriminator) {
1442
+ if (json == null) {
1443
+ return json;
1444
+ }
1445
+ return {
1446
+ data: CompanyInvoicesResponseDataFromJSON(json["data"]),
1447
+ params: GetCompanyInvoicesParamsFromJSON(json["params"])
1448
+ };
1449
+ }
1450
+ function GetCompanyInvoicesResponseToJSON(json) {
1451
+ return GetCompanyInvoicesResponseToJSONTyped(json, false);
1452
+ }
1453
+ function GetCompanyInvoicesResponseToJSONTyped(value, ignoreDiscriminator = false) {
1454
+ if (value == null) {
1455
+ return value;
1456
+ }
1457
+ return {
1458
+ data: CompanyInvoicesResponseDataToJSON(value["data"]),
1459
+ params: GetCompanyInvoicesParamsToJSON(value["params"])
1460
+ };
1461
+ }
1462
+
1463
+ // src/billing/contract/invoices.ts
1464
+ var DEFAULT_INVOICE_QUERY = {};
1465
+ function normalizeInvoiceQuery(query) {
1466
+ const { includePending, ...rest } = query;
1467
+ return includePending === true ? { ...rest, includePending: true } : rest;
1468
+ }
1469
+
1470
+ // src/billing/session.ts
1471
+ var SchematicApiError = class extends Error {
1472
+ constructor(status, path, body) {
1473
+ super(
1474
+ typeof body === "object" && body !== null && "error" in body ? String(body.error) : `Request to ${path} failed with status ${status}`
1475
+ );
1476
+ this.status = status;
1477
+ this.path = path;
1478
+ this.body = body;
1479
+ this.name = "SchematicApiError";
1480
+ }
1481
+ status;
1482
+ path;
1483
+ body;
1484
+ };
1485
+ var DEFAULT_API_URL = "https://api.schematichq.com";
1486
+ var TOKEN_CACHE_SIZE = 10;
1487
+ function sessionKey(session) {
1488
+ return JSON.stringify([session.company, session.user ?? null]);
1489
+ }
1490
+ var SchematicSession = class {
1491
+ _apiUrl;
1492
+ _headers;
1493
+ _fetch;
1494
+ _session;
1495
+ _tokens = /* @__PURE__ */ new Map();
1496
+ _resolving = /* @__PURE__ */ new Map();
1497
+ /**
1498
+ * Bumped when the session's identity changes, and only then — the object
1499
+ * itself is replaced on every render. Anything asking "is this still the
1500
+ * session I started under?" counts generations rather than comparing.
1501
+ */
1502
+ _generation = 0;
1503
+ _listeners = /* @__PURE__ */ new Set();
1504
+ constructor(options = {}) {
1505
+ this._session = options.session;
1506
+ this._apiUrl = (options.apiUrl ?? DEFAULT_API_URL).replace(/\/$/, "");
1507
+ this._headers = options.additionalHeaders ?? {};
1508
+ this._fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
1509
+ }
1510
+ get key() {
1511
+ return this._session === null || this._session === void 0 ? void 0 : sessionKey(this._session);
1512
+ }
1513
+ get status() {
1514
+ if (this._session === void 0) {
1515
+ return "pending";
1516
+ }
1517
+ return this._session === null ? "ended" : "active";
1518
+ }
1519
+ /** Only a statement that changes which pair is read counts as a change. */
1520
+ set(session) {
1521
+ if (session === void 0) {
1522
+ return;
1523
+ }
1524
+ const previous = this._session;
1525
+ this._session = session;
1526
+ if (session === null) {
1527
+ if (previous === null) {
1528
+ return;
1529
+ }
1530
+ this._tokens.clear();
1531
+ this._resolving.clear();
1532
+ this._generation += 1;
1533
+ this._emit({ type: "ended" });
1534
+ return;
1535
+ }
1536
+ if (previous !== null && previous !== void 0) {
1537
+ if (previous.company === session.company && (previous.user ?? null) === (session.user ?? null)) {
1538
+ return;
1539
+ }
1540
+ this._generation += 1;
1541
+ this._emit({ type: "changed" });
1542
+ return;
1543
+ }
1544
+ this._generation += 1;
1545
+ this._emit({ type: "started" });
1546
+ }
1547
+ onChange(listener) {
1548
+ this._listeners.add(listener);
1549
+ return () => {
1550
+ this._listeners.delete(listener);
1551
+ };
1552
+ }
1553
+ _emit(event) {
1554
+ for (const listener of this._listeners) {
1555
+ listener(event);
1556
+ }
1557
+ }
1558
+ _cached(key) {
1559
+ const cached = this._tokens.get(key);
1560
+ if (cached === void 0) {
1561
+ return void 0;
1562
+ }
1563
+ if (cached.expiresAt !== void 0 && cached.expiresAt.getTime() <= Date.now()) {
1564
+ this._tokens.delete(key);
1565
+ return void 0;
1566
+ }
1567
+ this._tokens.delete(key);
1568
+ this._tokens.set(key, cached);
1569
+ return cached;
1570
+ }
1571
+ _cache(key, resolved) {
1572
+ this._tokens.delete(key);
1573
+ this._tokens.set(key, resolved);
1574
+ while (this._tokens.size > TOKEN_CACHE_SIZE) {
1575
+ const oldest = this._tokens.keys().next();
1576
+ if (oldest.done === true) {
1577
+ break;
1578
+ }
1579
+ this._tokens.delete(oldest.value);
1580
+ }
1581
+ }
1582
+ /**
1583
+ * The credential for a session, minted if this one is not held. `force`
1584
+ * retires what is held first: the caller is a request the API has just
1585
+ * rejected.
1586
+ */
1587
+ resolveToken(session, force) {
1588
+ const { token } = session;
1589
+ if (typeof token === "string") {
1590
+ return Promise.resolve(token);
1591
+ }
1592
+ const key = sessionKey(session);
1593
+ if (!force) {
1594
+ const cached = this._cached(key);
1595
+ if (cached !== void 0) {
1596
+ return Promise.resolve(cached.token);
1597
+ }
1598
+ } else {
1599
+ this._tokens.delete(key);
1600
+ }
1601
+ const inflight = this._resolving.get(key);
1602
+ if (inflight !== void 0 && inflight.sessionGeneration === this._generation && (!force || inflight.forced)) {
1603
+ return inflight.promise;
1604
+ }
1605
+ const provider = token;
1606
+ const sessionGeneration = this._generation;
1607
+ const owns = () => this._resolving.get(key)?.promise === promise;
1608
+ const promise = Promise.resolve().then(() => provider()).then((result) => {
1609
+ const { resolved, stamped } = asResolvedToken(result, session);
1610
+ if (owns() && (this._generation === sessionGeneration || stamped)) {
1611
+ this._cache(key, resolved);
1612
+ }
1613
+ return resolved.token;
1614
+ }).finally(() => {
1615
+ if (owns()) {
1616
+ this._resolving.delete(key);
1617
+ }
1618
+ });
1619
+ this._resolving.set(key, { promise, forced: force, sessionGeneration });
1620
+ return promise;
1621
+ }
1622
+ /**
1623
+ * Sends a request under the active session's credential, refreshing once
1624
+ * and retrying if the API rejects it. Rejects rather than answering when
1625
+ * the session changes while the request is in flight: the rows would
1626
+ * otherwise come back as the answer to a question asked for another pair.
1627
+ */
1628
+ async request(path, options = {}) {
1629
+ const { method = "GET", body } = options;
1630
+ const send = async (credential2) => this._fetch(`${this._apiUrl}${path}`, {
1631
+ method,
1632
+ headers: {
1633
+ "Accept": "application/json",
1634
+ ...body === void 0 ? {} : { "Content-Type": "application/json" },
1635
+ ...this._headers,
1636
+ "X-Schematic-Api-Key": credential2
1637
+ },
1638
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
1639
+ });
1640
+ const session = this._session;
1641
+ if (session === null) {
1642
+ throw new Error("There is no session to read data for.");
1643
+ }
1644
+ if (session === void 0) {
1645
+ throw new Error("A session is required to read data.");
1646
+ }
1647
+ const provider = session.token;
1648
+ const generation = this._generation;
1649
+ const stillOurs = async (response2) => {
1650
+ if (this._generation === generation) {
1651
+ return;
1652
+ }
1653
+ if (response2 !== void 0) {
1654
+ await discardBody(response2);
1655
+ }
1656
+ throw new Error("The session changed while this request was in flight.");
1657
+ };
1658
+ const credential = await this.resolveToken(session, false);
1659
+ if (this._generation !== generation) {
1660
+ throw new Error("The session changed before this request was sent.");
1661
+ }
1662
+ let response = await send(credential);
1663
+ await stillOurs(response);
1664
+ if (response.status === 401 && typeof provider === "function" && this._generation === generation) {
1665
+ const status = response.status;
1666
+ const rejected = await readBody(response);
1667
+ let retried = false;
1668
+ const current = this._session;
1669
+ if (this._generation === generation && current !== null && current !== void 0) {
1670
+ const refreshed = await this.resolveToken(current, true);
1671
+ if (this._generation === generation) {
1672
+ response = await send(refreshed);
1673
+ await stillOurs(response);
1674
+ retried = true;
1675
+ }
1676
+ }
1677
+ if (!retried) {
1678
+ throw new SchematicApiError(status, path, rejected);
1679
+ }
1680
+ }
1681
+ const parsed = await readBody(response);
1682
+ await stillOurs();
1683
+ if (!response.ok) {
1684
+ throw new SchematicApiError(response.status, path, parsed);
1685
+ }
1686
+ return parsed;
1687
+ }
1688
+ };
1689
+ function asResolvedToken(result, session) {
1690
+ if (typeof result === "string") {
1691
+ return { resolved: { token: result }, stamped: false };
1692
+ }
1693
+ const token = result?.token;
1694
+ if (typeof token !== "string" || token === "") {
1695
+ throw new Error("The access token provider did not return a token.");
1696
+ }
1697
+ if (result.company !== void 0 && result.company !== session.company || result.user !== void 0 && session.user !== void 0 && result.user !== session.user) {
1698
+ throw new Error(
1699
+ "The access token provider returned a token for a different session."
1700
+ );
1701
+ }
1702
+ const stamped = result.company !== void 0 && (session.user === void 0 || result.user !== void 0);
1703
+ return { resolved: { token, expiresAt: asDate(result.expiresAt) }, stamped };
1704
+ }
1705
+ function asDate(value) {
1706
+ if (value === void 0 || value === null) {
1707
+ return void 0;
1708
+ }
1709
+ const date = value instanceof Date ? value : new Date(value);
1710
+ return Number.isNaN(date.getTime()) ? void 0 : date;
1711
+ }
1712
+ async function discardBody(response) {
1713
+ try {
1714
+ await response.body?.cancel();
1715
+ } catch {
1716
+ }
1717
+ }
1718
+ async function readBody(response) {
1719
+ const text = await response.text();
1720
+ if (text === "") {
1721
+ return null;
1722
+ }
1723
+ try {
1724
+ return JSON.parse(text);
1725
+ } catch {
1726
+ return text;
1727
+ }
1728
+ }
1729
+
1730
+ // src/billing/client.ts
1731
+ var INVOICE_PAGE_SIZE = 12;
1732
+ var INVOICE_MAX_PAGE_SIZE = 250;
1733
+ var SchematicBillingClient = class {
1734
+ /**
1735
+ * Public so a second client over the same surface can be constructed on
1736
+ * this one rather than minting tokens of its own.
1737
+ */
1738
+ session;
1739
+ constructor(options = {}) {
1740
+ this.session = options instanceof SchematicSession ? options : new SchematicSession(options);
1741
+ }
1742
+ get sessionKey() {
1743
+ return this.session.key;
1744
+ }
1745
+ get sessionStatus() {
1746
+ return this.session.status;
1747
+ }
1748
+ setSession(session) {
1749
+ this.session.set(session);
1750
+ }
1751
+ onSessionChange(listener) {
1752
+ return this.session.onChange(listener);
1753
+ }
1754
+ fetchInvoices(params) {
1755
+ const query = new URLSearchParams({
1756
+ limit: String(Math.min(params.limit, INVOICE_MAX_PAGE_SIZE)),
1757
+ offset: String(params.offset)
1758
+ });
1759
+ if (params.includePending !== void 0) {
1760
+ query.set("include_pending", String(params.includePending));
1761
+ }
1762
+ const path = `/company/invoices?${query}`;
1763
+ return this.session.request(path).then((body) => {
1764
+ if (body === null || typeof body !== "object" || !("data" in body)) {
1765
+ throw new Error(`Malformed response from ${path}`);
1766
+ }
1767
+ const data = body.data;
1768
+ if (data == null || data.invoices == null) {
1769
+ return { invoices: [], count: 0 };
1770
+ }
1771
+ const decoded = GetCompanyInvoicesResponseFromJSON(body).data;
1772
+ return { invoices: decoded.invoices, count: decoded.count };
1773
+ });
1774
+ }
1775
+ };
1776
+ async function fetchBillingData(client, options = {}) {
1777
+ const wanted = options.names ?? ["invoices"];
1778
+ const data = {};
1779
+ const invoices = options.invoices === void 0 ? void 0 : normalizeInvoiceQuery(options.invoices);
1780
+ if (invoices !== void 0) {
1781
+ data.params = { invoices };
1782
+ }
1783
+ data.sessionKey = client.sessionKey;
1784
+ await Promise.all(
1785
+ wanted.map(async (name) => {
1786
+ try {
1787
+ switch (name) {
1788
+ case "invoices": {
1789
+ const page = await client.fetchInvoices({
1790
+ ...invoices ?? {},
1791
+ limit: INVOICE_PAGE_SIZE,
1792
+ offset: 0
1793
+ });
1794
+ data.invoices = {
1795
+ invoices: page.invoices,
1796
+ count: page.count,
1797
+ // Two queries on the server: a count that outran the rows
1798
+ // would seed a page that pages nothing.
1799
+ hasMore: page.invoices.length > 0 && page.invoices.length < page.count
1800
+ };
1801
+ break;
1802
+ }
1803
+ }
1804
+ } catch {
1805
+ }
1806
+ })
1807
+ );
1808
+ return data;
1809
+ }
1199
1810
 
1200
1811
  // src/index.ts
1201
1812
  var anonymousIdKey = "schematicId";