Add comprehensive installation and setup documentation

- Add GETTING_STARTED.md with quick start guide and development modes
- Add INSTALL.sh automated installation script
- Add INSTALLATION_CHECKLIST.md, INSTALLATION_SUCCESS.md, and INSTALLATION_SUMMARY.md
- Add QUICK_REFERENCE.md for common commands
- Add SETUP_GUIDE.md with detailed setup instructions
- Update README.md with improved project overview
- Add did-wallet app dependencies and node_modules
This commit is contained in:
Dorian
2026-01-27 17:18:21 +00:00
parent a81f655133
commit 0d073fa89e
22658 changed files with 4494151 additions and 6 deletions
+126
View File
@@ -0,0 +1,126 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DidApi = void 0;
var agent_1 = require("@web5/agent");
/**
* The DID API is used to resolve DIDs.
*
* @beta
*/
var DidApi = /** @class */ (function () {
function DidApi(options) {
this.agent = options.agent;
this.connectedDid = options.connectedDid;
}
/**
* Initiates the creation of a Decentralized Identifier (DID) using the specified method, options,
* and storage preference.
*
* This method sends a request to the Web5 Agent to create a new DID based on the provided method,
* with method-specific options. It also specifies whether the newly created DID should be stored.
*
* @param request - The request parameters for creating a DID, including the method, options, and
* storage flag.
* @returns A promise that resolves to a `DidCreateResponse`, which includes the operation's
* status and, if successful, the newly created DID.
*/
DidApi.prototype.create = function (request) {
return __awaiter(this, void 0, void 0, function () {
var _a, result, status;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.agent.processDidRequest({
messageType: agent_1.DidInterface.Create,
messageParams: __assign({}, request)
})];
case 1:
_a = _b.sent(), result = _a.result, status = __rest(_a, ["result"]);
return [2 /*return*/, __assign({ did: result }, status)];
}
});
});
};
/**
* Resolves a DID to a DID Resolution Result.
*
* @param didUri - The DID or DID URL to resolve.
* @returns A promise that resolves to the DID Resolution Result.
*/
DidApi.prototype.resolve = function (didUri, options) {
return __awaiter(this, void 0, void 0, function () {
var didResolutionResult;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.agent.processDidRequest({
messageParams: { didUri: didUri, options: options },
messageType: agent_1.DidInterface.Resolve
})];
case 1:
didResolutionResult = (_a.sent()).result;
return [2 /*return*/, didResolutionResult];
}
});
});
};
return DidApi;
}());
exports.DidApi = DidApi;
//# sourceMappingURL=did-api.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"did-api.js","sourceRoot":"","sources":["../../src/did-api.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,qCAA2C;AA8B3C;;;;GAIG;AACH;IAUE,gBAAY,OAAmD;QAC7D,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;QAC3B,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC3C,CAAC;IAED;;;;;;;;;;;OAWG;IACU,uBAAM,GAAnB,UAAoB,OAAyB;;;;;4BACb,qBAAM,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC;4BAC/D,WAAW,EAAK,oBAAY,CAAC,MAAM;4BACnC,aAAa,eAAQ,OAAO,CAAE;yBAC/B,CAAC,EAAA;;wBAHI,KAAwB,SAG5B,EAHM,MAAM,YAAA,EAAK,MAAM,cAAnB,UAAqB,CAAF;wBAKzB,iCAAS,GAAG,EAAE,MAAM,IAAK,MAAM,GAAG;;;;KACnC;IAED;;;;;OAKG;IACU,wBAAO,GAApB,UACE,MAAkC,EAAE,OAAqC;;;;;4BAEjC,qBAAM,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC;4BACzE,aAAa,EAAG,EAAE,MAAM,QAAA,EAAE,OAAO,SAAA,EAAE;4BACnC,WAAW,EAAK,oBAAY,CAAC,OAAO;yBACrC,CAAC,EAAA;;wBAHc,mBAAmB,GAAK,CAAA,SAGtC,CAAA,OAHiC;wBAKnC,sBAAO,mBAAmB,EAAC;;;;KAC5B;IACH,aAAC;AAAD,CAAC,AApDD,IAoDC;AApDY,wBAAM"}
+407
View File
@@ -0,0 +1,407 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DwnApi = void 0;
var common_1 = require("@web5/common");
var agent_1 = require("@web5/agent");
var record_js_1 = require("./record.js");
var utils_js_1 = require("./utils.js");
var protocol_js_1 = require("./protocol.js");
/**
* Interface to interact with DWN Records and Protocols
*/
var DwnApi = /** @class */ (function () {
function DwnApi(options) {
this.agent = options.agent;
this.connectedDid = options.connectedDid;
}
Object.defineProperty(DwnApi.prototype, "protocols", {
/**
* API to interact with DWN protocols (e.g., `dwn.protocols.configure()`).
*/
get: function () {
var _this = this;
return {
/**
* Configure method, used to setup a new protocol (or update) with the passed definitions
*/
configure: function (request) { return __awaiter(_this, void 0, void 0, function () {
var agentResponse, message, messageCid, status, response, metadata;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.agent.processDwnRequest({
author: this.connectedDid,
messageParams: request.message,
messageType: agent_1.DwnInterface.ProtocolsConfigure,
target: this.connectedDid
})];
case 1:
agentResponse = _a.sent();
message = agentResponse.message, messageCid = agentResponse.messageCid, status = agentResponse.reply.status;
response = { status: status };
if (status.code < 300) {
metadata = { author: this.connectedDid, messageCid: messageCid };
response.protocol = new protocol_js_1.Protocol(this.agent, message, metadata);
}
return [2 /*return*/, response];
}
});
}); },
/**
* Query the available protocols
*/
query: function (request) { return __awaiter(_this, void 0, void 0, function () {
var agentRequest, agentResponse, reply, _a, entries, status, protocols;
var _this = this;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
agentRequest = {
author: this.connectedDid,
messageParams: request.message,
messageType: agent_1.DwnInterface.ProtocolsQuery,
target: request.from || this.connectedDid
};
if (!request.from) return [3 /*break*/, 2];
return [4 /*yield*/, this.agent.sendDwnRequest(agentRequest)];
case 1:
agentResponse = _b.sent();
return [3 /*break*/, 4];
case 2: return [4 /*yield*/, this.agent.processDwnRequest(agentRequest)];
case 3:
agentResponse = _b.sent();
_b.label = 4;
case 4:
reply = agentResponse.reply;
_a = reply.entries, entries = _a === void 0 ? [] : _a, status = reply.status;
protocols = entries.map(function (entry) {
var metadata = { author: _this.connectedDid };
return new protocol_js_1.Protocol(_this.agent, entry, metadata);
});
return [2 /*return*/, { protocols: protocols, status: status }];
}
});
}); }
};
},
enumerable: false,
configurable: true
});
Object.defineProperty(DwnApi.prototype, "records", {
/**
* API to interact with DWN records (e.g., `dwn.records.create()`).
*/
get: function () {
var _this = this;
return {
/**
* Alias for the `write` method
*/
create: function (request) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.records.write(request)];
});
}); },
/**
* Write a record based on an existing one (useful for updating an existing record)
*/
createFrom: function (request) { return __awaiter(_this, void 0, void 0, function () {
var _a, inheritedAuthor, inheritedProperties;
var _b;
return __generator(this, function (_c) {
_a = request.record.toJSON(), inheritedAuthor = _a.author, inheritedProperties = __rest(_a, ["author"]);
// If `data` is being updated then `dataCid` and `dataSize` must not be present.
if (request.data !== undefined) {
delete inheritedProperties.dataCid;
delete inheritedProperties.dataSize;
}
// If `published` is set to false, ensure that `datePublished` is undefined. Otherwise, DWN SDK's schema validation
// will throw an error if `published` is false but `datePublished` is set.
if (((_b = request.message) === null || _b === void 0 ? void 0 : _b.published) === false && inheritedProperties.datePublished !== undefined) {
delete inheritedProperties.datePublished;
delete inheritedProperties.published;
}
// If the request changes the `author` or message `descriptor` then the deterministic `recordId` will change.
// As a result, we will discard the `recordId` if either of these changes occur.
if (!(0, common_1.isEmptyObject)(request.message) || (request.author && request.author !== inheritedAuthor)) {
delete inheritedProperties.recordId;
}
return [2 /*return*/, this.records.write({
data: request.data,
message: __assign(__assign({}, inheritedProperties), request.message),
})];
});
}); },
/**
* Delete a record
*/
delete: function (request) { return __awaiter(_this, void 0, void 0, function () {
var agentRequest, agentResponse, status;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
agentRequest = {
/**
* The `author` is the DID that will sign the message and must be the DID the Web5 app is
* connected with and is authorized to access the signing private key of.
*/
author: this.connectedDid,
messageParams: request.message,
messageType: agent_1.DwnInterface.RecordsDelete,
/**
* The `target` is the DID of the DWN tenant under which the delete will be executed.
* If `from` is provided, the delete operation will be executed on a remote DWN.
* Otherwise, the record will be deleted on the local DWN.
*/
target: request.from || this.connectedDid
};
if (!request.from) return [3 /*break*/, 2];
return [4 /*yield*/, this.agent.sendDwnRequest(agentRequest)];
case 1:
agentResponse = _a.sent();
return [3 /*break*/, 4];
case 2: return [4 /*yield*/, this.agent.processDwnRequest(agentRequest)];
case 3:
agentResponse = _a.sent();
_a.label = 4;
case 4:
status = agentResponse.reply.status;
return [2 /*return*/, { status: status }];
}
});
}); },
/**
* Query a single or multiple records based on the given filter
*/
query: function (request) { return __awaiter(_this, void 0, void 0, function () {
var agentRequest, agentResponse, reply, entries, status, cursor, records;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
agentRequest = {
/**
* The `author` is the DID that will sign the message and must be the DID the Web5 app is
* connected with and is authorized to access the signing private key of.
*/
author: this.connectedDid,
messageParams: request.message,
messageType: agent_1.DwnInterface.RecordsQuery,
/**
* The `target` is the DID of the DWN tenant under which the query will be executed.
* If `from` is provided, the query operation will be executed on a remote DWN.
* Otherwise, the local DWN will be queried.
*/
target: request.from || this.connectedDid
};
if (!request.from) return [3 /*break*/, 2];
return [4 /*yield*/, this.agent.sendDwnRequest(agentRequest)];
case 1:
agentResponse = _a.sent();
return [3 /*break*/, 4];
case 2: return [4 /*yield*/, this.agent.processDwnRequest(agentRequest)];
case 3:
agentResponse = _a.sent();
_a.label = 4;
case 4:
reply = agentResponse.reply;
entries = reply.entries, status = reply.status, cursor = reply.cursor;
records = entries.map(function (entry) {
var recordOptions = __assign({
/**
* Extract the `author` DID from the record entry since records may be signed by the
* tenant owner or any other entity.
*/
author: (0, agent_1.getRecordAuthor)(entry),
/**
* Set the `connectedDid` to currently connected DID so that subsequent calls to
* {@link Record} instance methods, such as `record.update()` are executed on the
* local DWN even if the record was returned by a query of a remote DWN.
*/
connectedDid: _this.connectedDid,
/**
* If the record was returned by a query of a remote DWN, set the `remoteOrigin` to
* the DID of the DWN that returned the record. The `remoteOrigin` property will be used
* to determine which DWN to send subsequent read requests to in the event the data
* payload exceeds the threshold for being returned with queries.
*/
remoteOrigin: request.from }, entry);
var record = new record_js_1.Record(_this.agent, recordOptions);
return record;
});
return [2 /*return*/, { records: records, status: status, cursor: cursor }];
}
});
}); },
/**
* Read a single record based on the given filter
*/
read: function (request) { return __awaiter(_this, void 0, void 0, function () {
var agentRequest, agentResponse, _a, responseRecord, status, record, recordOptions;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
agentRequest = {
/**
* The `author` is the DID that will sign the message and must be the DID the Web5 app is
* connected with and is authorized to access the signing private key of.
*/
author: this.connectedDid,
messageParams: request.message,
messageType: agent_1.DwnInterface.RecordsRead,
/**
* The `target` is the DID of the DWN tenant under which the read will be executed.
* If `from` is provided, the read operation will be executed on a remote DWN.
* Otherwise, the read will occur on the local DWN.
*/
target: request.from || this.connectedDid
};
if (!request.from) return [3 /*break*/, 2];
return [4 /*yield*/, this.agent.sendDwnRequest(agentRequest)];
case 1:
agentResponse = _b.sent();
return [3 /*break*/, 4];
case 2: return [4 /*yield*/, this.agent.processDwnRequest(agentRequest)];
case 3:
agentResponse = _b.sent();
_b.label = 4;
case 4:
_a = agentResponse.reply, responseRecord = _a.record, status = _a.status;
if (200 <= status.code && status.code <= 299) {
recordOptions = __assign({
/**
* Extract the `author` DID from the record since records may be signed by the
* tenant owner or any other entity.
*/
author: (0, agent_1.getRecordAuthor)(responseRecord),
/**
* Set the `connectedDid` to currently connected DID so that subsequent calls to
* {@link Record} instance methods, such as `record.update()` are executed on the
* local DWN even if the record was read from a remote DWN.
*/
connectedDid: this.connectedDid,
/**
* If the record was returned by reading from a remote DWN, set the `remoteOrigin` to
* the DID of the DWN that returned the record. The `remoteOrigin` property will be used
* to determine which DWN to send subsequent read requests to in the event the data
* payload must be read again (e.g., if the data stream is consumed).
*/
remoteOrigin: request.from }, responseRecord);
record = new record_js_1.Record(this.agent, recordOptions);
}
return [2 /*return*/, { record: record, status: status }];
}
});
}); },
/**
* Writes a record to the DWN
*
* As a convenience, the Record instance returned will cache a copy of the data. This is done
* to maintain consistency with other DWN methods, like RecordsQuery, that include relatively
* small data payloads when returning RecordsWrite message properties. Regardless of data
* size, methods such as `record.data.stream()` will return the data when called even if it
* requires fetching from the DWN datastore.
*/
write: function (request) { return __awaiter(_this, void 0, void 0, function () {
var _a, dataBlob, dataFormat, agentResponse, responseMessage, status, record, recordOptions;
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_a = (0, utils_js_1.dataToBlob)(request.data, (_b = request.message) === null || _b === void 0 ? void 0 : _b.dataFormat), dataBlob = _a.dataBlob, dataFormat = _a.dataFormat;
return [4 /*yield*/, this.agent.processDwnRequest({
author: this.connectedDid,
dataStream: dataBlob,
messageParams: __assign(__assign({}, request.message), { dataFormat: dataFormat }),
messageType: agent_1.DwnInterface.RecordsWrite,
store: request.store,
target: this.connectedDid
})];
case 1:
agentResponse = _c.sent();
responseMessage = agentResponse.message, status = agentResponse.reply.status;
if (200 <= status.code && status.code <= 299) {
recordOptions = __assign({
/**
* Assume the author is the connected DID since the record was just written to the
* local DWN.
*/
author: this.connectedDid,
/**
* Set the `connectedDid` to currently connected DID so that subsequent calls to
* {@link Record} instance methods, such as `record.update()` are executed on the
* local DWN.
*/
connectedDid: this.connectedDid, encodedData: dataBlob }, responseMessage);
record = new record_js_1.Record(this.agent, recordOptions);
}
return [2 /*return*/, { record: record, status: status }];
}
});
}); },
};
},
enumerable: false,
configurable: true
});
return DwnApi;
}());
exports.DwnApi = DwnApi;
//# sourceMappingURL=dwn-api.js.map
File diff suppressed because one or more lines are too long
+62
View File
@@ -0,0 +1,62 @@
"use strict";
/**
* Making developing with Web5 components at least 5 times easier to work with.
*
* Web5 consists of the following components:
* - Decentralized Identifiers
* - Verifiable Credentials
* - DWeb Node personal datastores
*
* The SDK sets out to gather the most oft used functionality from all three of
* these pillar technologies to provide a simple library that is as close to
* effortless as possible.
*
* The SDK is currently still under active development, but having entered the
* Tech Preview phase there is now a drive to avoid unnecessary changes unless
* backwards compatibility is provided. Additional functionality will be added
* in the lead up to 1.0 final, and modifications will be made to address
* issues and community feedback.
*
* [Link to GitHub Repo](https://github.com/TBD54566975/web5-js)
*
* @packageDocumentation
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.utils = void 0;
__exportStar(require("./did-api.js"), exports);
__exportStar(require("./dwn-api.js"), exports);
__exportStar(require("./protocol.js"), exports);
__exportStar(require("./record.js"), exports);
__exportStar(require("./vc-api.js"), exports);
__exportStar(require("./web5.js"), exports);
__exportStar(require("./tech-preview.js"), exports);
__exportStar(require("./web-features.js"), exports);
var utils = __importStar(require("./utils.js"));
exports.utils = utils;
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,+CAA6B;AAC7B,+CAA6B;AAC7B,gDAA8B;AAC9B,8CAA4B;AAC5B,8CAA4B;AAC5B,4CAA0B;AAC1B,oDAAkC;AAClC,oDAAkC;AAElC,gDAAoC;AAC3B,sBAAK"}
+1
View File
@@ -0,0 +1 @@
{"type": "commonjs"}
+110
View File
@@ -0,0 +1,110 @@
"use strict";
/**
* NOTE: Added reference types here to avoid a `pnpm` bug during build.
* https://github.com/TBD54566975/web5-js/pull/507
*/
/// <reference types="@tbd54566975/dwn-sdk-js" />
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Protocol = void 0;
var agent_1 = require("@web5/agent");
/**
* Encapsulates a DWN Protocol with its associated metadata and configuration.
*
* This class primarly exists to provide developers with a convenient way to configure/install
* protocols on remote DWNs.
*/
var Protocol = /** @class */ (function () {
/**
* Constructs a new instance of the Protocol class.
*
* @param agent - The Web5Agent instance used for network interactions.
* @param protocolsConfigureMessage - The configuration message containing the protocol details.
* @param metadata - Metadata associated with the protocol, including the author and optional message CID.
*/
function Protocol(agent, protocolsConfigureMessage, metadata) {
this._agent = agent;
this._metadata = metadata;
this._protocolsConfigureMessage = protocolsConfigureMessage;
}
Object.defineProperty(Protocol.prototype, "definition", {
/**
* Retrieves the protocol definition from the protocol's configuration message.
* @returns The protocol definition.
*/
get: function () {
return this._protocolsConfigureMessage.descriptor.definition;
},
enumerable: false,
configurable: true
});
/**
* Serializes the protocol's configuration message to JSON.
* @returns The serialized JSON object of the protocol's configuration message.
*/
Protocol.prototype.toJSON = function () {
return this._protocolsConfigureMessage;
};
/**
* Sends the protocol configuration to a remote DWN identified by the target DID.
*
* @param target - The DID of the target DWN to which the protocol configuration will be installed.
* @returns A promise that resolves to an object containing the status of the send operation.
*/
Protocol.prototype.send = function (target) {
return __awaiter(this, void 0, void 0, function () {
var reply;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this._agent.sendDwnRequest({
author: this._metadata.author,
messageCid: this._metadata.messageCid,
messageType: agent_1.DwnInterface.ProtocolsConfigure,
target: target,
})];
case 1:
reply = (_a.sent()).reply;
return [2 /*return*/, { status: reply.status }];
}
});
});
};
return Protocol;
}());
exports.Protocol = Protocol;
//# sourceMappingURL=protocol.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../src/protocol.ts"],"names":[],"mappings":";AAAA;;;GAGG;AACH,iDAAiD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIjD,qCAA2C;AAiB3C;;;;;GAKG;AACH;IAUE;;;;;;OAMG;IACH,kBAAY,KAAgB,EAAE,yBAAsE,EAAE,QAA0B;QAC9H,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QACpB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAC1B,IAAI,CAAC,0BAA0B,GAAG,yBAAyB,CAAC;IAC9D,CAAC;IAMD,sBAAI,gCAAU;QAJd;;;WAGG;aACH;YACE,OAAO,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,UAAU,CAAC;QAC/D,CAAC;;;OAAA;IAED;;;OAGG;IACH,yBAAM,GAAN;QACE,OAAO,IAAI,CAAC,0BAA0B,CAAC;IACzC,CAAC;IAED;;;;;OAKG;IACG,uBAAI,GAAV,UAAW,MAAc;;;;;4BACL,qBAAM,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC;4BACjD,MAAM,EAAQ,IAAI,CAAC,SAAS,CAAC,MAAM;4BACnC,UAAU,EAAI,IAAI,CAAC,SAAS,CAAC,UAAU;4BACvC,WAAW,EAAG,oBAAY,CAAC,kBAAkB;4BAC7C,MAAM,EAAQ,MAAM;yBACrB,CAAC,EAAA;;wBALM,KAAK,GAAK,CAAA,SAKhB,CAAA,MALW;wBAOb,sBAAO,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,EAAC;;;;KACjC;IACH,eAAC;AAAD,CAAC,AAvDD,IAuDC;AAvDY,4BAAQ"}
+885
View File
@@ -0,0 +1,885 @@
"use strict";
/**
* NOTE: Added reference types here to avoid a `pnpm` bug during build.
* https://github.com/TBD54566975/web5-js/pull/507
*/
/// <reference types="@tbd54566975/dwn-sdk-js" />
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Record = void 0;
var agent_1 = require("@web5/agent");
var agent_2 = require("@web5/agent");
var common_1 = require("@web5/common");
var utils_js_1 = require("./utils.js");
/**
* Record wrapper class with convenience methods to send and update,
* aside from manipulating and reading the record data.
*
* Note: The `messageTimestamp` of the most recent RecordsWrite message is
* logically equivalent to the date/time at which a Record was most
* recently modified. Since this Record class implementation is
* intended to simplify the developer experience of working with
* logical records (and not individual DWN messages) the
* `messageTimestamp` is mapped to `dateModified`.
*
* @beta
*/
/**
* The `Record` class encapsulates a single record's data and metadata, providing a more
* developer-friendly interface for working with Decentralized Web Node (DWN) records.
*
* Methods are provided to read, update, and manage the record's lifecycle, including writing to
* remote DWNs.
*
* @beta
*/
var Record = exports.Record = /** @class */ (function () {
function Record(agent, options) {
this._agent = agent;
// Store the author DID that originally signed the message as a convenience for developers, so
// that they don't have to decode the signer's DID from the JWS.
this._author = options.author;
// Store the currently `connectedDid` so that subsequent message signing is done with the
// connected DID's keys and DWN requests target the connected DID's DWN.
this._connectedDid = options.connectedDid;
// If the record was queried or read from a remote DWN, the `remoteOrigin` DID will be
// defined. This value is used to send subsequent read requests to the same remote DWN in the
// event the record's data payload was too large to be returned in query results. or must be
// read again (e.g., if the data stream is consumed).
this._remoteOrigin = options.remoteOrigin;
// RecordsWriteMessage properties.
this._attestation = options.attestation;
this._authorization = options.authorization;
this._contextId = options.contextId;
this._descriptor = options.descriptor;
this._encryption = options.encryption;
this._initialWrite = options.initialWrite;
this._recordId = options.recordId;
this._protocolRole = options.protocolRole;
if (options.encodedData) {
// If `encodedData` is set, then it is expected that:
// type is Blob if the Record object was instantiated by dwn.records.create()/write().
// type is Base64 URL encoded string if the Record object was instantiated by dwn.records.query().
// If it is a string, we need to Base64 URL decode to bytes and instantiate a Blob.
this._encodedData = (typeof options.encodedData === 'string') ?
new Blob([common_1.Convert.base64Url(options.encodedData).toUint8Array()], { type: this.dataFormat }) :
options.encodedData;
}
if (options.data) {
// If the record was created from a RecordsRead reply then it will have a `data` property.
// If the `data` property is a web ReadableStream, convert it to a Node.js Readable.
this._readableStream = common_1.Stream.isReadableStream(options.data) ?
common_1.NodeStream.fromWebReadable({ readableStream: options.data }) :
options.data;
}
}
Object.defineProperty(Record.prototype, "attestation", {
// Getters for immutable DWN Record properties.
/** Record's signatures attestation */
get: function () { return this._attestation; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "authorization", {
/** Record's signatures attestation */
get: function () { return this._authorization; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "author", {
/** DID that signed the record. */
get: function () { return this._author; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "contextId", {
/** Record's context ID */
get: function () { return this._contextId; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "dataFormat", {
/** Record's data format */
get: function () { return this._descriptor.dataFormat; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "dateCreated", {
/** Record's creation date */
get: function () { return this._descriptor.dateCreated; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "encryption", {
/** Record's encryption */
get: function () { return this._encryption; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "initialWrite", {
/** Record's initial write if the record has been updated */
get: function () { return this._initialWrite; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "id", {
/** Record's ID */
get: function () { return this._recordId; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "interface", {
/** Interface is always `Records` */
get: function () { return this._descriptor.interface; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "method", {
/** Method is always `Write` */
get: function () { return this._descriptor.method; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "parentId", {
/** Record's parent ID */
get: function () { return this._descriptor.parentId; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "protocol", {
/** Record's protocol */
get: function () { return this._descriptor.protocol; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "protocolPath", {
/** Record's protocol path */
get: function () { return this._descriptor.protocolPath; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "protocolRole", {
/** Role under which the author is writing the record */
get: function () { return this._protocolRole; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "recipient", {
/** Record's recipient */
get: function () { return this._descriptor.recipient; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "schema", {
/** Record's schema */
get: function () { return this._descriptor.schema; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "dataCid", {
// Getters for mutable DWN Record properties.
/** Record's CID */
get: function () { return this._descriptor.dataCid; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "dataSize", {
/** Record's data size */
get: function () { return this._descriptor.dataSize; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "dateModified", {
/** Record's modified date */
get: function () { return this._descriptor.messageTimestamp; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "datePublished", {
/** Record's published date */
get: function () { return this._descriptor.datePublished; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "messageTimestamp", {
/** Record's published status */
get: function () { return this._descriptor.messageTimestamp; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "published", {
/** Record's published status (true/false) */
get: function () { return this._descriptor.published; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "tags", {
/** Tags of the record */
get: function () { return this._descriptor.tags; },
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "rawMessage", {
/**
* Returns a copy of the raw `RecordsWriteMessage` that was used to create the current `Record` instance.
*/
get: function () {
var message = JSON.parse(JSON.stringify({
contextId: this._contextId,
recordId: this._recordId,
descriptor: this._descriptor,
attestation: this._attestation,
authorization: this._authorization,
encryption: this._encryption,
}));
(0, common_1.removeUndefinedProperties)(message);
return message;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Record.prototype, "data", {
/**
* Returns the data of the current record.
* If the record data is not available, it attempts to fetch the data from the DWN.
* @returns a data stream with convenience methods such as `blob()`, `json()`, `text()`, and `stream()`, similar to the fetch API response
* @throws `Error` if the record has already been deleted.
*
* @beta
*/
get: function () {
var self = this; // Capture the context of the `Record` instance.
var dataObj = {
/**
* Returns the data of the current record as a `Blob`.
*
* @returns A promise that resolves to a Blob containing the record's data.
* @throws If the record data is not available or cannot be converted to a `Blob`.
*
* @beta
*/
blob: function () {
return __awaiter(this, void 0, void 0, function () {
var _a, _b, _c;
var _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
_a = Blob.bind;
_c = (_b = common_1.NodeStream).consumeToBytes;
_d = {};
return [4 /*yield*/, this.stream()];
case 1: return [4 /*yield*/, _c.apply(_b, [(_d.readable = _e.sent(), _d)])];
case 2: return [2 /*return*/, new (_a.apply(Blob, [void 0, [_e.sent()], { type: self.dataFormat }]))()];
}
});
});
},
/**
* Returns the data of the current record as a `Uint8Array`.
*
* @returns A Promise that resolves to a `Uint8Array` containing the record's data bytes.
* @throws If the record data is not available or cannot be converted to a byte array.
*
* @beta
*/
bytes: function () {
return __awaiter(this, void 0, void 0, function () {
var _a, _b;
var _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
_b = (_a = common_1.NodeStream).consumeToBytes;
_c = {};
return [4 /*yield*/, this.stream()];
case 1: return [4 /*yield*/, _b.apply(_a, [(_c.readable = _d.sent(), _c)])];
case 2: return [2 /*return*/, _d.sent()];
}
});
});
},
/**
* Parses the data of the current record as JSON and returns it as a JavaScript object.
*
* @returns A Promise that resolves to a JavaScript object parsed from the record's JSON data.
* @throws If the record data is not available, not in JSON format, or cannot be parsed.
*
* @beta
*/
json: function () {
return __awaiter(this, void 0, void 0, function () {
var _a, _b;
var _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
_b = (_a = common_1.NodeStream).consumeToJson;
_c = {};
return [4 /*yield*/, this.stream()];
case 1: return [4 /*yield*/, _b.apply(_a, [(_c.readable = _d.sent(), _c)])];
case 2: return [2 /*return*/, _d.sent()];
}
});
});
},
/**
* Returns the data of the current record as a `string`.
*
* @returns A promise that resolves to a `string` containing the record's text data.
* @throws If the record data is not available or cannot be converted to text.
*
* @beta
*/
text: function () {
return __awaiter(this, void 0, void 0, function () {
var _a, _b;
var _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
_b = (_a = common_1.NodeStream).consumeToText;
_c = {};
return [4 /*yield*/, this.stream()];
case 1: return [4 /*yield*/, _b.apply(_a, [(_c.readable = _d.sent(), _c)])];
case 2: return [2 /*return*/, _d.sent()];
}
});
});
},
/**
* Provides a `Readable` stream containing the record's data.
*
* @returns A promise that resolves to a Node.js `Readable` stream of the record's data.
* @throws If the record data is not available in-memory and cannot be fetched.
*
* @beta
*/
stream: function () {
return __awaiter(this, void 0, void 0, function () {
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (!self._encodedData) return [3 /*break*/, 1];
/** If `encodedData` is set, it indicates that the Record was instantiated by
* `dwn.records.create()`/`dwn.records.write()` or the record's data payload was small
* enough to be returned in `dwn.records.query()` results. In either case, the data is
* already available in-memory and can be returned as a Node.js `Readable` stream. */
self._readableStream = common_1.NodeStream.fromWebReadable({ readableStream: self._encodedData.stream() });
return [3 /*break*/, 6];
case 1:
if (!!common_1.NodeStream.isReadable({ readable: self._readableStream })) return [3 /*break*/, 6];
/** If the data stream for this `Record` instance has already been partially or fully
* consumed, then the data must be fetched again from either: */
_a = self;
if (!self._remoteOrigin) return [3 /*break*/, 3];
// A. ...a remote DWN if the record was originally queried from a remote DWN.
return [4 /*yield*/, self.readRecordData({ target: self._remoteOrigin, isRemote: true })];
case 2:
// A. ...a remote DWN if the record was originally queried from a remote DWN.
_b = _c.sent();
return [3 /*break*/, 5];
case 3:
// B. ...a local DWN if the record was originally queried from the local DWN.
return [4 /*yield*/, self.readRecordData({ target: self._connectedDid, isRemote: false })];
case 4:
// B. ...a local DWN if the record was originally queried from the local DWN.
_b = _c.sent();
_c.label = 5;
case 5:
/** If the data stream for this `Record` instance has already been partially or fully
* consumed, then the data must be fetched again from either: */
_a._readableStream = _b;
_c.label = 6;
case 6:
if (!self._readableStream) {
throw new Error('Record data is not available.');
}
return [2 /*return*/, self._readableStream];
}
});
});
},
/**
* Attaches callbacks for the resolution and/or rejection of the `Promise` returned by
* `stream()`.
*
* This method is a proxy to the `then` method of the `Promise` returned by `stream()`,
* allowing for a seamless integration with promise-based workflows.
* @param onFulfilled - A function to asynchronously execute when the `stream()` promise
* becomes fulfilled.
* @param onRejected - A function to asynchronously execute when the `stream()` promise
* becomes rejected.
* @returns A `Promise` for the completion of which ever callback is executed.
*/
then: function (onFulfilled, onRejected) {
return this.stream().then(onFulfilled, onRejected);
},
/**
* Attaches a rejection handler callback to the `Promise` returned by the `stream()` method.
* This method is a shorthand for `.then(undefined, onRejected)`, specifically designed for handling
* rejection cases in the promise chain initiated by accessing the record's data. It ensures that
* errors during data retrieval or processing can be caught and handled appropriately.
*
* @param onRejected - A function to asynchronously execute when the `stream()` promise
* becomes rejected.
* @returns A `Promise` that resolves to the value of the callback if it is called, or to its
* original fulfillment value if the promise is instead fulfilled.
*/
catch: function (onRejected) {
return this.stream().catch(onRejected);
}
};
return dataObj;
},
enumerable: false,
configurable: true
});
/**
* Stores the current record state as well as any initial write to the owner's DWN.
*
* @param importRecord - if true, the record will signed by the owner before storing it to the owner's DWN. Defaults to false.
* @returns the status of the store request
*
* @beta
*/
Record.prototype.store = function (importRecord) {
if (importRecord === void 0) { importRecord = false; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
// if we are importing the record we sign it as the owner
return [2 /*return*/, this.processRecord({ signAsOwner: importRecord, store: true })];
});
});
};
/**
* Signs the current record state as well as any initial write and optionally stores it to the owner's DWN.
* This is useful when importing a record that was signed by someone else into your own DWN.
*
* @param store - if true, the record will be stored to the owner's DWN after signing. Defaults to true.
* @returns the status of the import request
*
* @beta
*/
Record.prototype.import = function (store) {
if (store === void 0) { store = true; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.processRecord({ store: store, signAsOwner: true })];
});
});
};
/**
* Send the current record to a remote DWN by specifying their DID
* If no DID is specified, the target is assumed to be the owner (connectedDID).
* If an initial write is present and the Record class send cache has no awareness of it, the initial write is sent first
* (vs waiting for the regular DWN sync)
*
* @param target - the optional DID to send the record to, if none is set it is sent to the connectedDid
* @returns the status of the send record request
* @throws `Error` if the record has already been deleted.
*
* @beta
*/
Record.prototype.send = function (target) {
return __awaiter(this, void 0, void 0, function () {
var initialWrite, rawMessage, reply, _a, _b;
var _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
initialWrite = this._initialWrite;
target !== null && target !== void 0 ? target : (target = this._connectedDid);
if (!(initialWrite && !Record._sendCache.check(this._recordId, target))) return [3 /*break*/, 2];
rawMessage = __assign({}, initialWrite);
(0, common_1.removeUndefinedProperties)(rawMessage);
// Send the initial write to the target.
return [4 /*yield*/, this._agent.sendDwnRequest({
messageType: agent_2.DwnInterface.RecordsWrite,
author: this._connectedDid,
target: target,
rawMessage: rawMessage
})];
case 1:
// Send the initial write to the target.
_d.sent();
// Set the cache to maintain awareness that we don't need to send the initial write next time.
Record._sendCache.set(this._recordId, target);
_d.label = 2;
case 2:
_b = (_a = this._agent).sendDwnRequest;
_c = {
messageType: agent_2.DwnInterface.RecordsWrite,
author: this._connectedDid
};
return [4 /*yield*/, this.data.blob()];
case 3: return [4 /*yield*/, _b.apply(_a, [(_c.dataStream = _d.sent(),
_c.target = target,
_c.rawMessage = __assign({}, this.rawMessage),
_c)])];
case 4:
reply = (_d.sent()).reply;
return [2 /*return*/, reply];
}
});
});
};
/**
* Returns a JSON representation of the Record instance.
* It's called by `JSON.stringify(...)` automatically.
*/
Record.prototype.toJSON = function () {
return {
attestation: this.attestation,
author: this.author,
authorization: this.authorization,
contextId: this.contextId,
dataCid: this.dataCid,
dataFormat: this.dataFormat,
dataSize: this.dataSize,
dateCreated: this.dateCreated,
messageTimestamp: this.dateModified,
datePublished: this.datePublished,
encryption: this.encryption,
interface: this.interface,
method: this.method,
parentId: this.parentId,
protocol: this.protocol,
protocolPath: this.protocolPath,
protocolRole: this.protocolRole,
published: this.published,
recipient: this.recipient,
recordId: this.id,
schema: this.schema,
tags: this.tags,
};
};
/**
* Convenience method to return the string representation of the Record instance.
* Called automatically in string concatenation, String() type conversion, and template literals.
*/
Record.prototype.toString = function () {
var str = "Record: {\n";
str += " ID: ".concat(this.id, "\n");
str += this.contextId ? " Context ID: ".concat(this.contextId, "\n") : '';
str += this.protocol ? " Protocol: ".concat(this.protocol, "\n") : '';
str += this.schema ? " Schema: ".concat(this.schema, "\n") : '';
str += " Data CID: ".concat(this.dataCid, "\n");
str += " Data Format: ".concat(this.dataFormat, "\n");
str += " Data Size: ".concat(this.dataSize, "\n");
str += " Created: ".concat(this.dateCreated, "\n");
str += " Modified: ".concat(this.dateModified, "\n");
str += "}";
return str;
};
/**
* Returns a pagination cursor for the current record given a sort order.
*
* @param sort the sort order to use for the pagination cursor.
* @returns A promise that resolves to a pagination cursor for the current record.
*/
Record.prototype.paginationCursor = function (sort) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, (0, agent_1.getPaginationCursor)(this.rawMessage, sort)];
});
});
};
/**
* Update the current record on the DWN.
* @param params - Parameters to update the record.
* @returns the status of the update request
* @throws `Error` if the record has already been deleted.
*
* @beta
*/
Record.prototype.update = function (_a) {
var dateModified = _a.dateModified, data = _a.data, params = __rest(_a, ["dateModified", "data"]);
return __awaiter(this, void 0, void 0, function () {
var _b, parentId, descriptor, parentContextId, updateMessage, dataBlob, mutableDescriptorProperties, agentResponse, message, status, responseMessage;
var _this = this;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_b = this._descriptor, parentId = _b.parentId, descriptor = __rest(_b, ["parentId"]);
parentContextId = parentId ? this._contextId.split('/').slice(0, -1).join('/') : undefined;
updateMessage = __assign(__assign(__assign({}, descriptor), params), { parentContextId: parentContextId, messageTimestamp: dateModified, recordId: this._recordId });
// NOTE: The original Record's tags are copied to the update message, so that the tags are not lost.
// However if a user passes new tags in the `RecordUpdateParams` object, they will overwrite the original tags.
// If the updated tag object is empty or set to null, we remove the tags property to avoid schema validation errors in the DWN SDK.
if ((0, common_1.isEmptyObject)(updateMessage.tags) || updateMessage.tags === null) {
delete updateMessage.tags;
}
if (data !== undefined) {
// If `data` is being updated then `dataCid` and `dataSize` must be undefined and the `data`
// value must be converted to a Blob and later passed as a top-level property to
// `agent.processDwnRequest()`.
delete updateMessage.dataCid;
delete updateMessage.dataSize;
(dataBlob = (0, utils_js_1.dataToBlob)(data, updateMessage.dataFormat).dataBlob);
}
mutableDescriptorProperties = new Set(['data', 'dataCid', 'dataSize', 'datePublished', 'messageTimestamp', 'published', 'tags']);
Record.verifyPermittedMutation(Object.keys(params), mutableDescriptorProperties);
// If `published` is set to false, ensure that `datePublished` is undefined. Otherwise, DWN SDK's schema validation
// will throw an error if `published` is false but `datePublished` is set.
if (params.published === false && updateMessage.datePublished !== undefined) {
delete updateMessage.datePublished;
}
return [4 /*yield*/, this._agent.processDwnRequest({
author: this._connectedDid,
dataStream: dataBlob,
messageParams: __assign({}, updateMessage),
messageType: agent_2.DwnInterface.RecordsWrite,
target: this._connectedDid,
})];
case 1:
agentResponse = _c.sent();
message = agentResponse.message, status = agentResponse.reply.status;
responseMessage = message;
if (200 <= status.code && status.code <= 299) {
// copy the original raw message to the initial write before we update the values.
if (!this._initialWrite) {
this._initialWrite = __assign({}, this.rawMessage);
}
// Only update the local Record instance mutable properties if the record was successfully (over)written.
this._authorization = responseMessage.authorization;
this._protocolRole = params.protocolRole;
mutableDescriptorProperties.forEach(function (property) {
_this._descriptor[property] = responseMessage.descriptor[property];
});
// Cache data.
if (data !== undefined) {
this._encodedData = dataBlob;
}
}
return [2 /*return*/, { status: status }];
}
});
});
};
/**
* Handles the various conditions around there being an initial write, whether to store initial/current state,
* and whether to add an owner signature to the initial write to enable storage when protocol rules require it.
*/
Record.prototype.processRecord = function (_a) {
var store = _a.store, signAsOwner = _a.signAsOwner;
return __awaiter(this, void 0, void 0, function () {
var initialWriteRequest, agentResponse_1, message_1, status_1, responseMessage_1, requestOptions, agentResponse, message, status, responseMessage;
var _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (!(this._initialWrite && ((signAsOwner && !this._initialWriteSigned) || (store && !this._initialWriteStored)))) return [3 /*break*/, 2];
initialWriteRequest = {
messageType: agent_2.DwnInterface.RecordsWrite,
rawMessage: this.initialWrite,
author: this._connectedDid,
target: this._connectedDid,
signAsOwner: signAsOwner,
store: store,
};
return [4 /*yield*/, this._agent.processDwnRequest(initialWriteRequest)];
case 1:
agentResponse_1 = _c.sent();
message_1 = agentResponse_1.message, status_1 = agentResponse_1.reply.status;
responseMessage_1 = message_1;
// If we are signing as owner, make sure to update the initial write's authorization, because now it will have the owner's signature on it
// set the stored or signed status to true so we don't process it again.
if (200 <= status_1.code && status_1.code <= 299) {
if (store)
this._initialWriteStored = true;
if (signAsOwner) {
this._initialWriteSigned = true;
this.initialWrite.authorization = responseMessage_1.authorization;
}
}
_c.label = 2;
case 2:
_b = {
messageType: agent_2.DwnInterface.RecordsWrite,
rawMessage: this.rawMessage,
author: this._connectedDid,
target: this._connectedDid
};
return [4 /*yield*/, this.data.blob()];
case 3:
requestOptions = (_b.dataStream = _c.sent(),
_b.signAsOwner = signAsOwner,
_b.store = store,
_b);
return [4 /*yield*/, this._agent.processDwnRequest(requestOptions)];
case 4:
agentResponse = _c.sent();
message = agentResponse.message, status = agentResponse.reply.status;
responseMessage = message;
if (200 <= status.code && status.code <= 299) {
// If we are signing as the owner, make sure to update the current record state's authorization, because now it will have the owner's signature on it.
if (signAsOwner)
this._authorization = responseMessage.authorization;
}
return [2 /*return*/, { status: status }];
}
});
});
};
/**
* Fetches the record's data from the specified DWN.
*
* This private method is called when the record data is not available in-memory
* and needs to be fetched from either a local or a remote DWN.
* It makes a read request to the specified DWN and processes the response to provide
* a Node.js `Readable` stream of the record's data.
*
* @param params - Parameters for fetching the record's data.
* @param params.target - The DID of the DWN to fetch the data from.
* @param params.isRemote - Indicates whether the target DWN is a remote node.
* @returns A Promise that resolves to a Node.js `Readable` stream of the record's data.
* @throws If there is an error while fetching or processing the data from the DWN.
*
* @beta
*/
Record.prototype.readRecordData = function (_a) {
var target = _a.target, isRemote = _a.isRemote;
return __awaiter(this, void 0, void 0, function () {
var readRequest, agentResponsePromise, record, dataStream, nodeReadable, error_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
readRequest = {
author: this._connectedDid,
messageParams: { filter: { recordId: this.id } },
messageType: agent_2.DwnInterface.RecordsRead,
target: target,
};
agentResponsePromise = isRemote ?
this._agent.sendDwnRequest(readRequest) :
this._agent.processDwnRequest(readRequest);
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, agentResponsePromise];
case 2:
record = (_b.sent()).reply.record;
dataStream = record.data;
nodeReadable = common_1.Stream.isReadableStream(dataStream) ?
common_1.NodeStream.fromWebReadable({ readableStream: dataStream }) :
dataStream;
return [2 /*return*/, nodeReadable];
case 3:
error_1 = _b.sent();
throw new Error("Error encountered while attempting to read data: ".concat(error_1.message));
case 4: return [2 /*return*/];
}
});
});
};
/**
* Verifies if the properties to be mutated are mutable.
*
* This private method is used to ensure that only mutable properties of the `Record` instance
* are being changed. It checks whether the properties specified for mutation are among the
* set of properties that are allowed to be modified. If any of the properties to be mutated
* are not in the set of mutable properties, the method throws an error.
*
* @param propertiesToMutate - An iterable of property names that are intended to be mutated.
* @param mutableDescriptorProperties - A set of property names that are allowed to be mutated.
*
* @throws If any of the properties in `propertiesToMutate` are not in `mutableDescriptorProperties`.
*
* @beta
*/
Record.verifyPermittedMutation = function (propertiesToMutate, mutableDescriptorProperties) {
var e_1, _a;
try {
for (var propertiesToMutate_1 = __values(propertiesToMutate), propertiesToMutate_1_1 = propertiesToMutate_1.next(); !propertiesToMutate_1_1.done; propertiesToMutate_1_1 = propertiesToMutate_1.next()) {
var property = propertiesToMutate_1_1.value;
if (!mutableDescriptorProperties.has(property)) {
throw new Error("".concat(property, " is an immutable property. Its value cannot be changed."));
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (propertiesToMutate_1_1 && !propertiesToMutate_1_1.done && (_a = propertiesToMutate_1.return)) _a.call(propertiesToMutate_1);
}
finally { if (e_1) throw e_1.error; }
}
};
/**
* Cache to minimize the amount of redundant two-phase commits we do in store() and send()
* Retains awareness of the last 100 records stored/sent for up to 100 target DIDs each.
*/
Record._sendCache = utils_js_1.SendCache;
return Record;
}());
//# sourceMappingURL=record.js.map
File diff suppressed because one or more lines are too long
+153
View File
@@ -0,0 +1,153 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });
var dids_1 = require("@web5/dids");
var workerSelf = self;
var DidResolver = new dids_1.UniversalResolver({ didResolvers: [dids_1.DidDht, dids_1.DidWeb] });
var didUrlRegex = /^https?:\/\/dweb\/(([^/]+)\/.*)?$/;
var httpToHttpsRegex = /^http:/;
var trailingSlashRegex = /\/$/;
workerSelf.addEventListener('fetch', function (event) {
var match = event.request.url.match(didUrlRegex);
if (match) {
event.respondWith((function () { return __awaiter(void 0, void 0, void 0, function () {
var normalizedUrl, cachedResponse;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
normalizedUrl = event.request.url.replace(httpToHttpsRegex, 'https:').replace(trailingSlashRegex, '');
return [4 /*yield*/, caches.open('drl').then(function (cache) { return cache.match(normalizedUrl); })];
case 1:
cachedResponse = _a.sent();
return [2 /*return*/, cachedResponse || handleEvent(event, match[2], match[1])];
}
});
}); })());
}
});
function handleEvent(event, did, route) {
return __awaiter(this, void 0, void 0, function () {
var result, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 3, , 4]);
return [4 /*yield*/, DidResolver.resolve(did)];
case 1:
result = _a.sent();
return [4 /*yield*/, fetchResource(event, result.didDocument, route)];
case 2: return [2 /*return*/, _a.sent()];
case 3:
error_1 = _a.sent();
if (error_1 instanceof Response) {
return [2 /*return*/, error_1];
}
console.log("Error in DID URL fetch: ".concat(error_1));
return [2 /*return*/, new Response('DID URL fetch error', { status: 500 })];
case 4: return [2 /*return*/];
}
});
});
}
function fetchResource(event, ddo, route) {
var _a, _b;
return __awaiter(this, void 0, void 0, function () {
var endpoints, endpoints_1, endpoints_1_1, endpoint, response, error_2, e_1_1;
var e_1, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
endpoints = (_b = (_a = ddo === null || ddo === void 0 ? void 0 : ddo.service) === null || _a === void 0 ? void 0 : _a.find(function (service) { return service.type === 'DecentralizedWebNode'; })) === null || _b === void 0 ? void 0 : _b.serviceEndpoint;
endpoints = (Array.isArray(endpoints) ? endpoints : [endpoints]).filter(function (url) { return url.startsWith('http'); });
if (!(endpoints === null || endpoints === void 0 ? void 0 : endpoints.length)) {
throw new Response('DWeb Node resolution failed: no valid endpoints found.', { status: 530 });
}
_d.label = 1;
case 1:
_d.trys.push([1, 8, 9, 10]);
endpoints_1 = __values(endpoints), endpoints_1_1 = endpoints_1.next();
_d.label = 2;
case 2:
if (!!endpoints_1_1.done) return [3 /*break*/, 7];
endpoint = endpoints_1_1.value;
_d.label = 3;
case 3:
_d.trys.push([3, 5, , 6]);
return [4 /*yield*/, fetch("".concat(endpoint.replace(trailingSlashRegex, ''), "/").concat(route), { headers: event.request.headers })];
case 4:
response = _d.sent();
if (response.ok) {
return [2 /*return*/, response];
}
console.log("DWN endpoint error: ".concat(response.status));
return [2 /*return*/, new Response('DWeb Node request failed', { status: response.status })];
case 5:
error_2 = _d.sent();
console.log("DWN endpoint error: ".concat(error_2));
return [2 /*return*/, new Response('DWeb Node request failed: ' + error_2, { status: 500 })];
case 6:
endpoints_1_1 = endpoints_1.next();
return [3 /*break*/, 2];
case 7: return [3 /*break*/, 10];
case 8:
e_1_1 = _d.sent();
e_1 = { error: e_1_1 };
return [3 /*break*/, 10];
case 9:
try {
if (endpoints_1_1 && !endpoints_1_1.done && (_c = endpoints_1.return)) _c.call(endpoints_1);
}
finally { if (e_1) throw e_1.error; }
return [7 /*endfinally*/];
case 10: return [2 /*return*/];
}
});
});
}
//# sourceMappingURL=service-worker.js.map
@@ -0,0 +1 @@
{"version":3,"file":"service-worker.js","sourceRoot":"","sources":["../../src/service-worker.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,mCAA+D;AAE/D,IAAM,UAAU,GAAG,IAAW,CAAC;AAC/B,IAAM,WAAW,GAAG,IAAI,wBAAiB,CAAC,EAAE,YAAY,EAAE,CAAC,aAAM,EAAE,aAAM,CAAC,EAAE,CAAC,CAAC;AAC9E,IAAM,WAAW,GAAG,mCAAmC,CAAC;AACxD,IAAM,gBAAgB,GAAG,QAAQ,CAAC;AAClC,IAAM,kBAAkB,GAAG,KAAK,CAAC;AAEjC,UAAU,CAAC,gBAAgB,CAAC,OAAO,EAAE,UAAA,KAAK;IACxC,IAAM,KAAK,GAAG,KAAK,CAAC,OAAO,C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;;;;;;;;;;;;;;;CAGhF"}
+125
View File
@@ -0,0 +1,125 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTechPreviewDwnEndpoints = void 0;
var dids_1 = require("@web5/dids");
/**
* Dynamically selects up to 2 DWN endpoints that are provided
* by default during the Tech Preview period.
*
* @beta
*/
function getTechPreviewDwnEndpoints() {
return __awaiter(this, void 0, void 0, function () {
var response, error_1, didDocument, _a, dwnService, techPreviewEndpoints, dwnUrls, numNodesToAllocate, attempts, nodeIdx, dwnUrl, healthCheck, error_2;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_b.trys.push([0, 2, , 3]);
return [4 /*yield*/, fetch('https://dwn.tbddev.org/.well-known/did.json')];
case 1:
response = _b.sent();
if (!response.ok) {
throw new Error("HTTP Error: ".concat(response.status, " ").concat(response.statusText));
}
return [3 /*break*/, 3];
case 2:
error_1 = _b.sent();
console.warn('failed to get tech preview dwn endpoints:', error_1.message);
return [2 /*return*/, []];
case 3: return [4 /*yield*/, response.json()];
case 4:
didDocument = _b.sent();
_a = __read(dids_1.utils.getServices({ didDocument: didDocument, id: '#dwn', type: 'DecentralizedWebNode' }), 1), dwnService = _a[0];
techPreviewEndpoints = new Set();
if (!('serviceEndpoint' in dwnService
&& !Array.isArray(dwnService.serviceEndpoint)
&& typeof dwnService.serviceEndpoint !== 'string'
&& Array.isArray(dwnService.serviceEndpoint.nodes))) return [3 /*break*/, 10];
dwnUrls = dwnService.serviceEndpoint.nodes;
numNodesToAllocate = Math.min(dwnUrls.length, 2);
attempts = 0;
_b.label = 5;
case 5:
if (!(attempts < dwnUrls.length && techPreviewEndpoints.size < numNodesToAllocate)) return [3 /*break*/, 10];
nodeIdx = getRandomInt(0, dwnUrls.length);
dwnUrl = dwnUrls[nodeIdx];
_b.label = 6;
case 6:
_b.trys.push([6, 8, , 9]);
return [4 /*yield*/, fetch("".concat(dwnUrl, "/health"))];
case 7:
healthCheck = _b.sent();
if (healthCheck.ok) {
techPreviewEndpoints.add(dwnUrl);
}
return [3 /*break*/, 9];
case 8:
error_2 = _b.sent();
return [3 /*break*/, 9];
case 9:
attempts += 1;
return [3 /*break*/, 5];
case 10: return [2 /*return*/, Array.from(techPreviewEndpoints)];
}
});
});
}
exports.getTechPreviewDwnEndpoints = getTechPreviewDwnEndpoints;
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
//# sourceMappingURL=tech-preview.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"tech-preview.js","sourceRoot":"","sources":["../../src/tech-preview.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,mCAA+C;AAE/C;;;;;GAKG;AACH,SAAsB,0BAA0B;;;;;;;oBAGjC,qBAAM,KAAK,CAAC,6CAA6C,CAAC,EAAA;;oBAArE,QAAQ,GAAG,SAA0D,CAAC;oBACtE,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;wBAChB,MAAM,IAAI,KAAK,CAAC,sBAAe,QAAQ,CAAC,MAAM,cAAI,QAAQ,CAAC,UAAU,CAAE,CAAC,CAAC;qBAC1E;;;;oBAED,OAAO,CAAC,IAAI,CAAC,2CAA2C,EAAE,OAAK,CAAC,OAAO,CAAC,CAAC;oBACzE,sBAAO,EAAE,EAAC;wBAGQ,qBAAM,QAAQ,CAAC,IAAI,EAAE,EAAA;;oBAAnC,WAAW,GAAG,SAAqB;oBACnC,KAAA,OAAiB,YAAQ,CAAC,WAAW,CAAC,EAAE,WAAW,aAAA,EAAE,EAAE,EAAE,MA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IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC;AACvD,CAAC"}
+127
View File
@@ -0,0 +1,127 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SendCache = exports.dataToBlob = void 0;
var common_1 = require("@web5/common");
/**
* Converts various data types to a `Blob` object, automatically detecting the data type or using
* the specified `dataFormat` to set the Blob's MIME type.
*
* This function supports plain text, JSON objects, binary data (Uint8Array, ArrayBuffer), and Blob
* inputs and will attempt to automatically detect the type of the data if `dataFormat` is not
* explicitly provided.
*
* @beta
*
* @example
* ```ts
* // Convert a JSON object to a Blob
* const { dataBlob, dataFormat } = dataToBlob({ key: 'value' }, 'application/json');
*
* // Convert a plain text string to a Blob without specifying dataFormat
* const { dataBlob: textBlob } = dataToBlob('Hello, world!');
*
* // Convert binary data to a Blob
* const binaryData = new Uint8Array([0, 1, 2, 3]);
* const { dataBlob: binaryBlob } = dataToBlob(binaryData);
* ```
*
* @param data - The data to be converted into a `Blob`. This can be a string, an object, binary
* data (Uint8Array or ArrayBuffer), or a Blob.
* @param dataFormat - An optional MIME type string that specifies the format of the data. Common
* types include 'text/plain' for string data, 'application/json' for JSON
* objects, and 'application/octet-stream' for binary data. If not provided, the
* function will attempt to detect the format based on the data type or default
* to 'application/octet-stream'.
* @returns An object containing the `dataBlob`, a Blob representation of the input data, and
* `dataFormat`, the MIME type of the data as determined by the function or specified by the caller.
* @throws An error if the data type is not supported or cannot be converted to a Blob.
*/
function dataToBlob(data, dataFormat) {
var dataBlob;
// Check for Object or String, and if neither, assume bytes.
var detectedType = (0, common_1.universalTypeOf)(data);
if (dataFormat === 'text/plain' || detectedType === 'String') {
dataBlob = new Blob([data], { type: 'text/plain' });
}
else if (dataFormat === 'application/json' || detectedType === 'Object') {
var dataBytes = common_1.Convert.object(data).toUint8Array();
dataBlob = new Blob([dataBytes], { type: 'application/json' });
}
else if (detectedType === 'Uint8Array' || detectedType === 'ArrayBuffer') {
dataBlob = new Blob([data], { type: 'application/octet-stream' });
}
else if (detectedType === 'Blob') {
dataBlob = data;
}
else {
throw new Error('data type not supported.');
}
dataFormat = dataFormat || dataBlob.type || 'application/octet-stream';
return { dataBlob: dataBlob, dataFormat: dataFormat };
}
exports.dataToBlob = dataToBlob;
/**
* The `SendCache` class provides a static caching mechanism to optimize the process of sending
* records to remote DWN targets by minimizing redundant sends.
*
* It maintains a cache of record IDs and their associated target DIDs to which they have been sent.
* This helps in avoiding unnecessary network requests and ensures efficient data synchronization
* across Decentralized Web Nodes (DWNs).
*
* The cache employs a simple eviction policy to maintain a manageable size, ensuring that the cache
* does not grow indefinitely and consume excessive memory resources.
*
* @beta
*/
var SendCache = exports.SendCache = /** @class */ (function () {
function SendCache() {
}
/**
* Checks if a given record ID has been sent to a specified target DID. This method is used to
* determine whether a send operation is necessary or if it can be skipped to avoid redundancy.
*
* @param id - The unique identifier of the record.
* @param target - The DID of the target to check against.
* @returns A boolean indicating whether the record has been sent to the target.
*/
SendCache.check = function (id, target) {
var targetCache = SendCache.cache.get(id);
return targetCache ? targetCache.has(target) : false;
};
/**
* Adds or updates an entry in the cache for a given record ID and target DID. If the cache
* exceeds its size limit, the oldest entry is removed. This method ensures that the cache
* reflects the most recent sends.
*
* @param id - The unique identifier of the record.
* @param target - The DID of the target to which the record has been sent.
*/
SendCache.set = function (id, target) {
var targetCache = SendCache.cache.get(id) || new Set();
SendCache.cache.delete(id);
SendCache.cache.set(id, targetCache);
if (this.cache.size > SendCache.sendCacheLimit) {
var firstRecord = SendCache.cache.keys().next().value;
SendCache.cache.delete(firstRecord);
}
targetCache.delete(target);
targetCache.add(target);
if (targetCache.size > SendCache.sendCacheLimit) {
var firstTarget = targetCache.keys().next().value;
targetCache.delete(firstTarget);
}
};
/**
* A private static map that serves as the core storage mechanism for the cache. It maps record
* IDs to a set of target DIDs, indicating which records have been sent to which targets.
*/
SendCache.cache = new Map();
/**
* The maximum number of entries allowed in the cache. Once this limit is exceeded, the oldest
* entries are evicted to make room for new ones. This limit applies both to the number of records
* and the number of targets per record.
*/
SendCache.sendCacheLimit = 100;
return SendCache;
}());
//# sourceMappingURL=utils.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";;;AAAA,uCAAwD;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,SAAgB,UAAU,CAAC,IAAS,EAAE,UAAmB;IAMvD,IAAI,QAAc,CAAC;IAEnB,4DAA4D;IAC5D,IAAM,YAAY,GAAG,IAAA,wBAAe,EAAC,IAAI,CAAC,CAAC;IAC3C,IAAI,UAAU,KAAK,YAAY,IAAI,YAAY,KAAK,QAAQ,EAAE;QAC5D,QAAQ,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;KACrD;SAAM,IAAI,UAAU,KAAK,kBAAkB,IAAI,YAAY,KAAK,QAAQ,EAAE;QACzE,IAAM,SAAS,GAAG,gBAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,YAAY,EAAE,CAAC;QACtD,QAAQ,GAAG,IAAI,IAAI,CAAC,CAAC,SAAS,CAAC,EAAE,EAAE,IAAI,EAAE,kBAAkB,EAAE,CAAC,CAAC;KAChE;SAAM,IAAI,YAAY,KAAK,YAAY,IAAI,YAAY,KAAK,aAAa,EAAE;QAC1E,QAAQ,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,0BAA0B,EAAE,CAAC,CAAC;KACnE;SAAM,IAAI,YAAY,KAAK,MAAM,EAAE;QAClC,QAAQ,GAAG,IAAI,CAAC;KACjB;SAAM;QACL,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;KAC7C;IAED,UAAU,GAAG,UAAU,IAAI,QAAQ,CAAC,IAAI,IA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CAAC;SACjC;IACH,CAAC;IAhDD;;;MAGE;IACa,eAAK,GAAG,IAAI,GAAG,EAAuB,CAAC;IAEtD;;;;OAIG;IACY,wBAAc,GAAG,GAAG,CAAC;IAsCtC,gBAAC;CAAA,AAlDD,IAkDC"}
+64
View File
@@ -0,0 +1,64 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.VcApi = void 0;
/**
* The VC API is used to issue, present and verify VCs
*
* @beta
*/
var VcApi = /** @class */ (function () {
function VcApi(options) {
this.agent = options.agent;
this.connectedDid = options.connectedDid;
}
/**
* Issues a VC (Not implemented yet)
*/
VcApi.prototype.create = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
// TODO: implement
throw new Error('Not implemented.');
});
});
};
return VcApi;
}());
exports.VcApi = VcApi;
//# sourceMappingURL=vc-api.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"vc-api.js","sourceRoot":"","sources":["../../src/vc-api.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA;;;;GAIG;AACH;IAUE,eAAY,OAAmD;QAC7D,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;QAC3B,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAC3C,CAAC;IAED;;OAEG;IACG,sBAAM,GAAZ;;;gBACE,kBAAkB;gBAClB,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;;;KACrC;IACH,YAAC;AAAD,CAAC,AAtBD,IAsBC;AAtBY,sBAAK"}
+32
View File
@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.installNetworkingFeatures = void 0;
/**
* Installs the DWeb networking features in the current environment.
*/
function installNetworkingFeatures(path) {
var _a;
var workerSelf = self;
try {
if (typeof ServiceWorkerGlobalScope !== 'undefined' && workerSelf instanceof ServiceWorkerGlobalScope) {
// Dynamically import service worker code only if we're in a Service Worker context
import('./service-worker.js').catch(function (error) {
console.error('Error loading service worker module:', error);
});
}
else if ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _a === void 0 ? void 0 : _a.serviceWorker) {
if (path)
navigator.serviceWorker.register(path).catch(function (error) {
console.error('DWeb networking feature installation failed: ', error);
});
}
else {
throw new Error('DWeb networking features are not available for install in this environment');
}
}
catch (error) {
console.error('Error in installing networking features:', error);
}
}
exports.installNetworkingFeatures = installNetworkingFeatures;
//# sourceMappingURL=web-features.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"web-features.js","sourceRoot":"","sources":["../../src/web-features.ts"],"names":[],"mappings":";;;AAGA;;GAEG;AACH,SAAgB,yBAAyB,CAAC,IAAY;;IACpD,IAAM,UAAU,GAAG,IAAW,CAAC;IAE/B,IAAI;QACF,IAAI,OAAO,wBAAwB,KAAK,WAAW,IAAI,UAAU,YAAY,wBAAwB,EAAE;YACrG,mFAAmF;YACnF,MAAM,CAAC,qBAAqB,CAAC,CAAC,KAAK,CAAC,UAAA,KAAK;gBACvC,OAAO,CAAC,KAAK,CAAC,sCAAsC,EAAE,KAAK,CAAC,CAAC;YAC/D,CAAC,CAAC,CAAC;SACJ;aACI,IAAI,MAAA,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,SAAS,0CAAE,aAAa,EAAE;YAC7C,IAAI,IAAI;gBAAE,SAAS,CAAC,aAAa,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,UAAA,KAAK;oBAC1D,OAAO,CAAC,KAAK,CAAC,+CAA+C,EAAE,KAAK,CAAC,CAAC;gBACxE,CAAC,CAAC,CAAC;SACJ;aACI;YACH,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;SAC/F;KACF;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,CAAC,KAAK,CAAC,0CAA0C,EAAE,KAAK,CAAC,CAAC;KAClE;AACH,CAAC;AArBD,8DAqBC"}
+193
View File
@@ -0,0 +1,193 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Web5 = void 0;
var user_agent_1 = require("@web5/user-agent");
var vc_api_js_1 = require("./vc-api.js");
var dwn_api_js_1 = require("./dwn-api.js");
var did_api_js_1 = require("./did-api.js");
var tech_preview_js_1 = require("./tech-preview.js");
/**
* The main Web5 API interface. It manages the creation of a DID if needed, the connection to the
* local DWN and all the web5 main foundational APIs such as VC, syncing, etc.
*/
var Web5 = /** @class */ (function () {
function Web5(_a) {
var agent = _a.agent, connectedDid = _a.connectedDid;
this.agent = agent;
this.connectedDid = connectedDid;
this.did = new did_api_js_1.DidApi({ agent: agent, connectedDid: connectedDid });
this.dwn = new dwn_api_js_1.DwnApi({ agent: agent, connectedDid: connectedDid });
this.vc = new vc_api_js_1.VcApi({ agent: agent, connectedDid: connectedDid });
}
/**
* Connects to a {@link Web5Agent}. Defaults to creating a local {@link Web5UserAgent} if one
* isn't provided.
*
* @param options - Optional overrides that can be provided when calling {@link Web5.connect}.
* @returns A promise that resolves to a {@link Web5} instance and the connected DID.
*/
Web5.connect = function (_a) {
var _b;
var _c = _a === void 0 ? {} : _a, agent = _c.agent, agentVault = _c.agentVault, connectedDid = _c.connectedDid, password = _c.password, recoveryPhrase = _c.recoveryPhrase, sync = _c.sync, techPreview = _c.techPreview;
return __awaiter(this, void 0, void 0, function () {
var userAgent, notConnected, identity, identities, existingIdentityCount, serviceEndpointNodes, _d, _e, _f, web5;
var _g;
return __generator(this, function (_h) {
switch (_h.label) {
case 0:
if (!(agent === undefined)) return [3 /*break*/, 17];
return [4 /*yield*/, user_agent_1.Web5UserAgent.create({ agentVault: agentVault })];
case 1:
userAgent = _h.sent();
agent = userAgent;
// Warn the developer and application user of the security risks of using a static password.
if (password === undefined) {
password = 'insecure-static-phrase';
console.warn('%cSECURITY WARNING:%c ' +
'You have not set a password, which defaults to a static, guessable value. ' +
'This significantly compromises the security of your data. ' +
'Please configure a secure, unique password.', 'font-weight: bold; color: red;', 'font-weight: normal; color: inherit;');
}
return [4 /*yield*/, userAgent.firstLaunch()];
case 2:
if (!_h.sent()) return [3 /*break*/, 4];
return [4 /*yield*/, userAgent.initialize({ password: password, recoveryPhrase: recoveryPhrase })];
case 3:
recoveryPhrase = _h.sent();
_h.label = 4;
case 4: return [4 /*yield*/, userAgent.start({ password: password })];
case 5:
_h.sent();
notConnected = true;
if (!notConnected) return [3 /*break*/, 15];
identity = void 0;
return [4 /*yield*/, userAgent.identity.list()];
case 6:
identities = _h.sent();
existingIdentityCount = identities.length;
if (!(existingIdentityCount === 0)) return [3 /*break*/, 13];
if (!((_b = techPreview === null || techPreview === void 0 ? void 0 : techPreview.dwnEndpoints) !== null && _b !== void 0)) return [3 /*break*/, 7];
_d = _b;
return [3 /*break*/, 9];
case 7: return [4 /*yield*/, (0, tech_preview_js_1.getTechPreviewDwnEndpoints)()];
case 8:
_d = _h.sent();
_h.label = 9;
case 9:
serviceEndpointNodes = _d;
return [4 /*yield*/, userAgent.identity.create({
didMethod: 'dht',
metadata: { name: 'Default' },
didOptions: {
services: [
{
id: 'dwn',
type: 'DecentralizedWebNode',
serviceEndpoint: serviceEndpointNodes,
enc: '#enc',
sig: '#sig',
}
],
verificationMethods: [
{
algorithm: 'Ed25519',
id: 'sig',
purposes: ['assertionMethod', 'authentication']
},
{
algorithm: 'secp256k1',
id: 'enc',
purposes: ['keyAgreement']
}
]
}
})];
case 10:
// Generate a new Identity for the end-user.
identity = _h.sent();
_f = (_e = userAgent.identity).manage;
_g = {};
return [4 /*yield*/, identity.export()];
case 11:
// The User Agent will manage the Identity, which ensures it will be available on future
// sessions.
return [4 /*yield*/, _f.apply(_e, [(_g.portableIdentity = _h.sent(), _g)])];
case 12:
// The User Agent will manage the Identity, which ensures it will be available on future
// sessions.
_h.sent();
return [3 /*break*/, 14];
case 13:
if (existingIdentityCount === 1) {
// An existing identity was found in the User Agent's tenant.
identity = identities[0];
}
else {
throw new Error("connect() failed due to unexpected state: Expected 1 but found ".concat(existingIdentityCount, " stored identities."));
}
_h.label = 14;
case 14:
// Set the stored identity as the connected DID.
connectedDid = identity.did.uri;
_h.label = 15;
case 15:
if (!(sync !== 'off')) return [3 /*break*/, 17];
// First, register the user identity for sync.
return [4 /*yield*/, userAgent.sync.registerIdentity({ did: connectedDid })];
case 16:
// First, register the user identity for sync.
_h.sent();
// Enable sync using the specified interval or default.
sync !== null && sync !== void 0 ? sync : (sync = '2m');
userAgent.sync.startSync({ interval: sync })
.catch(function (error) {
console.error("Sync failed: ".concat(error));
});
_h.label = 17;
case 17:
web5 = new Web5({ agent: agent, connectedDid: connectedDid });
return [2 /*return*/, { web5: web5, did: connectedDid, recoveryPhrase: recoveryPhrase }];
}
});
});
};
return Web5;
}());
exports.Web5 = Web5;
//# sourceMappingURL=web5.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"web5.js","sourceRoot":"","sources":["../../src/web5.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,+CAAiD;AAEjD,yCAAoC;AACpC,2CAAsC;AACtC,2CAAsC;AACtC,qDAA+D;AAsH/D;;;GAGG;AACH;IAmBE,cAAY,EAAmC;YAAjC,KAAK,WAAA,EAAE,YAAY,kBAAA;QAC/B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,GAAG,GAAG,IAAI,mBAAM,CAAC,EAAE,KAAK,OAAA,EAAE,YAAY,cAAA,EAAE,CAAC,CAAC;QAC/C,IAAI,CAAC,GAAG,GAAG,IAAI,mBAAM,CAAC,EAAE,KAAK,OAAA,EAAE,YAAY,cAAA,EAAE,CAAC,CAAC;QAC/C,IAAI,CAAC,EAAE,GAAG,IAAI,iBAAK,CAAC,EAAE,KAAK,OAAA,EAAE,YAAY,cAAA,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED;;;;;;OAMG;IACU,YAAO,GAApB,UAAqB,EAEK;;YAFL,qBAEG,EAAE,KAAA,EADxB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