or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

configuration.mdevents.mdindex.mdrequests.mdservices.mdutilities.md
tile.json

utilities.mddocs/

Utilities & Helpers

The AWS SDK provides an extensive utility library (AWS.util) with encoding, cryptographic functions, date handling, object manipulation, and AWS-specific operations.

Core Utilities

AWS.util Object

const AWS = require('aws-sdk');

const util = AWS.util = {
  // Encoding & Decoding
  base64: {
    encode(string: string): string;
    decode(string: string): string;
  };
  
  uriEscape(string: string): string;
  uriEscapePath(string: string): string;
  
  // Buffer Operations
  buffer: {
    toBuffer(data: any, encoding?: string): Buffer;
    alloc(size: number, fill?: any, encoding?: string): Buffer;
    concat(buffers: Buffer[], totalLength?: number): Buffer;
  };
  
  // Cryptographic Functions
  crypto: {
    hmac(key: any, string: string, digest?: string, fn?: Function): string | Buffer;
    md5(data: any, digest?: string, callback?: Function): string | Buffer;
    sha256(data: any, digest?: string, callback?: Function): string | Buffer;
    sha1(data: any, digest?: string, callback?: Function): string | Buffer;
    crc32(data: any): number;
    toHex(data: any): string;
    createHash(algorithm: string): any;
  };
  
  // Date & Time Operations
  date: {
    getDate(): Date;
    iso8601(date?: Date): string;
    rfc822(date?: Date): string;
    unixTimestamp(date?: Date): number;
    parseTimestamp(value: any): Date;
    from(date: any): Date;
  };
  
  // Object Manipulation
  each(object: any, iterFunction: (key: string, value: any) => void): void;
  arrayEach(array: any[], iterFunction: (item: any, index: number) => void): void;
  update(obj1: any, obj2: any): any;
  merge(obj1: any, obj2: any): any;
  copy(object: any): any;
  deepCopy(object: any): any;
  isEmpty(obj: any): boolean;
  strictDeepEqual(first: any, second: any): boolean;
  
  // Type Checking
  isType(obj: any, type: string): boolean;
  typeName(type: any): string;
  isNode(): boolean;
  isBrowser(): boolean;
  isReactNative(): boolean;
  
  // String Operations
  string: {
    byteLength(string: string, encoding?: string): number;
    upperFirst(string: string): string;
    lowerFirst(string: string): string;
    trim(string: string): string;
  };
  
  // Error Handling
  error(err: Error, options?: any): AWSError;
  extractRequestId(resp: any): string;
  
  // Promise Support
  addPromises(constructors: any[], PromiseDependency?: any): void;
  promisifyMethod(methodName: string, PromiseDependency?: any): Function;
  defer(): { promise: Promise<any>, resolve: Function, reject: Function };
  
  // AWS-Specific Utilities
  isDualstackAvailable(service: string): boolean;
  calculateRetryDelay(retryCount: number, options?: any, err?: Error): number;
  jamespath: {
    search(data: any, expression: string): any;
  };
  
  // ARN Operations
  ARN: {
    validate(str: string): boolean;
    parse(arn: string): ARNComponents;
    build(arnObject: ARNComponents): string;
  };
  
  // UUID Generation
  uuid: {
    v4(): string;
  };
  
  // Configuration Loading
  getProfilesFromSharedConfig(iniLoader: any, filename?: string): any;
  iniLoader: any;
  
  // INI File Parsing
  ini: {
    parse(string: string): any;
  };
  
  // HTTP & Networking
  getAgent(endpoint: any, agentOptions?: any): any;
  getUserAgentString(): string;
  isFipsRegion(region: string): boolean;
  getRealRegion(region: string): string;
  
  // File Operations (Node.js only)
  readFileSync(path: string): Buffer;
  
  // URL Operations
  urlParse(url: string): any;
  urlFormat(url: any): string;
  queryStringParse(qs: string): any;
  queryParamsToString(params: any): string;
  
  // Class Inheritance
  inherit(klass: Function, features: any): Function;
  mixin(obj: any, ...sources: any[]): any;
}

Encoding & Decoding

Base64 Operations

const AWS = require('aws-sdk');

// Encode string to base64
const encoded = AWS.util.base64.encode('Hello World');
console.log(encoded); // "SGVsbG8gV29ybGQ="

// Decode base64 to string
const decoded = AWS.util.base64.decode(encoded);
console.log(decoded); // "Hello World"

// Binary data encoding
const binaryData = Buffer.from([1, 2, 3, 4, 5]);
const encodedBinary = AWS.util.base64.encode(binaryData);
const decodedBinary = AWS.util.base64.decode(encodedBinary);

URI Encoding

