Socket
Socket
Sign inDemoInstall

@dfinity/agent

Package Overview
Dependencies
Maintainers
13
Versions
121
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@dfinity/agent - npm Package Compare versions

Comparing version 0.17.0 to 0.18.0

lib/cjs/agent/http/errors.d.ts

24

lib/cjs/actor.d.ts

@@ -1,2 +0,2 @@

import { Agent, QueryResponseRejected, SubmitResponse } from './agent';
import { Agent, HttpDetailsResponse, QueryResponseRejected, SubmitResponse } from './agent';
import { AgentError } from './errors';

@@ -76,3 +76,3 @@ import { IDL } from '@dfinity/candid';

*/
export interface ActorMethod<Args extends unknown[] = unknown[], Ret extends unknown = unknown> {
export interface ActorMethod<Args extends unknown[] = unknown[], Ret = unknown> {
(...args: Args): Promise<Ret>;

@@ -82,2 +82,15 @@ withOptions(options: CallConfig): (...args: Args) => Promise<Ret>;

/**
* An actor method type, defined for each methods of the actor service.
*/
export interface ActorMethodWithHttpDetails<Args extends unknown[] = unknown[], Ret = unknown> extends ActorMethod {
(...args: Args): Promise<{
httpDetails: HttpDetailsResponse;
result: Ret;
}>;
}
export declare type FunctionWithArgsAndReturn<Args extends unknown[] = unknown[], Ret = unknown> = (...args: Args) => Ret;
export declare type ActorMethodMappedWithHttpDetails<T> = {
[K in keyof T]: T[K] extends FunctionWithArgsAndReturn<infer Args, infer Ret> ? ActorMethodWithHttpDetails<Args, Ret> : never;
};
/**
* The mode used when installing a canister.

@@ -101,2 +114,5 @@ */

declare const metadataSymbol: unique symbol;
export interface CreateActorClassOpts {
httpDetails?: boolean;
}
/**

@@ -129,4 +145,5 @@ * An actor base class. An actor is an object containing only functions that will

}, config?: CallConfig): Promise<ActorSubclass>;
static createActorClass(interfaceFactory: IDL.InterfaceFactory): ActorConstructor;
static createActorClass(interfaceFactory: IDL.InterfaceFactory, options?: CreateActorClassOpts): ActorConstructor;
static createActor<T = Record<string, ActorMethod>>(interfaceFactory: IDL.InterfaceFactory, configuration: ActorConfig): ActorSubclass<T>;
static createActorWithHttpDetails<T = Record<string, ActorMethod>>(interfaceFactory: IDL.InterfaceFactory, configuration: ActorConfig): ActorSubclass<ActorMethodMappedWithHttpDetails<T>>;
private [metadataSymbol];

@@ -136,2 +153,3 @@ protected constructor(metadata: ActorMetadata);

export declare type ActorConstructor = new (config: ActorConfig) => ActorSubclass;
export declare const ACTOR_METHOD_WITH_HTTP_DETAILS = "http-details";
export declare type ManagementCanisterRecord = _SERVICE;

@@ -138,0 +156,0 @@ /**

@@ -6,3 +6,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.getManagementCanister = exports.Actor = exports.CanisterInstallMode = exports.UpdateCallRejectedError = exports.QueryCallRejectedError = exports.ActorCallError = void 0;
exports.getManagementCanister = exports.ACTOR_METHOD_WITH_HTTP_DETAILS = exports.Actor = exports.CanisterInstallMode = exports.UpdateCallRejectedError = exports.QueryCallRejectedError = exports.ActorCallError = void 0;
const buffer_1 = require("buffer/");

@@ -120,3 +120,3 @@ const agent_1 = require("./agent");

}
static createActorClass(interfaceFactory) {
static createActorClass(interfaceFactory, options) {
const service = interfaceFactory({ IDL: candid_1.IDL });

@@ -133,2 +133,5 @@ class CanisterActor extends Actor {

for (const [methodName, func] of service._fields) {
if (options === null || options === void 0 ? void 0 : options.httpDetails) {
func.annotations.push(exports.ACTOR_METHOD_WITH_HTTP_DETAILS);
}
this[methodName] = _createActorMethod(this, methodName, func, config.blsVerify);

@@ -143,2 +146,5 @@ }

}
static createActorWithHttpDetails(interfaceFactory, configuration) {
return new (this.createActorClass(interfaceFactory, { httpDetails: true }))(configuration);
}
}

@@ -163,2 +169,3 @@ exports.Actor = Actor;

};
exports.ACTOR_METHOD_WITH_HTTP_DETAILS = 'http-details';
function _createActorMethod(actor, methodName, func, blsVerify) {

@@ -179,3 +186,8 @@ let caller;

case "replied" /* QueryResponseStatus.Replied */:
return decodeReturnValue(func.retTypes, result.reply.arg);
return func.annotations.includes(exports.ACTOR_METHOD_WITH_HTTP_DETAILS)
? {
httpDetails: result.httpDetails,
result: decodeReturnValue(func.retTypes, result.reply.arg),
}
: decodeReturnValue(func.retTypes, result.reply.arg);
}

@@ -204,7 +216,18 @@ };

