Web standard APIs including base64 encoding, URL handling, structured cloning, microtask scheduling, and other browser-compatible utilities.
Standard base64 encoding and decoding functions for binary data handling.
/**
* Global base64 encoding/decoding functions
*/
declare function atob(encodedData: string): string;
declare function btoa(stringToEncode: string): string;Usage Examples:
import { atob, btoa } from 'core-js-pure/stable/atob';
import { btoa } from 'core-js-pure/stable/btoa';
// Basic base64 operations
const originalText = "Hello, World!";
const encoded = btoa(originalText);
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="
const decoded = atob(encoded);
console.log(decoded); // "Hello, World!"
// Binary data encoding
const binaryData = String.fromCharCode(0, 1, 2, 3, 255);
const encodedBinary = btoa(binaryData);
const decodedBinary = atob(encodedBinary);
console.log(binaryData === decodedBinary); // true
// URL-safe encoding utility
const createUrlSafeBase64 = (str) => {
return btoa(str)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
const parseUrlSafeBase64 = (str) => {
// Add padding and restore characters
const padded = str + '='.repeat((4 - str.length % 4) % 4);
const standard = padded.replace(/-/g, '+').replace(/_/g, '/');
return atob(standard);
};
const token = "secure-token-data";
const urlSafe = createUrlSafeBase64(token);
console.log(urlSafe);
console.log(parseUrlSafeBase64(urlSafe) === token); // true
// JWT-like token creation (simplified)
const createJWT = (header, payload, secret) => {
const encodedHeader = createUrlSafeBase64(JSON.stringify(header));
const encodedPayload = createUrlSafeBase64(JSON.stringify(payload));
const signature = createUrlSafeBase64(`${encodedHeader}.${encodedPayload}.${secret}`);
return `${encodedHeader}.${encodedPayload}.${signature}`;
};
const jwt = createJWT(
{ alg: 'HS256', typ: 'JWT' },
{ sub: '1234567890', name: 'John Doe', iat: 1516239022 },
'secret-key'
);
console.log(jwt);Complete URL parsing and manipulation with search parameter handling.
/**
* URL constructor and methods
*/
interface URLConstructor {
/**
* Creates a new URL object
* @param url - URL string to parse
* @param base - Optional base URL
*/
new (url: string, base?: string | URL): URL;
}
interface URL {
readonly hash: string;
readonly host: string;
readonly hostname: string;
readonly href: string;
readonly origin: string;
readonly password: string;
readonly pathname: string;
readonly port: string;
readonly protocol: string;
readonly search: string;
readonly searchParams: URLSearchParams;
readonly username: string;
toString(): string;
toJSON(): string;
}
/**
* URLSearchParams constructor and methods
*/
interface URLSearchParamsConstructor {
/**
* Creates a new URLSearchParams object
* @param init - Initial parameters as string, array, or object
*/
new (init?: string | string[][] | Record<string, string> | URLSearchParams): URLSearchParams;
}
interface URLSearchParams {
/**
* Appends a key-value pair
*/
append(name: string, value: string): void;
/**
* Deletes all parameters with given name
*/
delete(name: string): void;
/**
* Returns iterator of [name, value] pairs
*/
entries(): IterableIterator<[string, string]>;
/**
* Executes callback for each parameter
*/
forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void, thisArg?: any): void;
/**
* Gets first value for parameter name
*/
get(name: string): string | null;
/**
* Gets all values for parameter name
*/
getAll(name: string): string[];
/**
* Checks if parameter exists
*/
has(name: string): boolean;
/**
* Returns iterator of parameter names
*/
keys(): IterableIterator<string>;
/**
* Sets parameter to single value
*/
set(name: string, value: string): void;
/**
* Sorts parameters by name
*/
sort(): void;
/**
* Returns URL-encoded string
*/
toString(): string;
/**
* Returns iterator of parameter values
*/
values(): IterableIterator<string>;
[Symbol.iterator](): IterableIterator<[string, string]>;
}Usage Examples:
import URL from 'core-js-pure/stable/url';
import URLSearchParams from 'core-js-pure/stable/url-search-params';
// URL parsing and manipulation
const url = new URL('https://example.com:8080/path/to/resource?param1=value1¶m2=value2#section');
console.log(url.protocol); // "https:"
console.log(url.hostname); // "example.com"
console.log(url.port); // "8080"
console.log(url.pathname); // "/path/to/resource"
console.log(url.search); // "?param1=value1¶m2=value2"
console.log(url.hash); // "#section"
console.log(url.origin); // "https://example.com:8080"
// Working with relative URLs
const baseUrl = 'https://api.example.com/v1/';
const resourceUrl = new URL('users/123', baseUrl);
console.log(resourceUrl.href); // "https://api.example.com/v1/users/123"
// URLSearchParams manipulation
const params = new URLSearchParams('name=John&age=30&city=NYC');
// Basic operations
console.log(params.get('name')); // "John"
console.log(params.has('age')); // true
params.set('age', '31');
params.append('hobby', 'reading');
params.append('hobby', 'coding'); // Multiple values
console.log(params.toString()); // "name=John&age=31&city=NYC&hobby=reading&hobby=coding"
console.log(params.getAll('hobby')); // ["reading", "coding"]
// Iteration
for (const [key, value] of params) {
console.log(`${key}: ${value}`);
}
// URL builder utility
class URLBuilder {
constructor(base) {
this.url = new URL(base);
}
path(...segments) {
const cleanedSegments = segments
.map(s => s.toString().replace(/^\/+|\/+$/g, ''))
.filter(s => s.length > 0);
this.url.pathname = '/' + cleanedSegments.join('/');
return this;
}
query(params) {
for (const [key, value] of Object.entries(params)) {
if (Array.isArray(value)) {
value.forEach(v => this.url.searchParams.append(key, v.toString()));
} else if (value !== undefined && value !== null) {
this.url.searchParams.set(key, value.toString());
}
}
return this;
}
hash(fragment) {
this.url.hash = fragment;
return this;
}
build() {
return this.url.href;
}
}
// Usage
const apiUrl = new URLBuilder('https://api.example.com')
.path('v1', 'users', 123, 'posts')
.query({
page: 2,
limit: 10,
tags: ['javascript', 'web'],
include: 'comments'
})
.hash('top')
.build();
console.log(apiUrl);
// "https://api.example.com/v1/users/123/posts?page=2&limit=10&tags=javascript&tags=web&include=comments#top"Deep cloning of objects with support for complex data types.
/**
* Structured cloning function
*/
declare function structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;
interface StructuredSerializeOptions {
transfer?: Transferable[];
}Usage Examples:
import structuredClone from 'core-js-pure/stable/structured-clone';
// Basic object cloning
const original = {
name: 'Alice',
age: 30,
hobbies: ['reading', 'coding'],
address: {
city: 'NYC',
zipCode: '10001'
}
};
const cloned = structuredClone(original);
cloned.hobbies.push('gaming');
cloned.address.city = 'LA';
console.log(original.hobbies); // ['reading', 'coding'] (unchanged)
console.log(original.address.city); // 'NYC' (unchanged)
console.log(cloned.hobbies); // ['reading', 'coding', 'gaming']
console.log(cloned.address.city); // 'LA'
// Cloning complex types
const complexData = {
date: new Date('2024-01-01'),
regex: /hello/gi,
map: new Map([['key1', 'value1'], ['key2', 'value2']]),
set: new Set([1, 2, 3]),
buffer: new ArrayBuffer(8),
error: new Error('Test error')
};
const complexClone = structuredClone(complexData);
console.log(complexClone.date instanceof Date); // true
console.log(complexClone.map instanceof Map); // true
console.log(complexClone.set.has(2)); // true
// Safe cloning utility
const safeClone = (obj) => {
try {
return structuredClone(obj);
} catch (error) {
console.warn('Structured clone failed, falling back to JSON:', error);
return JSON.parse(JSON.stringify(obj));
}
};
// Cloning with circular references (throws error)
const circular = { name: 'test' };
circular.self = circular;
try {
const clonedCircular = structuredClone(circular);
} catch (error) {
console.log('Cannot clone circular structure:', error.message);
}
// Message passing simulation
const createMessage = (type, data) => ({
id: Math.random().toString(36),
type,
data: structuredClone(data), // Ensure data is safely serializable
timestamp: Date.now()
});
const message = createMessage('user-update', {
userId: 123,
profile: {
name: 'John',
preferences: new Map([['theme', 'dark'], ['lang', 'en']])
}
});
console.log(message);Scheduling functions to run in the next microtask queue.
/**
* Queue microtask function
*/
declare function queueMicrotask(callback: VoidFunction): void;Usage Examples:
import queueMicrotask from 'core-js-pure/stable/queue-microtask';
// Basic microtask scheduling
console.log('Start');
queueMicrotask(() => {
console.log('Microtask 1');
});
queueMicrotask(() => {
console.log('Microtask 2');
});
Promise.resolve().then(() => {
console.log('Promise microtask');
});
setTimeout(() => {
console.log('Timeout (macrotask)');
}, 0);
console.log('End');
// Output order:
// Start
// End
// Microtask 1
// Microtask 2
// Promise microtask
// Timeout (macrotask)
// Batch DOM updates
class DOMBatcher {
constructor() {
this.updates = [];
this.scheduled = false;
}
scheduleUpdate(element, property, value) {
this.updates.push({ element, property, value });
if (!this.scheduled) {
this.scheduled = true;
queueMicrotask(() => {
this.flushUpdates();
});
}
}
flushUpdates() {
const updates = this.updates.splice(0);
this.scheduled = false;
// Apply all updates in one batch
updates.forEach(({ element, property, value }) => {
element.style[property] = value;
});
console.log(`Applied ${updates.length} DOM updates`);
}
}
const batcher = new DOMBatcher();
// These will be batched into a single DOM update
// batcher.scheduleUpdate(element1, 'color', 'red');
// batcher.scheduleUpdate(element2, 'fontSize', '16px');
// batcher.scheduleUpdate(element3, 'margin', '10px');
// State synchronization utility
class StateManager {
constructor() {
this.state = {};
this.listeners = [];
this.notificationScheduled = false;
}
setState(updates) {
Object.assign(this.state, updates);
this.scheduleNotification();
}
subscribe(listener) {
this.listeners.push(listener);
return () => {
const index = this.listeners.indexOf(listener);
if (index > -1) {
this.listeners.splice(index, 1);
}
};
}
scheduleNotification() {
if (!this.notificationScheduled) {
this.notificationScheduled = true;
queueMicrotask(() => {
this.notifyListeners();
});
}
}
notifyListeners() {
this.notificationScheduled = false;
const currentState = { ...this.state };
this.listeners.forEach(listener => {
try {
listener(currentState);
} catch (error) {
console.error('State listener error:', error);
}
});
}
}
const stateManager = new StateManager();
stateManager.subscribe(state => {
console.log('State updated:', state);
});
// These updates will be batched
stateManager.setState({ user: 'Alice' });
stateManager.setState({ age: 30 });
stateManager.setState({ city: 'NYC' });
// Only one notification will be triggeredAccess to the global object across different environments.
/**
* Global object reference
*/
declare var globalThis: typeof globalThis;Usage Examples:
import 'core-js-pure/stable/global-this';
// Cross-environment global access
const getGlobal = () => {
// Works in browsers, Node.js, Web Workers, etc.
return globalThis;
};
// Feature detection utility
const hasFeature = (featureName) => {
return featureName in globalThis;
};
console.log(hasFeature('fetch')); // true in browsers
console.log(hasFeature('process')); // true in Node.js
// Polyfill registration
const registerPolyfill = (name, implementation) => {
if (!hasFeature(name)) {
globalThis[name] = implementation;
}
};
// Environment-specific utilities
const getEnvironment = () => {
if (typeof window !== 'undefined') return 'browser';
if (typeof global !== 'undefined') return 'node';
if (typeof self !== 'undefined') return 'webworker';
return 'unknown';
};
// Universal module pattern
const createUniversalModule = (moduleFactory) => {
const global = globalThis;
const module = moduleFactory(global);
// Export in different module systems
if (typeof exports === 'object') {
// CommonJS
module.exports = module;
} else if (typeof define === 'function' && define.amd) {
// AMD
define(() => module);
} else {
// Global
global.MyModule = module;
}
return module;
};Creating robust API clients using URL and base64 utilities.
import URL from 'core-js-pure/stable/url';
import URLSearchParams from 'core-js-pure/stable/url-search-params';
import { btoa } from 'core-js-pure/stable/btoa';
import structuredClone from 'core-js-pure/stable/structured-clone';
class APIClient {
constructor(baseURL, options = {}) {
this.baseURL = baseURL;
this.defaultHeaders = options.headers || {};
this.timeout = options.timeout || 5000;
}
buildURL(endpoint, params = {}) {
const url = new URL(endpoint, this.baseURL);
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
if (Array.isArray(value)) {
value.forEach(v => url.searchParams.append(key, v.toString()));
} else {
url.searchParams.set(key, value.toString());
}
}
});
return url.href;
}
createAuthHeader(username, password) {
const credentials = btoa(`${username}:${password}`);
return `Basic ${credentials}`;
}
async request(endpoint, options = {}) {
const url = this.buildURL(endpoint, options.params);
const config = structuredClone({
method: 'GET',
headers: {
'Content-Type': 'application/json',
...this.defaultHeaders,
...options.headers
},
...options
});
delete config.params; // Remove params from fetch options
const response = await fetch(url, config);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response.json();
}
// Convenience methods
get(endpoint, params, options = {}) {
return this.request(endpoint, { ...options, params, method: 'GET' });
}
post(endpoint, data, options = {}) {
return this.request(endpoint, {
...options,
method: 'POST',
body: JSON.stringify(data)
});
}
}
// Usage
const client = new APIClient('https://api.example.com/v1');
// GET with query parameters
const users = await client.get('users', {
page: 2,
limit: 10,
roles: ['admin', 'user'],
active: true
});
// POST with authentication
client.defaultHeaders.Authorization = client.createAuthHeader('user', 'pass');
const newUser = await client.post('users', {
name: 'Alice',
email: 'alice@example.com'
});Building a robust message serialization system for inter-process communication.
import structuredClone from 'core-js-pure/stable/structured-clone';
import { btoa, atob } from 'core-js-pure/stable/atob';
class MessageSerializer {
static serialize(message) {
try {
// Clone to ensure no reference sharing
const cloned = structuredClone(message);
// Add metadata
const envelope = {
version: '1.0',
timestamp: Date.now(),
data: cloned
};
// Serialize and encode
const json = JSON.stringify(envelope);
return btoa(json);
} catch (error) {
throw new Error(`Serialization failed: ${error.message}`);
}
}
static deserialize(encoded) {
try {
const json = atob(encoded);
const envelope = JSON.parse(json);
// Validate envelope
if (!envelope.version || !envelope.data) {
throw new Error('Invalid message format');
}
return {
data: envelope.data,
metadata: {
version: envelope.version,
timestamp: envelope.timestamp,
age: Date.now() - envelope.timestamp
}
};
} catch (error) {
throw new Error(`Deserialization failed: ${error.message}`);
}
}
}
// Message queue with persistence
class MessageQueue {
constructor() {
this.queue = [];
this.processing = false;
}
enqueue(message) {
const serialized = MessageSerializer.serialize(message);
this.queue.push(serialized);
this.scheduleProcessing();
}
scheduleProcessing() {
if (!this.processing) {
this.processing = true;
queueMicrotask(() => {
this.processQueue();
});
}
}
processQueue() {
while (this.queue.length > 0) {
const serialized = this.queue.shift();
const { data, metadata } = MessageSerializer.deserialize(serialized);
console.log(`Processing message (age: ${metadata.age}ms):`, data);
// Process message...
}
this.processing = false;
}
}Using web APIs for progressive enhancement with graceful degradation.
import queueMicrotask from 'core-js-pure/stable/queue-microtask';
import structuredClone from 'core-js-pure/stable/structured-clone';
class ProgressiveEnhancement {
constructor() {
this.features = new Map();
this.initQueue = [];
this.initialized = false;
}
registerFeature(name, implementation, fallback) {
this.features.set(name, { implementation, fallback });
if (this.initialized) {
this.initializeFeature(name);
}
}
initializeFeature(name) {
const feature = this.features.get(name);
if (!feature) return;
queueMicrotask(() => {
try {
feature.implementation();
console.log(`✓ Enhanced feature: ${name}`);
} catch (error) {
console.warn(`✗ Enhancement failed for ${name}:`, error);
if (feature.fallback) {
feature.fallback();
console.log(`↳ Fallback activated for ${name}`);
}
}
});
}
init() {
if (this.initialized) return;
this.initialized = true;
// Initialize all registered features
for (const [name] of this.features) {
this.initializeFeature(name);
}
}
// Feature detection utilities
static hasFeature(feature) {
const features = {
fetch: () => typeof fetch !== 'undefined',
websocket: () => typeof WebSocket !== 'undefined',
serviceworker: () => 'serviceWorker' in navigator,
indexeddb: () => typeof indexedDB !== 'undefined',
geolocation: () => 'geolocation' in navigator
};
return features[feature] ? features[feature]() : false;
}
}
// Usage
const enhancer = new ProgressiveEnhancement();
// Register enhanced features with fallbacks
enhancer.registerFeature('realtime-updates',
() => {
if (!ProgressiveEnhancement.hasFeature('websocket')) {
throw new Error('WebSocket not supported');
}
// WebSocket implementation
console.log('WebSocket real-time updates enabled');
},
() => {
// Polling fallback
console.log('Using polling for updates');
}
);
enhancer.registerFeature('offline-storage',
() => {
if (!ProgressiveEnhancement.hasFeature('indexeddb')) {
throw new Error('IndexedDB not supported');
}
// IndexedDB implementation
console.log('IndexedDB offline storage enabled');
},
() => {
// localStorage fallback
console.log('Using localStorage for offline storage');
}
);
// Initialize all features
enhancer.init();