@learncard/didkit-plugin 1.10.9 → 1.10.11

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.
@@ -21,9 +21,19 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  // src/index.ts
22
22
  var index_exports = {};
23
23
  __export(index_exports, {
24
+ DEFAULT_DID_WEB_DOCUMENT_CACHE_MAX_ENTRIES: () => DEFAULT_DID_WEB_DOCUMENT_CACHE_MAX_ENTRIES,
25
+ DEFAULT_DID_WEB_DOCUMENT_TTL_MS: () => DEFAULT_DID_WEB_DOCUMENT_TTL_MS,
26
+ WALLET_DID_WEB_DOCUMENT_TTL_MS: () => WALLET_DID_WEB_DOCUMENT_TTL_MS,
27
+ clearDidWebDocumentFetchCache: () => clearDidWebDocumentFetchCache,
28
+ didWebToDocumentUrl: () => didWebToDocumentUrl,
24
29
  getContextURIs: () => getContextURIs,
25
30
  getDidKitPlugin: () => getDidKitPlugin,
26
- getDocumentMap: () => getDocumentMap
31
+ getDidWebDocumentFetchCacheStats: () => getDidWebDocumentFetchCacheStats,
32
+ getDocumentMap: () => getDocumentMap,
33
+ installDidWebDocumentFetchCache: () => installDidWebDocumentFetchCache,
34
+ installWalletDidWebDocumentFetchCache: () => installWalletDidWebDocumentFetchCache,
35
+ invalidateDidWebDocument: () => invalidateDidWebDocument,
36
+ isDidWebDocumentUrl: () => isDidWebDocumentUrl
27
37
  });
28
38
  module.exports = __toCommonJS(index_exports);
29
39
 