const responseBytes = await (0, polling_1.pollForResponse)(agent, ecid, requestId, pollStrategy, blsVerify);
const shouldIncludeHttpDetails = func.annotations.includes(exports.ACTOR_METHOD_WITH_HTTP_DETAILS);
if (responseBytes !== undefined) {
return decodeReturnValue(func.retTypes, responseBytes);
return shouldIncludeHttpDetails
? {
httpDetails: response,
result: decodeReturnValue(func.retTypes, responseBytes),
}
: decodeReturnValue(func.retTypes, responseBytes);
}
else if (func.retTypes.length === 0) {
return undefined;
return shouldIncludeHttpDetails
? {
httpDetails: response,
result: undefined,
}
: undefined;
}

@@ -211,0 +234,0 @@ else {

@@ -5,2 +5,3 @@ import { Principal } from '@dfinity/principal';

import { Identity } from '../auth';
import { HttpHeaderField } from './http/types';
/**

@@ -34,2 +35,11 @@ * Codes used by the replica for rejecting a message.

}
export interface HttpDetailsResponse {
ok: boolean;
status: number;
statusText: string;
headers: HttpHeaderField[];
}
export declare type ApiQueryResponse = QueryResponse & {
httpDetails: HttpDetailsResponse;
};
export interface QueryResponseBase {

@@ -94,2 +104,3 @@ status: QueryResponseStatus;

} | null;
headers: HttpHeaderField[];
};

@@ -139,2 +150,3 @@ }

* @param options Options to use to create and send the query.
* @param identity Sender principal to use when sending the query.
* @returns The response from the replica. The Promise will only reject when the communication

@@ -144,3 +156,3 @@ * failed. If the query itself failed but no protocol errors happened, the response will

*/
query(canisterId: Principal | string, options: QueryFields): Promise<QueryResponse>;
query(canisterId: Principal | string, options: QueryFields, identity?: Identity | Promise<Identity>): Promise<ApiQueryResponse>;
/**

@@ -147,0 +159,0 @@ * By default, the agent is configured to talk to the main Internet Computer,

8

lib/cjs/agent/http/index.d.ts

@@ -5,3 +5,3 @@ import { JsonObject } from '@dfinity/candid';

import { Identity } from '../../auth';
import { Agent, QueryFields, QueryResponse, ReadStateOptions, ReadStateResponse, SubmitResponse } from '../api';
import { Agent, ApiQueryResponse, QueryFields, ReadStateOptions, ReadStateResponse, SubmitResponse } from '../api';
import { HttpAgentRequest, HttpAgentRequestTransformFn } from './types';

@@ -63,3 +63,3 @@ export * from './transforms';

private _rootKeyFetched;
private _retryTimes;
private readonly _retryTimes;
readonly _isAgent = true;

@@ -76,3 +76,3 @@ constructor(options?: HttpAgentOptions);

private _requestAndRetry;
query(canisterId: Principal | string, fields: QueryFields, identity?: Identity | Promise<Identity>): Promise<QueryResponse>;
query(canisterId: Principal | string, fields: QueryFields, identity?: Identity | Promise<Identity>): Promise<ApiQueryResponse>;
createReadStateRequest(fields: ReadStateOptions, identity?: Identity | Promise<Identity>): Promise<any>;

@@ -82,3 +82,3 @@ readState(canisterId: Principal | string, fields: ReadStateOptions, identity?: Identity | Promise<Identity>, request?: any): Promise<ReadStateResponse>;

* Allows agent to sync its time with the network. Can be called during intialization or mid-lifecycle if the device's clock has drifted away from the network time. This is necessary to set the Expiry for a request
* @param {PrincipalLike} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default
* @param {Principal} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default
*/

@@ -85,0 +85,0 @@ syncTime(canisterId?: Principal): Promise<void>;

@@ -38,2 +38,3 @@ "use strict";

const types_1 = require("./types");
const errors_2 = require("./errors");
__exportStar(require("./transforms"), exports);

@@ -123,3 +124,2 @@ var types_2 = require("./types");

this._rootKeyFetched = false;
this._retryTimes = 3; // Retry requests 3 times before erroring by default
this._isAgent = true;

@@ -160,6 +160,5 @@ if (options.source) {

}
// Default is 3, only set if option is provided
if (options.retryTimes !== undefined) {
this._retryTimes = options.retryTimes;
}
// Default is 3, only set from option if greater or equal to 0
this._retryTimes =
options.retryTimes !== undefined && options.retryTimes >= 0 ? options.retryTimes : 3;
// Rewrite to avoid redirects

@@ -249,2 +248,3 @@ if (this._host.hostname.endsWith(IC0_SUB_DOMAIN)) {

body: responseBody,
headers: (0, transforms_1.httpHeadersTransform)(response.headers),
},

@@ -254,20 +254,20 @@ };