// URI encode string
const encoded = AWS.util.uriEscape('hello world/test');
console.log(encoded); // "hello%20world%2Ftest"

// URI encode path (preserves forward slashes)
const encodedPath = AWS.util.uriEscapePath('folder/file name.txt');
console.log(encodedPath); // "folder/file%20name.txt"

Cryptographic Functions

Hashing Operations

const data = 'Hello World';

// MD5 hash
const md5Hash = AWS.util.crypto.md5(data, 'hex');
console.log(md5Hash); // "b10a8db164e0754105b7a99be72e3fe5"

// SHA-256 hash
const sha256Hash = AWS.util.crypto.sha256(data, 'hex');
console.log(sha256Hash); // "a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e"

// SHA-1 hash
const sha1Hash = AWS.util.crypto.sha1(data, 'hex');

// With callback (for large data)
AWS.util.crypto.sha256(data, 'hex', (hash) => {
  console.log('SHA-256:', hash);
});

HMAC Operations

const key = 'secret-key';
const message = 'Hello World';

// HMAC-SHA256
const hmac = AWS.util.crypto.hmac(key, message, 'sha256', 'hex');
console.log(hmac);

// HMAC with different digest formats
const hmacBase64 = AWS.util.crypto.hmac(key, message, 'sha256', 'base64');
const hmacBinary = AWS.util.crypto.hmac(key, message, 'sha256');

Checksums

const data = Buffer.from('Hello World');

// CRC32 checksum
const crc32 = AWS.util.crypto.crc32(data);
console.log(crc32); // Number

// Convert to hexadecimal
const hex = AWS.util.crypto.toHex(data);
console.log(hex); // "48656c6c6f20576f726c64"

Date & Time Operations

Date Formatting

const now = new Date();

// Get current date with clock offset
const adjustedDate = AWS.util.date.getDate();

// ISO 8601 format
const iso8601 = AWS.util.date.iso8601(now);
console.log(iso8601); // "2023-12-07T10:30:00.000Z"

// RFC 822 format
const rfc822 = AWS.util.date.rfc822(now);
console.log(rfc822); // "Thu, 07 Dec 2023 10:30:00 GMT"

// Unix timestamp
const timestamp = AWS.util.date.unixTimestamp(now);
console.log(timestamp); // 1701943800

// Parse various timestamp formats
const parsed = AWS.util.date.parseTimestamp('2023-12-07T10:30:00Z');
const parsed2 = AWS.util.date.parseTimestamp(1701943800);

Object Manipulation

Object Iteration

const obj = { a: 1, b: 2, c: 3 };

// Iterate over object properties
AWS.util.each(obj, (key, value) => {
  console.log(`${key}: ${value}`);
});

// Iterate over array
const arr = ['apple', 'banana', 'cherry'];
AWS.util.arrayEach(arr, (item, index) => {
  console.log(`${index}: ${item}`);
});

Object Operations

const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };

// Update object (shallow merge)
const updated = AWS.util.update(obj1, obj2);
console.log(updated); // { a: 1, b: 3, c: 4 }

// Deep merge objects
const nested1 = { a: { x: 1, y: 2 } };
const nested2 = { a: { y: 3, z: 4 }, b: 5 };
const merged = AWS.util.merge(nested1, nested2);
console.log(merged); // { a: { x: 1, y: 3, z: 4 }, b: 5 }

// Copy object (shallow)
const copied = AWS.util.copy(obj1);

// Deep copy object
const deepCopied = AWS.util.deepCopy(nested1);

// Check if object is empty
const isEmpty = AWS.util.isEmpty({});        // true
const isNotEmpty = AWS.util.isEmpty({ a: 1 }); // false

// Deep equality comparison
const isEqual = AWS.util.strictDeepEqual(obj1, { a: 1, b: 2 }); // true

Type Checking & Validation

Type Operations

// Type checking
const isString = AWS.util.isType('hello', 'string');     // true
const isArray = AWS.util.isType([1, 2, 3], 'array');     // true
const isObject = AWS.util.isType({}, 'object');          // true

// Get type name
const typeName = AWS.util.typeName('hello');             // "string"
const arrayTypeName = AWS.util.typeName([]);             // "array"

// Environment detection
const isNodeJs = AWS.util.isNode();                      // true in Node.js
const isBrowserEnv = AWS.util.isBrowser();               // true in browser
const isReactNativeEnv = AWS.util.isReactNative();       // true in React Native

String Operations

String Utilities

// Byte length of string
const byteLength = AWS.util.string.byteLength('Hello 世界');
console.log(byteLength); // Actual byte length

// String case manipulation
const upperFirst = AWS.util.string.upperFirst('hello world');  // "Hello world"
const lowerFirst = AWS.util.string.lowerFirst('Hello World');  // "hello World"