@@ -1085,13 +1095,11 @@ var getContextURIs = /* @__PURE__ */ __name((jsonld) => {
1085
1095
  const contexts = [];
1086
1096
  const traverse = /* @__PURE__ */ __name((obj) => {
1087
1097
  if (typeof obj !== "object" || obj === null) return;
1088
- if (obj["@context"]) {
1089
- if (Array.isArray(obj["@context"])) contexts.push(...obj["@context"]);
1090
- else contexts.push(obj["@context"]);
1098
+ const context = "@context" in obj ? obj["@context"] : void 0;
1099
+ for (const entry of Array.isArray(context) ? context : [context]) {
1100
+ if (typeof entry === "string") contexts.push(entry);
1091
1101
  }
1092
- Object.keys(obj).forEach((key) => {
1093
- traverse(obj[key]);
1094
- });
1102
+ Object.values(obj).forEach(traverse);
1095
1103
  }, "traverse");
1096
1104
  traverse(jsonld);
1097
1105
  return contexts;
@@ -1108,8 +1116,351 @@ var getDocumentMap = /* @__PURE__ */ __name(async (learnCard, obj, allowRemoteCo
1108
1116
  }, {});
1109
1117
  }, "getDocumentMap");
1110
1118
 
1119
+ // src/didWebDocumentCache.ts
1120
+ var DEFAULT_DID_WEB_DOCUMENT_TTL_MS = 1e4;
1121
+ var WALLET_DID_WEB_DOCUMENT_TTL_MS = 6e4;
1122
+ var DEFAULT_DID_WEB_DOCUMENT_CACHE_MAX_ENTRIES = 64;
1123
+ var NULL_BODY_STATUSES = /* @__PURE__ */ new Set([101, 204, 205, 304]);
1124
+ var installed = false;
1125
+ var underlyingFetch;
1126
+ var ttlMs = DEFAULT_DID_WEB_DOCUMENT_TTL_MS;
1127
+ var maxEntries = DEFAULT_DID_WEB_DOCUMENT_CACHE_MAX_ENTRIES;
1128
+ var cacheGeneration = 0;
1129
+ var successCache = /* @__PURE__ */ new Map();
1130
+ var inflight = /* @__PURE__ */ new Map();
1131
+ var urlGeneration = /* @__PURE__ */ new Map();
1132
+ var normalizeAbsoluteUrl = /* @__PURE__ */ __name((href) => new URL(href).href, "normalizeAbsoluteUrl");
1133
+ var headersToSortedTuples = /* @__PURE__ */ __name((headers) => {
1134
+ const tuples = [];
1135
+ headers.forEach((value, key) => {
1136
+ tuples.push([key.toLowerCase(), value]);
1137
+ });
1138
+ tuples.sort(
1139
+ (a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0
1140
+ );
1141
+ return tuples;
1142
+ }, "headersToSortedTuples");
1143
+ var normalizeRequest = /* @__PURE__ */ __name((input, init2) => new Request(input, init2), "normalizeRequest");
1144
+ var describeSemanticsFromRequest = /* @__PURE__ */ __name((request) => ({
1145
+ method: request.method.toUpperCase(),
1146
+ url: normalizeAbsoluteUrl(request.url),
1147
+ headers: headersToSortedTuples(request.headers),
1148
+ credentials: request.credentials,
1149
+ mode: request.mode,
1150
+ cache: request.cache,
1151
+ redirect: request.redirect,
1152
+ referrerPolicy: request.referrerPolicy
1153
+ }), "describeSemanticsFromRequest");
1154
+ var semanticsKey = /* @__PURE__ */ __name((semantics) => JSON.stringify([
1155
+ semantics.method,
1156
+ semantics.url,
1157
+ semantics.headers,
1158
+ semantics.credentials,
1159
+ semantics.mode,
1160
+ semantics.cache,
1161
+ semantics.redirect,
1162
+ semantics.referrerPolicy
1163
+ ]), "semanticsKey");
1164
+ var sharedNetworkRequest = /* @__PURE__ */ __name((normalized, signal) => new Request(normalized, { signal }), "sharedNetworkRequest");
1165
+ var peekRequestUrl = /* @__PURE__ */ __name((input) => {
1166
+ if (typeof input === "string") return input;
1167
+ if (input instanceof URL) return input.href;
1168
+ return input.url;
1169
+ }, "peekRequestUrl");
1170
+ var peekMethod = /* @__PURE__ */ __name((input, init2) => {
1171
+ if (init2?.method) return init2.method.toUpperCase();
1172
+ if (input instanceof Request) return input.method.toUpperCase();
1173
+ return "GET";
1174
+ }, "peekMethod");
1175
+ var peekHasIntegrity = /* @__PURE__ */ __name((input, init2) => {
1176
+ if (typeof init2?.integrity === "string" && init2.integrity.length > 0) return true;
1177
+ if (input instanceof Request && input.integrity.length > 0) return true;
1178
+ return false;
1179
+ }, "peekHasIntegrity");
1180
+ var peekCacheMode = /* @__PURE__ */ __name((input, init2) => {
1181
+ if (init2?.cache) return init2.cache;
1182
+ if (input instanceof Request) return input.cache;
1183
+ return "default";
1184
+ }, "peekCacheMode");
1185
+ var peekIsDidWebDocumentUrl = /* @__PURE__ */ __name((url) => {
1186
+ try {
1187
+ const pathname = new URL(url).pathname;
1188
+ return pathname === "/did.json" || pathname.endsWith("/did.json");
1189
+ } catch {
1190
+ const path = url.split(/[?#]/, 1)[0] ?? url;
1191
+ return path === "did.json" || path.endsWith("/did.json");
1192
+ }
1193
+ }, "peekIsDidWebDocumentUrl");
1194
+ var isDidWebDocumentUrl = /* @__PURE__ */ __name((url) => {
1195
+ try {
1196
+ const pathname = new URL(url).pathname;
1197
+ return pathname === "/did.json" || pathname.endsWith("/did.json");
1198
+ } catch {
1199
+ return false;
1200
+ }
1201
+ }, "isDidWebDocumentUrl");
1202
+ var didWebToDocumentUrl = /* @__PURE__ */ __name((did) => {
1203
+ if (!did.startsWith("did:web:")) return void 0;
1204
+ const parts = did.slice("did:web:".length).split(":");
1205
+ const domainName = parts[0];
1206
+ if (!domainName) return void 0;
1207
+ const domain = domainName.replace(/%3A/gi, ":");
1208
+ const path = parts.length > 1 ? parts.slice(1).join("/") : ".well-known";
1209
+ const proto = domain.startsWith("localhost") ? "http" : "https";
1210
+ try {
1211
+ return normalizeAbsoluteUrl(`${proto}://${domain}/${path}/did.json`);
1212
+ } catch {
1213
+ return void 0;
1214
+ }
1215
+ }, "didWebToDocumentUrl");
1216
+ var getUrlGeneration = /* @__PURE__ */ __name((url) => urlGeneration.get(url) ?? 0, "getUrlGeneration");
1217
+ var bumpUrlGeneration = /* @__PURE__ */ __name((url) => {
1218
+ urlGeneration.set(url, getUrlGeneration(url) + 1);
1219
+ for (const key of [...inflight.keys()]) {
1220
+ try {
1221
+ const parsed = JSON.parse(key);
1222
+ if (parsed[1] === url) inflight.delete(key);
1223
+ } catch {
1224
+ }
1225
+ }
1226
+ }, "bumpUrlGeneration");
1227
+ var headersToTuples = /* @__PURE__ */ __name((headers) => {
1228
+ const tuples = [];
1229
+ headers.forEach((value, key) => {
1230
+ tuples.push([key, value]);
1231
+ });
1232
+ return tuples;
1233
+ }, "headersToTuples");
1234
+ var parseCacheControlMaxAgeMs = /* @__PURE__ */ __name((headers) => {
1235
+ const raw = headers.get("cache-control");
1236
+ if (!raw) return void 0;
1237
+ const directives = raw.toLowerCase().split(",").map((part) => part.trim());
1238
+ if (directives.some((d) => d === "no-store" || d === "no-cache")) return 0;
1239
+ for (const directive of directives) {
1240
+ const match = /^max-age=(\d+)$/.exec(directive);
1241
+ if (match) return Number(match[1]) * 1e3;
1242
+ }
1243
+ return void 0;
1244
+ }, "parseCacheControlMaxAgeMs");
1245
+ var storedToResponse = /* @__PURE__ */ __name((stored) => {
1246
+ const body = stored.body === null || NULL_BODY_STATUSES.has(stored.status) ? null : stored.body.slice(0);
1247
+ const response = new Response(body, {
1248
+ status: stored.status,
1249
+ statusText: stored.statusText,
1250
+ headers: stored.headers
1251
+ });
1252
+ try {
1253
+ Object.defineProperty(response, "url", {
1254
+ value: stored.url,
1255
+ writable: false,
1256
+ enumerable: true,
1257
+ configurable: true
1258
+ });
1259
+ } catch {
1260
+ }
1261
+ return response;
1262
+ }, "storedToResponse");
1263
+ var readResponse = /* @__PURE__ */ __name(async (response, effectiveTtlMs, fallbackUrl) => {
1264
+ const body = NULL_BODY_STATUSES.has(response.status) ? null : await response.arrayBuffer();
1265
+ return {
1266
+ expiresAt: Date.now() + effectiveTtlMs,
1267
+ status: response.status,
1268
+ statusText: response.statusText,
1269
+ headers: headersToTuples(response.headers),
1270
+ body,
1271
+ url: response.url || fallbackUrl
1272
+ };
1273
+ }, "readResponse");
1274
+ var sweepExpired = /* @__PURE__ */ __name((now = Date.now()) => {
1275
+ for (const [key, entry] of successCache) {
1276
+ if (entry.expiresAt <= now) successCache.delete(key);
1277
+ }
1278
+ }, "sweepExpired");
1279
+ var touchLru = /* @__PURE__ */ __name((key, stored) => {
1280
+ successCache.delete(key);
1281
+ successCache.set(key, stored);
1282
+ while (successCache.size > maxEntries) {
1283
+ const oldest = successCache.keys().next().value;
1284
+ if (oldest === void 0) break;
1285
+ successCache.delete(oldest);
1286
+ }
1287
+ }, "touchLru");
1288
+ var getFreshSuccess = /* @__PURE__ */ __name((key, now = Date.now()) => {
1289
+ sweepExpired(now);
1290
+ const hit = successCache.get(key);
1291
+ if (!hit) return void 0;
1292
+ if (hit.expiresAt <= now) {
1293
+ successCache.delete(key);
1294
+ return void 0;
1295
+ }
1296
+ touchLru(key, hit);
1297
+ return hit;
1298
+ }, "getFreshSuccess");
1299
+ var abortError = /* @__PURE__ */ __name(() => {
1300
+ if (typeof DOMException === "function") {
1301
+ return new DOMException("The operation was aborted.", "AbortError");
1302
+ }
1303
+ const error = new Error("The operation was aborted.");
1304
+ error.name = "AbortError";
1305
+ return error;
1306
+ }, "abortError");
1307
+ var waitForAbort = /* @__PURE__ */ __name((signal) => new Promise((_, reject) => {
1308
+ if (signal.aborted) {
1309
+ reject(abortError());
1310
+ return;
1311
+ }
1312
+ signal.addEventListener("abort", () => reject(abortError()), { once: true });
1313
+ }), "waitForAbort");
1314
+ var releaseInflightWaiter = /* @__PURE__ */ __name((key, entry) => {
1315
+ entry.waiters -= 1;
1316
+ if (entry.waiters > 0) return;
1317
+ if (inflight.get(key) === entry) inflight.delete(key);
1318
+ if (!entry.controller.signal.aborted) {
1319
+ entry.controller.abort();
1320
+ }
1321
+ }, "releaseInflightWaiter");
1322
+ async function joinInflight(key, entry, callerSignal) {
1323
+ entry.waiters += 1;
1324
+ try {
1325
+ if (callerSignal?.aborted) throw abortError();
1326
+ const stored = callerSignal ? await Promise.race([entry.promise, waitForAbort(callerSignal)]) : await entry.promise;
1327
+ return storedToResponse(stored);
1328
+ } finally {
1329
+ releaseInflightWaiter(key, entry);
1330
+ }
1331
+ }
1332
+ __name(joinInflight, "joinInflight");
1333
+ var shouldBypassRequestCacheMode = /* @__PURE__ */ __name((cache) => cache === "no-store" || cache === "reload" || cache === "no-cache", "shouldBypassRequestCacheMode");
1334
+ async function cachedFetch(input, init2) {
1335
+ const fetchImpl = underlyingFetch;
1336
+ if (!fetchImpl) {
1337
+ if (typeof globalThis.fetch !== "function") {
1338
+ throw new TypeError("globalThis.fetch is not available");
1339
+ }
1340
+ return globalThis.fetch(input, init2);
1341
+ }
1342
+ if (peekHasIntegrity(input, init2)) {
1343
+ return fetchImpl(input, init2);
1344
+ }
1345
+ if (peekMethod(input, init2) !== "GET") {
1346
+ return fetchImpl(input, init2);
1347
+ }
1348
+ if (!peekIsDidWebDocumentUrl(peekRequestUrl(input))) {
1349
+ return fetchImpl(input, init2);
1350
+ }
1351
+ if (shouldBypassRequestCacheMode(peekCacheMode(input, init2))) {
1352
+ return fetchImpl(input, init2);
1353
+ }
1354
+ let normalized;
1355
+ try {
1356
+ normalized = normalizeRequest(input, init2);
1357
+ } catch {
1358
+ return fetchImpl(input, init2);
1359
+ }
1360
+ const semantics = describeSemanticsFromRequest(normalized);
1361
+ if (semantics.method !== "GET" || !isDidWebDocumentUrl(semantics.url)) {
1362
+ return fetchImpl(input, init2);
1363
+ }
1364
+ if (shouldBypassRequestCacheMode(semantics.cache)) {
1365
+ return fetchImpl(input, init2);
1366
+ }
1367
+ const callerSignal = normalized.signal;
1368
+ if (callerSignal.aborted) throw abortError();
1369
+ const key = semanticsKey(semantics);
1370
+ const cached = getFreshSuccess(key);
1371
+ if (cached) return storedToResponse(cached);
1372
+ const existing = inflight.get(key);
1373
+ if (existing && existing.generation === cacheGeneration) {
1374
+ return joinInflight(key, existing, callerSignal);
1375
+ }
1376
+ const generationAtStart = cacheGeneration;
1377
+ const urlGenerationAtStart = getUrlGeneration(semantics.url);
1378
+ const controller = new AbortController();
1379
+ const networkRequest = sharedNetworkRequest(normalized, controller.signal);
1380
+ const pending = (async () => {
1381
+ const response = await fetchImpl(networkRequest);
1382
+ const responseMaxAgeMs = parseCacheControlMaxAgeMs(response.headers);
1383
+ const effectiveTtlMs = responseMaxAgeMs === void 0 ? ttlMs : Math.max(0, Math.min(ttlMs, responseMaxAgeMs));
1384
+ const stored = await readResponse(response, effectiveTtlMs || ttlMs, semantics.url);
1385
+ const stillCurrentGeneration = generationAtStart === cacheGeneration && urlGenerationAtStart === getUrlGeneration(semantics.url);
1386
+ const canStore = response.ok && responseMaxAgeMs !== 0 && effectiveTtlMs > 0 && stillCurrentGeneration;
1387
+ if (canStore) {
1388
+ if (generationAtStart === cacheGeneration && urlGenerationAtStart === getUrlGeneration(semantics.url)) {
1389
+ touchLru(key, stored);
1390
+ }
1391
+ }
1392
+ return stored;
1393
+ })();
1394
+ const entry = {
1395
+ generation: generationAtStart,
1396
+ controller,
1397
+ promise: pending,
1398
+ waiters: 0,
1399
+ semanticsKey: key
1400
+ };
1401
+ inflight.set(key, entry);
1402
+ return joinInflight(key, entry, callerSignal);
1403
+ }
1404
+ __name(cachedFetch, "cachedFetch");
1405
+ var installDidWebDocumentFetchCache = /* @__PURE__ */ __name((options = {}) => {
1406
+ if (typeof globalThis.fetch !== "function") {
1407
+ throw new TypeError(
1408
+ "installDidWebDocumentFetchCache requires globalThis.fetch; none is available"
1409
+ );
1410
+ }
1411
+ if (typeof options.ttlMs === "number" && options.ttlMs > 0) {
1412
+ ttlMs = options.ttlMs;
1413
+ }
1414
+ if (typeof options.maxEntries === "number" && options.maxEntries > 0) {
1415
+ maxEntries = options.maxEntries;
1416
+ }
1417
+ if (installed && !options.force) return;
1418
+ if (installed && options.force && underlyingFetch) {
1419
+ globalThis.fetch = underlyingFetch;
1420
+ }
1421
+ underlyingFetch = globalThis.fetch.bind(globalThis);
1422
+ globalThis.fetch = cachedFetch;
1423
+ installed = true;
1424
+ }, "installDidWebDocumentFetchCache");
1425
+ var installWalletDidWebDocumentFetchCache = /* @__PURE__ */ __name(() => {
1426
+ installDidWebDocumentFetchCache({ ttlMs: WALLET_DID_WEB_DOCUMENT_TTL_MS });
1427
+ }, "installWalletDidWebDocumentFetchCache");
1428
+ var clearDidWebDocumentFetchCache = /* @__PURE__ */ __name(() => {
1429
+ cacheGeneration += 1;
1430
+ successCache.clear();
1431
+ inflight.clear();
1432
+ urlGeneration.clear();
1433
+ }, "clearDidWebDocumentFetchCache");
1434
+ var invalidateDidWebDocument = /* @__PURE__ */ __name((didOrUrl) => {
1435
+ const raw = didOrUrl.startsWith("did:") ? didWebToDocumentUrl(didOrUrl) : isDidWebDocumentUrl(didOrUrl) ? didOrUrl : void 0;
1436
+ if (!raw) return;
1437
+ let url;
1438
+ try {
1439
+ url = normalizeAbsoluteUrl(raw);
1440
+ } catch {
1441
+ return;
1442
+ }
1443
+ for (const key of [...successCache.keys()]) {
1444
+ try {
1445
+ const parsed = JSON.parse(key);
1446
+ if (parsed[1] === url) successCache.delete(key);
1447
+ } catch {
1448
+ }
1449
+ }
1450
+ bumpUrlGeneration(url);
1451
+ }, "invalidateDidWebDocument");
1452
+ var getDidWebDocumentFetchCacheStats = /* @__PURE__ */ __name(() => ({
1453
+ installed,
1454
+ ttlMs,
1455
+ maxEntries,
1456
+ successEntries: successCache.size,
1457
+ inflightEntries: inflight.size,
1458
+ cacheGeneration
1459
+ }), "getDidWebDocumentFetchCacheStats");
1460
+
1111
1461
  // src/plugin.ts
1112
1462
  var getDidKitPlugin = /* @__PURE__ */ __name(async (input, allowRemoteContexts = false) => {
1463
+ installDidWebDocumentFetchCache();
1113
1464
  await didkit_default(input);
1114
1465
  const memoizedDids = {};
1115
1466
  return {
@@ -1118,6 +1469,7 @@ var getDidKitPlugin = /* @__PURE__ */ __name(async (input, allowRemoteContexts =
1118
1469
  description: "Provides an interface to DIDKit, which allows for the generation of key material, as well as signing and verifying credentials and presentations",
1119
1470
  context: {
1120
1471
  resolveStaticDocument: /* @__PURE__ */ __name(async (_learnCard, url) => {
1472
+ if (typeof url !== "string") return void 0;
1121
1473
  try {
1122
1474
  return JSON.parse(await contextLoader(url) ?? "") || void 0;
1123
1475
  } catch (error) {
@@ -1186,6 +1538,7 @@ var getDidKitPlugin = /* @__PURE__ */ __name(async (input, allowRemoteContexts =
1186
1538
  );
1187
1539
  }, "verifyPresentation"),
1188
1540
  contextLoader: /* @__PURE__ */ __name(async (_learnCard, url) => {
1541
+ if (typeof url !== "string") return void 0;
1189
1542
  try {
1190
1543
  return JSON.parse(await contextLoader(url) ?? "") || void 0;
1191
1544
  } catch (error) {
@@ -1193,8 +1546,14 @@ var getDidKitPlugin = /* @__PURE__ */ __name(async (input, allowRemoteContexts =
1193
1546
  return void 0;
1194
1547
  }
1195
1548
  }, "contextLoader"),
1196
- resolveDid: /* @__PURE__ */ __name(async (_learnCard, did, inputMetadata = {}) => JSON.parse(await resolveDID(did, JSON.stringify(inputMetadata))), "resolveDid"),
1197
- didResolver: /* @__PURE__ */ __name(async (_learnCard, did, inputMetadata = {}) => JSON.parse(await didResolver(did, JSON.stringify(inputMetadata))), "didResolver"),
1549
+ resolveDid: /* @__PURE__ */ __name(async (_learnCard, did, inputMetadata = {}) => {
1550
+ if (inputMetadata.noCache) invalidateDidWebDocument(did);
1551
+ return JSON.parse(await resolveDID(did, JSON.stringify(inputMetadata)));
1552
+ }, "resolveDid"),
1553
+ didResolver: /* @__PURE__ */ __name(async (_learnCard, did, inputMetadata = {}) => {
1554
+ if (inputMetadata.noCache) invalidateDidWebDocument(did);
1555
+ return JSON.parse(await didResolver(did, JSON.stringify(inputMetadata)));
1556
+ }, "didResolver"),
1198
1557
  createJwe: /* @__PURE__ */ __name(async (_learnCard, cleartext, recipients) => JSON.parse(await createJwe(cleartext, recipients)), "createJwe"),
1199
1558
  decryptJwe: /* @__PURE__ */ __name(async (_learnCard, jwe, jwks) => decryptJwe(
1200
1559
  JSON.stringify(jwe),
@@ -1225,6 +1584,7 @@ var getDidKitPlugin = /* @__PURE__ */ __name(async (input, allowRemoteContexts =
1225
1584
  );
1226
1585
  }, "decryptDagJwe"),
1227
1586
  clearDidWebCache: /* @__PURE__ */ __name(async () => {
1587
+ clearDidWebDocumentFetchCache();
1228
1588
  await clearCache();
1229
1589
  }, "clearDidWebCache")
1230
1590
  }