Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/RokuDeploy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4294,6 +4294,41 @@ describe('RokuDeploy', () => {
}

describe('defaults', () => {
describe('constructor defaults', () => {
Comment thread
Christian-Holbrook marked this conversation as resolved.
it('merges constructor defaults with method options', async () => {
const rd = new RokuDeploy({ host: 'constructor-host', password: 'constructor-password' });
const stub = sinon.stub(rd as any, 'doPostRequest').resolves({});
await rd['sendKeyEvent']({ key: 'home', action: 'keypress' } as any);
expect(stub.getCall(0).args[0].url).to.include('constructor-host');
});

it('method options override constructor defaults', async () => {
const rd = new RokuDeploy({ host: 'constructor-host', password: 'constructor-password' });
const stub = sinon.stub(rd as any, 'doPostRequest').resolves({});
await rd['sendKeyEvent']({ host: 'method-host', key: 'home', action: 'keypress' });
expect(stub.getCall(0).args[0].url).to.include('method-host');
});

it('uses custom logger when provided in constructor', () => {
const customLogger = {
logLevel: 'off' as any,
log: sinon.stub(),
info: sinon.stub(),
warn: sinon.stub(),
debug: sinon.stub(),
error: sinon.stub(),
trace: sinon.stub()
};
const rd = new RokuDeploy({ logger: customLogger as any });
expect(rd['_logger']).to.equal(customLogger);
});

it('sets logLevel on logger when provided in constructor', () => {
const rd = new RokuDeploy({ logLevel: 'debug' as any });
expect(rd['_logger'].logLevel).to.equal('debug');
});
});

describe('generateBaseRequestOptions', () => {
it('uses default timeout', () => {
const result = rokuDeploy['generateBaseRequestOptions']('test', { host: 'localhost', password: 'test' });
Expand Down
106 changes: 86 additions & 20 deletions src/RokuDeploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import * as errors from './Errors';
import * as xml2js from 'xml2js';
import { parse as parseJsonc } from 'jsonc-parser';
import { util } from './util';
import type { FileEntry } from './RokuDeployOptions';
import { logger, type LogLevel } from '@rokucommunity/logger';
import type { FileEntry, RokuDeployOptions } from './RokuDeployOptions';
import { logger } from '@rokucommunity/logger';
import * as dayjs from 'dayjs';
import * as lodash from 'lodash';
import type { DeviceInfo, DeviceInfoRaw } from './DeviceInfo';
Expand All @@ -29,12 +29,57 @@ export class RokuDeploy {
outFile: 'roku-deploy.zip'
};

/**
* Instance-level default options that are merged into every method call
*/
private readonly options: RokuDeployOptions;

/**
* Custom logger instance, if provided
*/
private readonly _logger: typeof logger;

/**
* Create a new RokuDeploy instance with optional default options.
* These defaults will be merged into every method call, so you don't need to
* repeat common options like `host` and `password` on every call.
*
* @example
* ```typescript
* const rd = new RokuDeploy({ host: '192.168.1.100', password: 'secret' });
* await rd.sideload({ rootDir: './dist' }); // host and password come from defaults
* ```
*/
constructor(options?: RokuDeployOptions) {
Comment thread
Christian-Holbrook marked this conversation as resolved.
Outdated
this.options = options ?? {};

// Use custom logger if provided, otherwise use global logger
if (this.options.logger) {
this._logger = this.options.logger;
} else {
this._logger = logger;
}

// Set log level if provided
if (this.options.logLevel) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We decided to drop logLevel as an option. We will unify with other tools that just take logger.

See example from brighterscript

/**
 * A runner class that handles
 */
export class ProgramBuilder {

    public constructor(
        options?: {
            logger?: Logger;
        }
    ) {
        this.logger = option

Comment thread
Christian-Holbrook marked this conversation as resolved.
Outdated
this._logger.logLevel = this.options.logLevel;
}
}

/**
* Get the logger instance for this RokuDeploy instance
*/
private get log() {
Comment thread
Christian-Holbrook marked this conversation as resolved.
Outdated
return this._logger;
}

/**
* Copies all of the referenced files to the staging folder
* @param options
*/
public async stage(options: StageOptions) {
logger.info('Beginning to copy files to staging folder');
options = { ...this.options, ...options };
this.log.info('Beginning to copy files to staging folder');
const cwd = options.cwd ?? process.cwd();

// Set defaults and resolve paths
Expand Down Expand Up @@ -73,7 +118,7 @@ export class RokuDeploy {
});
}, 10);
}));
logger.info('Relevant files copied to:', out);
this.log.info('Relevant files copied to:', out);
return out;
}

Expand All @@ -82,7 +127,8 @@ export class RokuDeploy {
* @param options
*/
public async zip(options: ZipOptions) {
logger.info('Beginning to zip folder');
options = { ...this.options, ...options };
this.log.info('Beginning to zip folder');
const cwd = options.cwd ?? process.cwd();

// Resolve source directory - dir is required
Expand All @@ -108,7 +154,7 @@ export class RokuDeploy {

//create a zip of the folder
await this.makeZip(dir, out);
logger.info('Zip created at:', out);
this.log.info('Zip created at:', out);
}

/**
Expand Down Expand Up @@ -152,6 +198,7 @@ export class RokuDeploy {
* Get all file paths for the specified options
*/
public async getFilePaths(options: GetFilePathsOptions): Promise<StandardizedFileEntry[]> {
options = { ...this.options, ...options } as GetFilePathsOptions;
let rootDir = options.rootDir;
const files = options.files;

Expand Down Expand Up @@ -214,6 +261,7 @@ export class RokuDeploy {
}

public async keyPress(options: KeyPressOptions) {
options = { ...this.options, ...options } as KeyPressOptions;
return this.sendKeyEvent({
...options,
key: options.key,
Expand All @@ -222,20 +270,23 @@ export class RokuDeploy {
}

public async keyUp(options: KeyUpOptions) {
options = { ...this.options, ...options } as KeyUpOptions;
return this.sendKeyEvent({
...options,
action: 'keyup'
});
}

public async keyDown(options: KeyDownOptions) {
options = { ...this.options, ...options } as KeyDownOptions;
return this.sendKeyEvent({
...options,
action: 'keydown'
});
}

public async sendText(options: SendTextOptions) {
options = { ...this.options, ...options } as SendTextOptions;
this.checkRequiredOptions(options, ['host', 'text']);
const chars = options.text.split('');
for (const char of chars) {
Expand All @@ -252,7 +303,8 @@ export class RokuDeploy {
* This makes the roku return to the home screen
*/
private async sendKeyEvent(options: SendKeyEventOptions) {
logger.info('Sending key event:', options.key);
options = { ...this.options, ...options } as SendKeyEventOptions;
this.log.info('Sending key event:', options.key);
this.checkRequiredOptions(options, ['host', 'key']);
// Set defaults
const ecpPort = options.ecpPort ?? RokuDeploy.defaults.ecpPort;
Expand All @@ -265,6 +317,7 @@ export class RokuDeploy {
}

public async closeChannel(options: CloseChannelOptions) {
options = { ...this.options, ...options } as CloseChannelOptions;
// TODO: After 13.0 releases, add check for ECP close-app support, and use that twice to kill instant resume if available
await this.sendKeyEvent({
...options,
Expand All @@ -279,7 +332,8 @@ export class RokuDeploy {
* @param options
*/
public async sideload(options: SideloadOptions): Promise<{ message: string; results: any }> {
logger.info('Beginning to sideload package');
options = { ...this.options, ...options } as SideloadOptions;
this.log.info('Beginning to sideload package');
this.checkRequiredOptions(options, ['host', 'password']);

const cwd = options.cwd ?? process.cwd();
Expand Down Expand Up @@ -397,7 +451,7 @@ export class RokuDeploy {
if (response.body.indexOf('Identical to previous version -- not replacing.') > -1) {
return { message: 'Identical to previous version -- not replacing', results: response };
}
logger.info('Successful sideload');
this.log.info('Successful sideload');
return { message: 'Successful sideload', results: response };
} finally {
//delete the zip file if we generated it from rootDir
Expand All @@ -408,7 +462,7 @@ export class RokuDeploy {
try {
readStream?.close();
} catch (e) {
logger.warn('Error closing read stream', e);
this.log.warn('Error closing read stream', e);
}
}
}
Expand Down Expand Up @@ -439,6 +493,7 @@ export class RokuDeploy {
* @param options
*/
public async convertToSquashfs(options: ConvertToSquashfsOptions) {
options = { ...this.options, ...options } as ConvertToSquashfsOptions;
this.checkRequiredOptions(options, ['host', 'password']);
let requestOptions = this.generateBaseRequestOptions('plugin_install', options, {
archive: '',
Expand All @@ -459,7 +514,7 @@ export class RokuDeploy {
return results;
}
} catch (e) {
logger.warn('Error converting to squashfs:', error);
this.log.warn('Error converting to squashfs:', error);
throw error;
}
} else {
Expand All @@ -476,6 +531,7 @@ export class RokuDeploy {
* @param options
*/
public async rekeyDevice(options: RekeyDeviceOptions) {
options = { ...this.options, ...options } as RekeyDeviceOptions;
this.checkRequiredOptions(options, ['host', 'password', 'pkg', 'signingPassword']);
const cwd = path.resolve(process.cwd(), options.cwd ?? '.');

Expand Down Expand Up @@ -523,7 +579,8 @@ export class RokuDeploy {
* @param options
*/
public async createSignedPackage(options: CreateSignedPackageOptions): Promise<string> {
logger.info('Creating signed package');
options = { ...this.options, ...options } as CreateSignedPackageOptions;
this.log.info('Creating signed package');
this.checkRequiredOptions(options, ['host', 'password', 'signingPassword']);
const cwd = options.cwd ?? process.cwd();

Expand Down Expand Up @@ -593,7 +650,7 @@ export class RokuDeploy {
const url = pkgSearchMatches[1];
let requestOptions2 = this.generateBaseRequestOptions(url, options);
await this.downloadFile(requestOptions2, out);
logger.info('Signed package created at:', out);
this.log.info('Signed package created at:', out);
return out;
}

Expand Down Expand Up @@ -640,7 +697,7 @@ export class RokuDeploy {
* @param params
*/
private async doPostRequest(params: requestType.OptionsWithUrl, verify = true) {
logger.info('handling POST request to', params.url);
this.log.info('handling POST request to', params.url);
let results: { response: any; body: any } = await new Promise((resolve, reject) => {

this.setUserAgentIfMissing(params);
Expand All @@ -663,7 +720,7 @@ export class RokuDeploy {
* @param params
*/
private async doGetRequest(params: requestType.OptionsWithUrl) {
logger.info('handling GET request to', params.url);
this.log.info('handling GET request to', params.url);
let results: { response: any; body: any } = await new Promise((resolve, reject) => {

this.setUserAgentIfMissing(params);
Expand Down Expand Up @@ -814,7 +871,8 @@ export class RokuDeploy {
* @param options
*/
public async deleteDevChannel(options?: DeleteDevChannelOptions) {
logger.info('Deleting dev channel...');
options = { ...this.options, ...options } as DeleteDevChannelOptions;
this.log.info('Deleting dev channel...');
this.checkRequiredOptions(options, ['host', 'password']);

let deleteOptions = this.generateBaseRequestOptions('plugin_install', options);
Expand All @@ -829,6 +887,7 @@ export class RokuDeploy {
* Delete the component library with the specified filename from the device
*/
public async deleteComponentLibrary(options?: { host: string; password: string; fileName: string; username?: string }) {
options = { ...this.options, ...options } as { host: string; password: string; fileName: string; username?: string };
this.checkRequiredOptions(options, ['host', 'password', 'fileName']);

let deleteOptions = this.generateBaseRequestOptions('plugin_install', options);
Expand All @@ -847,6 +906,7 @@ export class RokuDeploy {
* Delete all component libraries from the device
*/
public async deleteAllComponentLibraries(options: { host: string; password: string; username?: string }) {
options = { ...this.options, ...options } as { host: string; password: string; username?: string };
const packages = await this.getInstalledPackages(options);
for (const pkg of packages) {
if (pkg.appType === 'dcl') {
Expand All @@ -862,6 +922,7 @@ export class RokuDeploy {
* Fetch the full list of installed packages from the device. Useful for finding the file names of installed component libraries or the dev channel.
*/
private async getInstalledPackages(options: { host: string; password: string; username?: string }): Promise<RokuPackage[]> {
options = { ...this.options, ...options } as { host: string; password: string; username?: string };
this.checkRequiredOptions(options, ['host', 'password']);
let deleteOptions = this.generateBaseRequestOptions('plugin_install', options);
deleteOptions.qs ??= {};
Expand All @@ -876,6 +937,7 @@ export class RokuDeploy {
* Gets a screenshot from the device. A side-loaded channel must be running or an error will be thrown.
*/
public async captureScreenshot(options: CaptureScreenshotOptions) {
options = { ...this.options, ...options } as CaptureScreenshotOptions;
this.checkRequiredOptions(options, ['host', 'password']);
const cwd = options.cwd ?? process.cwd();
const screenshotDir = options.screenshotDir
Expand Down Expand Up @@ -985,6 +1047,7 @@ export class RokuDeploy {
public async getDeviceInfo(options?: GetDeviceInfoOptions & { enhance: true }): Promise<DeviceInfo>;
public async getDeviceInfo(options?: GetDeviceInfoOptions): Promise<DeviceInfoRaw>;
public async getDeviceInfo(options: GetDeviceInfoOptions) {
options = { ...this.options, ...options } as GetDeviceInfoOptions;
this.checkRequiredOptions(options, ['host']);

// Set defaults
Expand Down Expand Up @@ -1030,10 +1093,10 @@ export class RokuDeploy {
}
deviceInfo = result;
}
logger.debug('Device info:', deviceInfo);
this.log.debug('Device info:', deviceInfo);
return deviceInfo;
} catch (e) {
logger.warn('Error getting device info:', e);
this.log.warn('Error getting device info:', e);
throw new errors.UnparsableDeviceResponseError('Could not retrieve device info', response);
}
}
Expand All @@ -1050,6 +1113,7 @@ export class RokuDeploy {
* - 'permissive': Full access for internal networks
*/
public async getEcpNetworkAccessMode(options: GetDeviceInfoOptions): Promise<EcpNetworkAccessMode> {
options = { ...this.options, ...options } as GetDeviceInfoOptions;
try {
const deviceInfo = await this.getDeviceInfo(options);
return deviceInfo['ecp-setting-mode'];
Expand Down Expand Up @@ -1087,9 +1151,10 @@ export class RokuDeploy {
* @returns
*/
public async getDevId(options?: GetDevIdOptions) {
options = { ...this.options, ...options } as GetDevIdOptions;
this.checkRequiredOptions(options, ['host']);
const deviceInfo = await this.getDeviceInfo(options);
logger.debug('Found dev id:', deviceInfo['keyed-developer-id']);
this.log.debug('Found dev id:', deviceInfo['keyed-developer-id']);
return deviceInfo['keyed-developer-id'];
}

Expand Down Expand Up @@ -1120,6 +1185,7 @@ export class RokuDeploy {
}

public async rebootDevice(options: RebootDeviceOptions) {
options = { ...this.options, ...options } as RebootDeviceOptions;
this.checkRequiredOptions(options, ['host', 'password']);

// Get device info to check software version
Expand All @@ -1141,6 +1207,7 @@ export class RokuDeploy {
}

public async checkForUpdate(options: CheckForUpdateOptions) {
options = { ...this.options, ...options } as CheckForUpdateOptions;
this.checkRequiredOptions(options, ['host', 'password']);

// Get device info to check software version
Expand Down Expand Up @@ -1335,7 +1402,6 @@ export interface BaseRequestOptions {
password: string;
packagePort?: number;
timeout?: number;
logLevel?: LogLevel;
}

export interface BaseEcpOptions {
Expand Down
Loading
Loading