UNPKG

scriptable-testlab

Version:

A lightweight, efficient tool designed to manage and update scripts for Scriptable.

137 lines (122 loc) 2.54 kB
import {AbsKeychain} from 'scriptable-abstract'; interface KeychainState { items: Map<string, string>; accessGroups: string[]; lastAccess: Date | null; } const DEFAULT_STATE: KeychainState = { items: new Map(), accessGroups: [], lastAccess: null, }; /** * Mock implementation of Scriptable's Keychain global variable * @implements Keychain */ export class MockKeychain extends AbsKeychain<KeychainState> { static get instance(): MockKeychain { return super.instance as MockKeychain; } constructor() { super(DEFAULT_STATE); } /** * @inheritdoc */ set(key: string, value: string): void { this.setState(state => { const items = new Map(state.items); items.set(key, value); return { ...state, items, lastAccess: new Date(), }; }); } /** * @inheritdoc */ get(key: string): string { const value = this.state.items.get(key); if (value === undefined) { throw new Error(`No value found for key: ${key}`); } this.setState({lastAccess: new Date()}); return value; } /** * @inheritdoc */ remove(key: string): void { this.setState(state => { const items = new Map(state.items); items.delete(key); return { ...state, items, lastAccess: new Date(), }; }); } /** * @inheritdoc */ contains(key: string): boolean { return this.state.items.has(key); } /** * @inheritdoc */ get accessGroup(): string | null { return this.state.accessGroups[this.state.accessGroups.length - 1] ?? null; } /** * @inheritdoc */ set accessGroup(group: string | null) { if (group === null) { this.setState(state => ({ ...state, accessGroups: state.accessGroups.slice(0, -1), })); } else { this.setState(state => ({ ...state, accessGroups: [...state.accessGroups, group], })); } } /** * @additional * Get all stored keys */ getKeys(): string[] { return Array.from(this.state.items.keys()); } /** * @additional * Get all access groups */ getAccessGroups(): string[] { return [...this.state.accessGroups]; } /** * @additional * Get last access time */ getLastAccess(): Date | null { return this.state.lastAccess; } /** * @additional * Clear all stored items */ clear(): void { this.setState({ items: new Map(), accessGroups: [], lastAccess: new Date(), }); } }