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