// Trim whitespace
const trimmed = AWS.util.string.trim('  hello world  ');       // "hello world"

Buffer Operations

Buffer Utilities

// Convert to buffer
const buffer = AWS.util.buffer.toBuffer('hello', 'utf8');

// Allocate buffer
const allocated = AWS.util.buffer.alloc(10, 0);

// Concatenate buffers
const buf1 = Buffer.from('hello');
const buf2 = Buffer.from(' world');
const concatenated = AWS.util.buffer.concat([buf1, buf2]);
console.log(concatenated.toString()); // "hello world"

AWS-Specific Utilities

ARN Operations

interface ARNComponents {
  partition: string;
  service: string;
  region: string;
  accountId: string;
  resource: string;
}
const arn = 'arn:aws:s3:::my-bucket/my-object';

// Validate ARN format
const isValid = AWS.util.ARN.validate(arn); // true

// Parse ARN into components
const parsed = AWS.util.ARN.parse(arn);
console.log(parsed);
// {
//   partition: 'aws',
//   service: 's3',
//   region: '',
//   accountId: '',
//   resource: 'my-bucket/my-object'
// }

// Build ARN from components
const rebuilt = AWS.util.ARN.build({
  partition: 'aws',
  service: 'dynamodb',
  region: 'us-east-1',
  accountId: '123456789012',
  resource: 'table/MyTable'
});
console.log(rebuilt); // "arn:aws:dynamodb:us-east-1:123456789012:table/MyTable"

JMESPath Queries

const data = {
  users: [
    { name: 'Alice', age: 25, active: true },
    { name: 'Bob', age: 30, active: false },
    { name: 'Charlie', age: 35, active: true }
  ]
};

// JMESPath query
const activeUsers = AWS.util.jamespath.search(data, 'users[?active]');
console.log(activeUsers); // [{ name: 'Alice', ... }, { name: 'Charlie', ... }]

const names = AWS.util.jamespath.search(data, 'users[].name');
console.log(names); // ['Alice', 'Bob', 'Charlie']

UUID Generation

// Generate UUID v4
const uuid = AWS.util.uuid.v4();
console.log(uuid); // "f47ac10b-58cc-4372-a567-0e02b2c3d479"

Retry Delay Calculation

// Calculate retry delay
const delay1 = AWS.util.calculateRetryDelay(1); // First retry
const delay2 = AWS.util.calculateRetryDelay(2); // Second retry

// With custom options
const customDelay = AWS.util.calculateRetryDelay(1, {
  base: 300,
  customBackoff: (retryCount) => retryCount * 1000
});

Error Utilities

Enhanced Error Creation

// Create AWS error
const baseError = new Error('Something went wrong');
const awsError = AWS.util.error(baseError, {
  code: 'CustomError',
  statusCode: 500,
  retryable: true
});

console.log(awsError.code);        // "CustomError"
console.log(awsError.statusCode);  // 500
console.log(awsError.retryable);   // true

// Extract request ID from response
const requestId = AWS.util.extractRequestId(response);

Promise Integration

Promise Utilities

// Add promise support to constructors
AWS.util.addPromises([CustomClass]);

// Promisify method
const promisifiedMethod = AWS.util.promisifyMethod('methodName');

// Create deferred promise
const deferred = AWS.util.defer();
setTimeout(() => {
  deferred.resolve('success');
}, 1000);
deferred.promise.then(result => console.log(result));

Configuration & File Operations

INI File Operations

// Parse INI file content
const iniContent = `
[default]
region = us-east-1
output = json

[production]
region = us-west-2
output = table
`;

const parsed = AWS.util.ini.parse(iniContent);
console.log(parsed);
// {
//   default: { region: 'us-east-1', output: 'json' },
//   production: { region: 'us-west-2', output: 'table' }
// }

// Load profiles from shared config
const profiles = AWS.util.getProfilesFromSharedConfig(AWS.util.iniLoader);

URL Operations

// Parse URL
const parsed = AWS.util.urlParse('https://s3.amazonaws.com/bucket/key?prefix=test');
console.log(parsed);
// { protocol: 'https:', hostname: 's3.amazonaws.com', pathname: '/bucket/key', ... }

// Format URL
const formatted = AWS.util.urlFormat({
  protocol: 'https:',
  hostname: 's3.amazonaws.com',
  pathname: '/bucket/key',
  search: '?prefix=test'
});

// Query string operations
const queryObj = AWS.util.queryStringParse('name=value&foo=bar');
console.log(queryObj); // { name: 'value', foo: 'bar' }

const queryString = AWS.util.queryParamsToString({ name: 'value', foo: 'bar' });
console.log(queryString); // "name=value&foo=bar"