async _requestAndRetry(request, tries = 0) {
if (tries > this._retryTimes && this._retryTimes !== 0) {
throw new Error(`AgentError: Exceeded configured limit of ${this._retryTimes} retry attempts. Please check your network connection or try again in a few moments`);
}
const response = await request();
if (!response.ok) {
const responseText = await response.clone().text();
const errorMessage = `Server returned an error:\n` +
` Code: ${response.status} (${response.statusText})\n` +
` Body: ${responseText}\n`;
if (this._retryTimes > tries) {
console.warn(errorMessage + ` Retrying request.`);
return await this._requestAndRetry(request, tries + 1);
}
else {
throw new Error(errorMessage);
}
if (response.ok) {
return response;
}
return response;
const responseText = await response.clone().text();
const errorMessage = `Server returned an error:\n` +
` Code: ${response.status} (${response.statusText})\n` +
` Body: ${responseText}\n`;
if (this._retryTimes > tries) {
console.warn(errorMessage + ` Retrying request.`);
return await this._requestAndRetry(request, tries + 1);
}
throw new errors_2.AgentHTTPResponseError(errorMessage, {
ok: response.ok,
status: response.status,
statusText: response.statusText,
headers: (0, transforms_1.httpHeadersTransform)(response.headers),
});
}

@@ -303,3 +303,9 @@ async query(canisterId, fields, identity) {

const response = await this._requestAndRetry(() => this._fetch('' + new URL(`/api/v2/canister/${canister.toText()}/query`, this._host), Object.assign(Object.assign(Object.assign({}, this._fetchOptions), transformedRequest.request), { body })));
return cbor.decode(await response.arrayBuffer());
const queryResponse = cbor.decode(await response.arrayBuffer());
return Object.assign(Object.assign({}, queryResponse), { httpDetails: {
ok: response.ok,
status: response.status,
statusText: response.statusText,
headers: (0, transforms_1.httpHeadersTransform)(response.headers),
} });
}

@@ -347,3 +353,3 @@ async createReadStateRequest(fields, identity) {

* Allows agent to sync its time with the network. Can be called during intialization or mid-lifecycle if the device's clock has drifted away from the network time. This is necessary to set the Expiry for a request
* @param {PrincipalLike} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default
* @param {Principal} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default
*/

@@ -350,0 +356,0 @@ async syncTime(canisterId) {

import * as cbor from 'simple-cbor';
import { HttpAgentRequestTransformFn, Nonce } from './types';
import { HttpAgentRequestTransformFn, HttpHeaderField, Nonce } from './types';
export declare class Expiry {

@@ -21,1 +21,8 @@ private readonly _value;

export declare function makeExpiryTransform(delayInMilliseconds: number): HttpAgentRequestTransformFn;
/**
* Maps the default fetch headers field to the serializable HttpHeaderField.
*
* @param headers Fetch definition of the headers type
* @returns array of header fields
*/
export declare function httpHeadersTransform(headers: Headers): HttpHeaderField[];

@@ -26,3 +26,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.makeExpiryTransform = exports.makeNonceTransform = exports.Expiry = void 0;
exports.httpHeadersTransform = exports.makeExpiryTransform = exports.makeNonceTransform = exports.Expiry = void 0;
const candid_1 = require("@dfinity/candid");

@@ -80,2 +80,16 @@ const cbor = __importStar(require("simple-cbor"));

exports.makeExpiryTransform = makeExpiryTransform;
/**
* Maps the default fetch headers field to the serializable HttpHeaderField.
*
* @param headers Fetch definition of the headers type
* @returns array of header fields
*/
function httpHeadersTransform(headers) {
const headerFields = [];
headers.forEach((value, key) => {
headerFields.push([key, value]);
});
return headerFields;
}
exports.httpHeadersTransform = httpHeadersTransform;
//# sourceMappingURL=transforms.js.map

@@ -16,2 +16,3 @@ import type { Principal } from '@dfinity/principal';

}
export declare type HttpHeaderField = [string, string];
export interface HttpAgentSubmitRequest extends HttpAgentBaseRequest {

@@ -18,0 +19,0 @@ readonly endpoint: Endpoint.Call;

import { JsonObject } from '@dfinity/candid';
import { Agent, CallOptions, QueryFields, QueryResponse, ReadStateOptions, ReadStateResponse, SubmitResponse } from './api';
import { Agent, ApiQueryResponse, CallOptions, QueryFields, QueryResponse, ReadStateOptions, ReadStateResponse, SubmitResponse } from './api';
import { Principal } from '@dfinity/principal';

@@ -81,5 +81,5 @@ export declare enum ProxyMessageKind {

status(): Promise<JsonObject>;
query(canisterId: Principal | string, fields: QueryFields): Promise<QueryResponse>;
query(canisterId: Principal | string, fields: QueryFields): Promise<ApiQueryResponse>;
private _sendAndWait;
fetchRootKey(): Promise<ArrayBuffer>;
}

@@ -1,2 +0,2 @@

import { Agent, QueryResponseRejected, SubmitResponse } from './agent';
import { Agent, HttpDetailsResponse, QueryResponseRejected, SubmitResponse } from './agent';
import { AgentError } from './errors';

@@ -76,3 +76,3 @@ import { IDL } from '@dfinity/candid';

*/
export interface ActorMethod<Args extends unknown[] = unknown[], Ret extends unknown = unknown> {
export interface ActorMethod<Args extends unknown[] = unknown[], Ret = unknown> {
(...args: Args): Promise<Ret>;

@@ -82,2 +82,15 @@ withOptions(options: CallConfig): (...args: Args) => Promise<Ret>;

/**
* An actor method type, defined for each methods of the actor service.
*/
export interface ActorMethodWithHttpDetails<Args extends unknown[] = unknown[], Ret = unknown> extends ActorMethod {
(...args: Args): Promise<{
httpDetails: HttpDetailsResponse;
result: Ret;
}>;
}
export declare type FunctionWithArgsAndReturn<Args extends unknown[] = unknown[], Ret = unknown> = (...args: Args) => Ret;
export declare type ActorMethodMappedWithHttpDetails<T> = {
[K in keyof T]: T[K] extends FunctionWithArgsAndReturn<infer Args, infer Ret> ? ActorMethodWithHttpDetails<Args, Ret> : never;
};
/**
* The mode used when installing a canister.

@@ -101,2 +114,5 @@ */

declare const metadataSymbol: unique symbol;
export interface CreateActorClassOpts {
httpDetails?: boolean;
}
/**

@@ -129,4 +145,5 @@ * An actor base class. An actor is an object containing only functions that will

}, config?: CallConfig): Promise<ActorSubclass>;
static createActorClass(interfaceFactory: IDL.InterfaceFactory): ActorConstructor;
static createActorClass(interfaceFactory: IDL.InterfaceFactory, options?: CreateActorClassOpts): ActorConstructor;
static createActor<T = Record<string, ActorMethod>>(interfaceFactory: IDL.InterfaceFactory, configuration: ActorConfig): ActorSubclass<T>;
static createActorWithHttpDetails<T = Record<string, ActorMethod>>(interfaceFactory: IDL.InterfaceFactory, configuration: ActorConfig): ActorSubclass<ActorMethodMappedWithHttpDetails<T>>;
private [metadataSymbol];

@@ -136,2 +153,3 @@ protected constructor(metadata: ActorMetadata);

export declare type ActorConstructor = new (config: ActorConfig) => ActorSubclass;
export declare const ACTOR_METHOD_WITH_HTTP_DETAILS = "http-details";
export declare type ManagementCanisterRecord = _SERVICE;

@@ -138,0 +156,0 @@ /**

@@ -110,3 +110,3 @@ import { Buffer } from 'buffer/';

}
static createActorClass(interfaceFactory) {
static createActorClass(interfaceFactory, options) {
const service = interfaceFactory({ IDL });

@@ -123,2 +123,5 @@ class CanisterActor extends Actor {

for (const [methodName, func] of service._fields) {
if (options === null || options === void 0 ? void 0 : options.httpDetails) {
func.annotations.push(ACTOR_METHOD_WITH_HTTP_DETAILS);
}
this[methodName] = _createActorMethod(this, methodName, func, config.blsVerify);

@@ -133,2 +136,5 @@ }

}
static createActorWithHttpDetails(interfaceFactory, configuration) {
return new (this.createActorClass(interfaceFactory, { httpDetails: true }))(configuration);
}
}

@@ -152,2 +158,3 @@ // IDL functions can have multiple return values, so decoding always

};
export const ACTOR_METHOD_WITH_HTTP_DETAILS = 'http-details';
function _createActorMethod(actor, methodName, func, blsVerify) {

@@ -168,3 +175,8 @@ let caller;

case "replied" /* QueryResponseStatus.Replied */:
return decodeReturnValue(func.retTypes, result.reply.arg);
return func.annotations.includes(ACTOR_METHOD_WITH_HTTP_DETAILS)
? {
httpDetails: result.httpDetails,
result: decodeReturnValue(func.retTypes, result.reply.arg),
}
: decodeReturnValue(func.retTypes, result.reply.arg);
}

@@ -193,7 +205,18 @@ };

const responseBytes = await pollForResponse(agent, ecid, requestId, pollStrategy, blsVerify);
const shouldIncludeHttpDetails = func.annotations.includes(ACTOR_METHOD_WITH_HTTP_DETAILS);
if (responseBytes !== undefined) {
return decodeReturnValue(func.retTypes, responseBytes);
return shouldIncludeHttpDetails
? {
httpDetails: response,
result: decodeReturnValue(func.retTypes, responseBytes),
}
: decodeReturnValue(func.retTypes, responseBytes);
}
else if (func.retTypes.length === 0) {
return undefined;
return shouldIncludeHttpDetails
? {
httpDetails: response,
result: undefined,
}
: undefined;
}

@@ -200,0 +223,0 @@ else {

@@ -5,2 +5,3 @@ import { Principal } from '@dfinity/principal';

import { Identity } from '../auth';
import { HttpHeaderField } from './http/types';
/**

@@ -34,2 +35,11 @@ * Codes used by the replica for rejecting a message.

}
export interface HttpDetailsResponse {
ok: boolean;
status: number;
statusText: string;
headers: HttpHeaderField[];
}
export declare type ApiQueryResponse = QueryResponse & {
httpDetails: HttpDetailsResponse;
};
export interface QueryResponseBase {

@@ -94,2 +104,3 @@ status: QueryResponseStatus;

} | null;
headers: HttpHeaderField[];
};

@@ -139,2 +150,3 @@ }

* @param options Options to use to create and send the query.
* @param identity Sender principal to use when sending the query.
* @returns The response from the replica. The Promise will only reject when the communication

@@ -144,3 +156,3 @@ * failed. If the query itself failed but no protocol errors happened, the response will

*/
query(canisterId: Principal | string, options: QueryFields): Promise<QueryResponse>;
query(canisterId: Principal | string, options: QueryFields, identity?: Identity | Promise<Identity>): Promise<ApiQueryResponse>;
/**

@@ -147,0 +159,0 @@ * By default, the agent is configured to talk to the main Internet Computer,

@@ -5,3 +5,3 @@ import { JsonObject } from '@dfinity/candid';

import { Identity } from '../../auth';
import { Agent, QueryFields, QueryResponse, ReadStateOptions, ReadStateResponse, SubmitResponse } from '../api';
import { Agent, ApiQueryResponse, QueryFields, ReadStateOptions, ReadStateResponse, SubmitResponse } from '../api';
import { HttpAgentRequest, HttpAgentRequestTransformFn } from './types';

@@ -63,3 +63,3 @@ export * from './transforms';

private _rootKeyFetched;
private _retryTimes;
private readonly _retryTimes;
readonly _isAgent = true;

@@ -76,3 +76,3 @@ constructor(options?: HttpAgentOptions);

private _requestAndRetry;
query(canisterId: Principal | string, fields: QueryFields, identity?: Identity | Promise<Identity>): Promise<QueryResponse>;
query(canisterId: Principal | string, fields: QueryFields, identity?: Identity | Promise<Identity>): Promise<ApiQueryResponse>;
createReadStateRequest(fields: ReadStateOptions, identity?: Identity | Promise<Identity>): Promise<any>;

@@ -82,3 +82,3 @@ readState(canisterId: Principal | string, fields: ReadStateOptions, identity?: Identity | Promise<Identity>, request?: any): Promise<ReadStateResponse>;

* Allows agent to sync its time with the network. Can be called during intialization or mid-lifecycle if the device's clock has drifted away from the network time. This is necessary to set the Expiry for a request
* @param {PrincipalLike} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default
* @param {Principal} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default
*/

@@ -85,0 +85,0 @@ syncTime(canisterId?: Principal): Promise<void>;

@@ -7,4 +7,5 @@ import { Principal } from '@dfinity/principal';

import { fromHex } from '../../utils/buffer';
import { Expiry, makeNonceTransform } from './transforms';
import { Expiry, httpHeadersTransform, makeNonceTransform } from './transforms';
import { makeNonce, SubmitRequestType, } from './types';
import { AgentHTTPResponseError } from './errors';
export * from './transforms';

@@ -92,3 +93,2 @@ export { makeNonce } from './types';

this._rootKeyFetched = false;
this._retryTimes = 3; // Retry requests 3 times before erroring by default
this._isAgent = true;

@@ -129,6 +129,5 @@ if (options.source) {

}
// Default is 3, only set if option is provided
if (options.retryTimes !== undefined) {
this._retryTimes = options.retryTimes;
}
// Default is 3, only set from option if greater or equal to 0
this._retryTimes =
options.retryTimes !== undefined && options.retryTimes >= 0 ? options.retryTimes : 3;
// Rewrite to avoid redirects

@@ -218,2 +217,3 @@ if (this._host.hostname.endsWith(IC0_SUB_DOMAIN)) {

body: responseBody,
headers: httpHeadersTransform(response.headers),
},

@@ -223,20 +223,20 @@ };

async _requestAndRetry(request, tries = 0) {
if (tries > this._retryTimes && this._retryTimes !== 0) {
throw new Error(`AgentError: Exceeded configured limit of ${this._retryTimes} retry attempts. Please check your network connection or try again in a few moments`);
}
const response = await request();
if (!response.ok) {
const responseText = await response.clone().text();
const errorMessage = `Server returned an error:\n` +
` Code: ${response.status} (${response.statusText})\n` +
` Body: ${responseText}\n`;
if (this._retryTimes > tries) {
console.warn(errorMessage + ` Retrying request.`);
return await this._requestAndRetry(request, tries + 1);
}
else {
throw new Error(errorMessage);
}
if (response.ok) {
return response;
}
return response;
const responseText = await response.clone().text();
const errorMessage = `Server returned an error:\n` +
` Code: ${response.status} (${response.statusText})\n` +
` Body: ${responseText}\n`;
if (this._retryTimes > tries) {
console.warn(errorMessage + ` Retrying request.`);
return await this._requestAndRetry(request, tries + 1);
}
throw new AgentHTTPResponseError(errorMessage, {
ok: response.ok,
status: response.status,
statusText: response.statusText,
headers: httpHeadersTransform(response.headers),
});
}

@@ -272,3 +272,9 @@ async query(canisterId, fields, identity) {

const response = await this._requestAndRetry(() => this._fetch('' + new URL(`/api/v2/canister/${canister.toText()}/query`, this._host), Object.assign(Object.assign(Object.assign({}, this._fetchOptions), transformedRequest.request), { body })));
return cbor.decode(await response.arrayBuffer());
const queryResponse = cbor.decode(await response.arrayBuffer());
return Object.assign(Object.assign({}, queryResponse), { httpDetails: {
ok: response.ok,
status: response.status,
statusText: response.statusText,
headers: httpHeadersTransform(response.headers),
} });
}

@@ -316,3 +322,3 @@ async createReadStateRequest(fields, identity) {

* Allows agent to sync its time with the network. Can be called during intialization or mid-lifecycle if the device's clock has drifted away from the network time. This is necessary to set the Expiry for a request
* @param {PrincipalLike} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default
* @param {Principal} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default
*/

@@ -319,0 +325,0 @@ async syncTime(canisterId) {

import * as cbor from 'simple-cbor';
import { HttpAgentRequestTransformFn, Nonce } from './types';
import { HttpAgentRequestTransformFn, HttpHeaderField, Nonce } from './types';
export declare class Expiry {

@@ -21,1 +21,8 @@ private readonly _value;

export declare function makeExpiryTransform(delayInMilliseconds: number): HttpAgentRequestTransformFn;
/**
* Maps the default fetch headers field to the serializable HttpHeaderField.
*
* @param headers Fetch definition of the headers type
* @returns array of header fields
*/
export declare function httpHeadersTransform(headers: Headers): HttpHeaderField[];
import { lebEncode } from '@dfinity/candid';
import * as cbor from 'simple-cbor';
import { makeNonce } from './types';
import { makeNonce, } from './types';
const NANOSECONDS_PER_MILLISECONDS = BigInt(1000000);

@@ -50,2 +50,15 @@ const REPLICA_PERMITTED_DRIFT_MILLISECONDS = BigInt(60 * 1000);

}
/**
* Maps the default fetch headers field to the serializable HttpHeaderField.
*
* @param headers Fetch definition of the headers type
* @returns array of header fields
*/
export function httpHeadersTransform(headers) {
const headerFields = [];
headers.forEach((value, key) => {
headerFields.push([key, value]);
});
return headerFields;
}
//# sourceMappingURL=transforms.js.map

@@ -16,2 +16,3 @@ import type { Principal } from '@dfinity/principal';

}
export declare type HttpHeaderField = [string, string];
export interface HttpAgentSubmitRequest extends HttpAgentBaseRequest {

@@ -18,0 +19,0 @@ readonly endpoint: Endpoint.Call;

import { JsonObject } from '@dfinity/candid';
import { Agent, CallOptions, QueryFields, QueryResponse, ReadStateOptions, ReadStateResponse, SubmitResponse } from './api';
import { Agent, ApiQueryResponse, CallOptions, QueryFields, QueryResponse, ReadStateOptions, ReadStateResponse, SubmitResponse } from './api';
import { Principal } from '@dfinity/principal';

@@ -81,5 +81,5 @@ export declare enum ProxyMessageKind {

status(): Promise<JsonObject>;
query(canisterId: Principal | string, fields: QueryFields): Promise<QueryResponse>;
query(canisterId: Principal | string, fields: QueryFields): Promise<ApiQueryResponse>;
private _sendAndWait;
fetchRootKey(): Promise<ArrayBuffer>;
}
{
"name": "@dfinity/agent",
"version": "0.17.0",
"version": "0.18.0",
"author": "DFINITY Stiftung <sdk@dfinity.org>",

@@ -53,4 +53,4 @@ "license": "Apache-2.0",

"peerDependencies": {
"@dfinity/candid": "^0.17.0",
"@dfinity/principal": "^0.17.0"
"@dfinity/candid": "^0.18.0",
"@dfinity/principal": "^0.18.0"
},

@@ -57,0 +57,0 @@ "dependencies": {

@@ -57,2 +57,8 @@ # @dfinity/agent

Actors can also be initialized to include the boundary node http headers, This is done by calling the `Actor.createActor` constructor:
```
Actor.createActorWithHttpDetails(interfaceFactory: InterfaceFactory, configuration: ActorConfig): ActorSubclass<ActorMethodMappedWithHttpDetails<T>>
```
### Inspecting an actor's agent

@@ -59,0 +65,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc