@leordev-web5/api
Version:
SDK for accessing the features and capabilities of Web5
105 lines • 5.7 kB
JavaScript
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());
});
};
import ms from 'ms';
import { Web5UserAgent } from '@web5/user-agent';
import { VcApi } from './vc-api.js';
import { DwnApi } from './dwn-api.js';
import { DidApi } from './did-api.js';
import { getTechPreviewDwnEndpoints } from './tech-preview.js';
import { DidIonMethod } from '@web5/dids';
/**
* 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.
*
* @beta
*/
export class Web5 {
constructor(options) {
const { agent, connectedDid } = options;
this.agent = agent;
this.connectedDid = connectedDid;
this.did = new DidApi({ agent, connectedDid });
this.dwn = new DwnApi({ agent, connectedDid });
this.vc = new VcApi({ agent, connectedDid });
}
/**
* Connects to a {@link @web5/agent#Web5Agent}. Defaults to creating a local {@link @web5/user-agent#Web5UserAgent}
* if one isn't provided.
*
* @param options - optional overrides
* @returns
*/
static connect(options = {}) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
let { agent, appData, connectedDid, sync, techPreview } = options;
if (agent === undefined) {
// A custom Web5Agent implementation was not specified, so use default managed user agent.
const userAgent = yield Web5UserAgent.create({ appData });
agent = userAgent;
// Start the agent.
yield userAgent.start({ passphrase: 'insecure-static-phrase' });
// TODO: Replace stubbed connection attempt once Connect Protocol has been implemented.
// Attempt to Connect to localhost agent or via Connect Server.
// userAgent.connect();
const notConnected = true;
if ( /* !userAgent.isConnected() */notConnected) {
// Connect attempt failed or was rejected so fallback to local user agent.
// Query the Agent's DWN tenant for identity records.
const identities = yield userAgent.identityManager.list();
const storedIdentities = identities.length;
// If an existing identity is not found found, create a new one.
if (storedIdentities === 0) {
// Use the specified DWN endpoints or get default tech preview hosted nodes.
const serviceEndpointNodes = (_a = techPreview === null || techPreview === void 0 ? void 0 : techPreview.dwnEndpoints) !== null && _a !== void 0 ? _a : yield getTechPreviewDwnEndpoints();
// Generate ION DID service and key set.
const didOptions = yield DidIonMethod.generateDwnOptions({ serviceEndpointNodes });
// Generate a new Identity for the end-user.
const identity = yield userAgent.identityManager.create({
name: 'Default',
didMethod: 'ion',
didOptions,
kms: 'local'
});
/** Import the Identity metadata to the User Agent's tenant so that it can be restored
* on subsequent launches or page reloads. */
yield userAgent.identityManager.import({ identity, context: userAgent.agentDid });
// Set the newly created identity as the connected DID.
connectedDid = identity.did;
}
else if (storedIdentities === 1) {
// An existing identity was found in the User Agent's tenant.
const [identity] = identities;
// Set the stored identity as the connected DID.
connectedDid = identity.did;
}
else {
throw new Error(`connect() failed due to unexpected state: ${storedIdentities} stored identities`);
}
}
// Enable sync, unless disabled.
if (sync !== 'off') {
// First, register the user identity for sync.
yield userAgent.syncManager.registerIdentity({ did: connectedDid });
// Enable sync using the specified interval or default.
sync !== null && sync !== void 0 ? sync : (sync = '2m');
userAgent.syncManager.startSync({ interval: ms(sync) })
.catch((error) => {
console.error(`Sync failed: ${error}`);
});
}
}
const web5 = new Web5({ agent, connectedDid });
return { web5, did: connectedDid };
});
}
}
//# sourceMappingURL=web5.js.map