diff --git a/bootstrap.ts b/bootstrap.ts index 314c8eee..e628aea6 100644 --- a/bootstrap.ts +++ b/bootstrap.ts @@ -22,3 +22,24 @@ $injector.require("propertiesParser", "./common/properties-parser"); $injector.requireCommand(["help", "/?"], "./common/commands/help"); $injector.requireCommand("feature-usage-tracking", "./common/services/analytics-service"); + +$injector.require("iOSCore", "./common/mobile/ios/ios-core"); +$injector.require("coreFoundation", "./common/mobile/ios/ios-core"); +$injector.require("mobileDevice", "./common/mobile/ios/ios-core"); +$injector.require("plistService", "./common/mobile/ios/ios-core"); + +$injector.require("installationProxyClient", "./common/mobile/ios/ios-proxy-services"); +$injector.require("notificationProxyClient", "./common/mobile/ios/ios-proxy-services"); +$injector.require("houseArrestClient", "./common/mobile/ios/ios-proxy-services"); + +$injector.require("signal", "./events/signal"); +$injector.require("deviceFound", "./common/mobile/mobile-core/device-discovery"); +$injector.require("deviceLost", "./common/mobile/mobile-core/device-discovery"); + +$injector.require("deviceDiscovery", "./common/mobile/mobile-core/device-discovery"); +$injector.require("iOSDeviceDiscovery", "./common/mobile/mobile-core/device-discovery"); +$injector.require("androidDeviceDiscovery", "./common/mobile/mobile-core/device-discovery"); +$injector.require("iOSDevice", "./common/mobile/ios/ios-device"); +$injector.require("androidDevice", "./common/mobile/android/android-device"); + +$injector.require("devicesServices", "./common/mobile/mobile-core/devices-services"); diff --git a/declarations.d.ts b/declarations.d.ts index 2c276ba2..f394587f 100644 --- a/declarations.d.ts +++ b/declarations.d.ts @@ -169,3 +169,7 @@ interface IAnalyticsSettingsService { canRequestConsent(): IFuture; getUserId(): IFuture; } + +interface IHostCapabilities { + debugToolsSupported: boolean; +} diff --git a/definitions/bufferpack.d.ts b/definitions/bufferpack.d.ts new file mode 100644 index 00000000..6e895068 --- /dev/null +++ b/definitions/bufferpack.d.ts @@ -0,0 +1,62 @@ +declare module "bufferpack" { + interface NodeBuffer { + /** Shorthand for `ref.address`. */ + address(): number; + /** Shorthand for `ref.deref`. */ + deref(): any; + /** Shorthand for `ref.isNull`. */ + isNull(): boolean; + /** Shorthand for `ref.readCString`. */ + readCString(offset?: number): string; + /** Shorthand for `ref.readInt64BE`. */ + readInt64BE(offset?: number): string; + /** Shorthand for `ref.readInt64LE`. */ + readInt64LE(offset?: number): string; + /** Shorthand for `ref.readObject`. */ + readObject(offset?: number): string; + /** Shorthand for `ref.readPointer`. */ + readPointer(offset?: number): string; + /** Shorthand for `ref.readUInt64BE`. */ + readUInt64BE(offset?: number): string; + /** Shorthand for `ref.readUInt64LE`. */ + readUInt64LE(offset?: number): string; + /** Shorthand for `ref.ref`. */ + ref(): NodeBuffer; + /** Shorthand for `ref.reinterpret`. */ + reinterpret(size: number, offset?: number): NodeBuffer; + /** Shorthand for `ref.reinterpretUntilZeros`. */ + reinterpretUntilZeros(size: number, offset?: number): NodeBuffer; + /** Shorthand for `ref.writeCString`. */ + writeCString(offset: number, string: string, encoding?: string): void; + /** Shorthand for `ref.writeInt64BE`. */ + writeInt64BE(offset: number, input: number): any; + /** Shorthand for `ref.writeInt64BE`. */ + writeInt64BE(offset: number, input: string): any; + /** Shorthand for `ref.writeInt64LE`. */ + writeInt64LE(offset: number, input: number): any; + /** Shorthand for `ref.writeInt64LE`. */ + writeInt64LE(offset: number, input: string): any; + /** Shorthand for `ref.writeObject`. */ + writeObject(offset: number, object: Object): void; + /** Shorthand for `ref.writePointer`. */ + writePointer(offset: number, pointer: NodeBuffer): void; + /** Shorthand for `ref.writeUInt64BE`. */ + writeUInt64BE(offset: number, input: number): any; + /** Shorthand for `ref.writeUInt64BE`. */ + writeUInt64BE(offset: number, input: string): any; + /** Shorthand for `ref.writeUInt64LE`. */ + writeUInt64LE(offset: number, input: number): any; + /** Shorthand for `ref.writeUInt64LE`. */ + writeUInt64LE(offset: number, input: string): any; + + /** + * Generate string for inspecting. + * String includes the hex-encoded memory address of the Buffer instance. + * @override + */ + inspect(): string; + } + + export function pack(endian: string, lengths: number[]): string; + export function unpack(endian: string, data: NodeBuffer): number[]; +} \ No newline at end of file diff --git a/definitions/byline.d.ts b/definitions/byline.d.ts new file mode 100644 index 00000000..44559322 --- /dev/null +++ b/definitions/byline.d.ts @@ -0,0 +1,4 @@ +declare module "byline" { + function lineStream(stream: any): any; + export = lineStream; +} \ No newline at end of file diff --git a/definitions/config.d.ts b/definitions/config.d.ts index 7090d824..5baef752 100644 --- a/definitions/config.d.ts +++ b/definitions/config.d.ts @@ -5,8 +5,10 @@ declare module Config { ANALYTICS_API_KEY: string; ANALYTICS_INSTALLATION_ID_SETTING_NAME: string; TRACK_FEATURE_USAGE_SETTING_NAME: string; + START_PACKAGE_ACTIVITY_NAME: string; version: string; helpTextPath: string; + adbFilePath: string; } interface IConfig { diff --git a/definitions/mobile.d.ts b/definitions/mobile.d.ts new file mode 100644 index 00000000..ff7bcf5d --- /dev/null +++ b/definitions/mobile.d.ts @@ -0,0 +1,152 @@ +/// + +declare module Mobile { + + interface ISyncOptions { + skipRefresh?: boolean; + } + + interface IDevice { + getIdentifier(): string; + getInstalledApplications(): IFuture; + getDisplayName(): string; + getModel(): string; + getVersion(): string; + getVendor(): string; + getPlatform(): string; + deploy(packageFile: string, packageName: string): IFuture; + sync(localToDevicePaths: ILocalToDevicePathData[], appIdentifier: IAppIdentifier, projectType: number): IFuture; + sync(localToDevicePaths: ILocalToDevicePathData[], appIdentifier: IAppIdentifier, projectType: number, options: ISyncOptions): IFuture; + openDeviceLogStream(): void; + } + + interface IAppIdentifier { + appIdentifier: string; + deviceProjectPath: string; + liveSyncFormat: string; + isLiveSyncSupported(device: any): IFuture; + getliveSyncNotSupportedError(device: any): string; + } + + interface IIOSDevice extends IDevice { + startService(serviceName: string): number; + } + + interface IDeviceDiscovery { + deviceFound: ISignal; + deviceLost: ISignal; + startLookingForDevices(): IFuture; + } + + interface IDevicesServicesInitializationOptions { + skipInferPlatform?: boolean; + } + + interface IDevicesServices { + hasDevices: boolean; + deviceCount: number; + execute(action: (device: Mobile.IDevice) => IFuture, canExecute?: (dev: Mobile.IDevice) => boolean, options?: {allowNoDevices?: boolean}): IFuture; + initialize(platform: string, deviceOption?: string, options?: IDevicesServicesInitializationOptions): IFuture; + platform: string; + } + + interface IiOSCore { + getCoreFoundationLibrary(): any; + getMobileDeviceLibrary(): any; + } + + interface ICoreFoundation { + runLoopRun(): void; + runLoopGetCurrent(): any; + stringCreateWithCString(alloc: NodeBuffer, str: string, encoding: number): NodeBuffer; + dictionaryGetValue(theDict: NodeBuffer, value: NodeBuffer): NodeBuffer; + numberGetValue(number: NodeBuffer, theType: number, valuePtr: NodeBuffer): boolean; + kCFRunLoopCommonModes(): NodeBuffer; + kCFRunLoopDefaultMode(): NodeBuffer; + kCFTypeDictionaryKeyCallBacks(): NodeBuffer; + kCFTypeDictionaryValueCallBacks(): NodeBuffer; + runLoopTimerCreate(allocator: NodeBuffer, fireDate: number, interval: number, flags: number, order: number, callout: NodeBuffer, context: any): NodeBuffer; + absoluteTimeGetCurrent(): number; + runLoopAddTimer(r1: NodeBuffer, timer: NodeBuffer, mode: NodeBuffer): void; + runLoopRemoveTimer(r1: NodeBuffer, timer: NodeBuffer, mode: NodeBuffer): void; + runLoopStop(r1: any): void; + convertCFStringToCString(cfstr: NodeBuffer): string; + dictionaryCreate(allocator: NodeBuffer, keys: NodeBuffer, values: NodeBuffer, count: number, dictionaryKeyCallbacks: NodeBuffer, dictionaryValueCallbacks: NodeBuffer): NodeBuffer; + getTypeID(type: NodeBuffer): number; + stringGetCString(theString: NodeBuffer, buffer: NodeBuffer, bufferSize: number, encoding: number): boolean; + stringGetLength(theString: NodeBuffer): number; + dictionaryGetCount(theDict: NodeBuffer): number; + createCFString(str: string): NodeBuffer; + dictToPlistEncoding(dict: {[key: string]: {}}, format: number): NodeBuffer; + dictFromPlistEncoding(str: NodeBuffer): NodeBuffer; + dictionaryGetTypeID(): number; + stringGetTypeID(): number; + dataGetTypeID(): number; + numberGetTypeID(): number; + booleanGetTypeID(): number; + arrayGetTypeID(): number; + dateGetTypeID(): number; + setGetTypeID(): number; + dictionaryGetKeysAndValues(dictionary: NodeBuffer, keys: NodeBuffer, values: NodeBuffer): void; + } + + interface IMobileDevice { + deviceNotificationSubscribe(notificationCallback: NodeBuffer, p1: number, p2: number, context: any, callbackSignature: NodeBuffer): number; + deviceCopyDeviceIdentifier(devicePointer: NodeBuffer): NodeBuffer; + deviceCopyValue(devicePointer: NodeBuffer, domain: NodeBuffer, name: NodeBuffer): NodeBuffer; + deviceConnect(devicePointer: NodeBuffer): number; + deviceIsPaired(devicePointer: NodeBuffer): number; + devicePair(devicePointer: NodeBuffer): number; + deviceValidatePairing(devicePointer: NodeBuffer): number; + deviceStartSession(devicePointer: NodeBuffer): number; + deviceStopSession(devicePointer: NodeBuffer): number; + deviceDisconnect(devicePointer: NodeBuffer): number; + deviceStartService(devicePointer: NodeBuffer, serviceName: NodeBuffer, socketNumber: NodeBuffer): number; + deviceTransferApplication(service: number, packageFile: NodeBuffer, options: NodeBuffer, installationCallback: NodeBuffer): number; + deviceInstallApplication(service: number, packageFile: NodeBuffer, options: NodeBuffer, installationCallback: NodeBuffer): number; + afcConnectionOpen(service: number, timeout: number, afcConnection: NodeBuffer): number; + afcConnectionClose(afcConnection: NodeBuffer): number; + afcDirectoryCreate(afcConnection: NodeBuffer, path: string): number; + afcFileRefOpen(afcConnection: NodeBuffer, path: string, mode: number, afcFileRef: NodeBuffer): number; + afcFileRefClose(afcConnection: NodeBuffer, afcFileRef: number): number; + afcFileRefWrite(afcConnection: NodeBuffer, afcFileRef: number, buffer: NodeBuffer, byteLength: number): number; + afcFileRefRead(afcConnection: NodeBuffer, afcFileRef: number, buffer: NodeBuffer, byteLength: number): number; + afcRemovePath(afcConnection: NodeBuffer, path: string): number; + afcDirectoryOpen(afcConnection: NodeBuffer, path: string, afcDirectory: NodeBuffer): number; + afcDirectoryRead(afcConnection: NodeBuffer, afcdirectory: NodeBuffer, name: NodeBuffer): number; + afcDirectoryClose(afcConnection: NodeBuffer, afcdirectory: NodeBuffer): number; + isDataReceivingCompleted(reply: string): boolean; + } + + interface IHouseArrestClient { + getAfcClientForAppDocuments(applicationIdentifier: string): Mobile.IAfcClient; + getAfcClientForAppContainer(applicationIdentifier: string): Mobile.IAfcClient; + closeSocket(): void; + } + + interface IAfcClient { + transferCollection(localToDevicePaths: Mobile.ILocalToDevicePathData[]): IFuture; + deleteFile(devicePath: string): void; + } + + interface ILocalToDevicePathData { + getLocalPath(): string; + getDevicePath(): string; + getRelativeToProjectBasePath(): string; + } + + interface IiOSDeviceSocket { + receiveMessage(): IFuture; + readSystemLog(action: (data: NodeBuffer) => void): void; + sendMessage(message: {[key: string]: {}}, format?: number): void; + close(): void; + } + + interface IPlatformCapabilities { + wirelessDeploy: boolean; + cableDeploy: boolean; + companion: boolean; + publishTelerikAppManager: boolean; + hostPlatformsForDeploy: string[]; + } +} diff --git a/definitions/node-ffi.d.ts b/definitions/node-ffi.d.ts new file mode 100644 index 00000000..9f46adb5 --- /dev/null +++ b/definitions/node-ffi.d.ts @@ -0,0 +1,596 @@ +// Type definitions for node-ffi, ref, ref-array, ref-struct and ref-union +// Project: https://github.com/rbranson/node-ffi +// Definitions by: Paul Loyd +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "ffi" { + import ref = require('ref'); + import StructType = require('ref-struct'); + + /** Provides a friendly API on-top of `DynamicLibrary` and `ForeignFunction`. */ + export var Library: { + /** The extension to use on libraries. */ + EXT: string; + + /** + * @param libFile name of library + * @param funcs hash of [retType, [...argType], opts?: {abi?, async?, varargs?}] + * @param lib hash that will be extended + */ + new (libFile: string, funcs?: {[key: string]: any[]}, lib?: Object): any; + + /** + * @param libFile name of library + * @param funcs hash of [retType, [...argType], opts?: {abi?, async?, varargs?}] + * @param lib hash that will be extended + */ + (libFile: string, funcs?: {[key: string]: any[]}, lib?: Object): any; + }; + + /** Get value of errno. */ + export function errno(): number; + + export interface Function extends ref.Type { + /** The type of return value. */ + retType: ref.Type; + /** The type of arguments. */ + argTypes: ref.Type[]; + /** Is set for node-ffi functions. */ + ffi_type: NodeBuffer; + abi: number; + + /** Get a `Callback` pointer of this function type. */ + toPointer(fn: (...args: any[]) => any): NodeBuffer; + /** Get a `ForeignFunction` of this function type. */ + toFunction(buf: NodeBuffer): ForeignFunction; + } + + /** Creates and returns a type for a C function pointer. */ + export var Function: { + new (retType: ref.Type, argTypes: any[], abi?: number): Function; + new (retType: string, argTypes: any[], abi?: number): Function; + (retType: ref.Type, argTypes: any[], abi?: number): Function; + (retType: string, argTypes: any[], abi?: number): Function; + }; + + export interface ForeignFunction { + (...args: any[]): any; + async(...args: any[]): void; + } + + /** + * Represents a foreign function in another library. Manages all of the aspects + * of function execution, including marshalling the data parameters for the + * function into native types and also unmarshalling the return from function + * execution. + */ + export var ForeignFunction: { + new (ptr: NodeBuffer, retType: ref.Type, argTypes: any[], abi?: number): ForeignFunction; + new (ptr: NodeBuffer, retType: string, argTypes: any[], abi?: number): ForeignFunction; + (ptr: NodeBuffer, retType: ref.Type, argTypes: any[], abi?: number): ForeignFunction; + (ptr: NodeBuffer, retType: string, argTypes: any[], abi?: number): ForeignFunction; + } + + export interface VariadicForeignFunction { + /** + * What gets returned is another function that needs to be invoked with the rest + * of the variadic types that are being invoked from the function. + */ + (...args: any[]): ForeignFunction; + + /** + * Return type as a property of the function generator to + * allow for monkey patching the return value in the very rare case where the + * return type is variadic as well + */ + returnType: any; + } + + /** + * For when you want to call to a C function with variable amount of arguments. + * i.e. `printf`. + * + * This function takes care of caching and reusing `ForeignFunction` instances that + * contain the same ffi_type argument signature. + */ + export var VariadicForeignFunction: { + new (ptr: NodeBuffer, ret: ref.Type, fixedArgs: any[], abi?: number): VariadicForeignFunction; + new (ptr: NodeBuffer, ret: string, fixedArgs: any[], abi?: number): VariadicForeignFunction; + (ptr: NodeBuffer, ret: ref.Type, fixedArgs: any[], abi?: number): VariadicForeignFunction; + (ptr: NodeBuffer, ret: string, fixedArgs: any[], abi?: number): VariadicForeignFunction; + }; + + export interface DynamicLibrary { + /** Close library, returns the result of the `dlclose` system function. */ + close(): number; + /** Get a symbol from this library. */ + get(symbol: string): NodeBuffer; + /** Get the result of the `dlerror` system function. */ + error(): string; + } + + /** + * This class loads and fetches function pointers for dynamic libraries + * (.so, .dylib, etc). After the libray's function pointer is acquired, then you + * call `get(symbol)` to retreive a pointer to an exported symbol. You need to + * call `get___` on the pointer to dereference it into its actual value, or + * turn the pointer into a callable function with `ForeignFunction`. + */ + export var DynamicLibrary: { + FLAGS: { + RTLD_LAZY: number; + RTLD_NOW: number; + RTLD_LOCAL: number; + RTLD_GLOBAL: number; + RTLD_NOLOAD: number; + RTLD_NODELETE: number; + RTLD_NEXT: NodeBuffer; + RTLD_DEFAUL: NodeBuffer; + } + + new (path?: string, mode?: number): DynamicLibrary; + (path?: string, mode?: number): DynamicLibrary; + }; + + /** + * Turns a JavaScript function into a C function pointer. + * The function pointer may be used in other C functions that + * accept C callback functions. + */ + export var Callback: { + new (retType: any, argTypes: any[], abi: number, fn: Function): NodeBuffer; + new (retType: any, argTypes: any[], fn: Function): NodeBuffer; + (retType: any, argTypes: any[], abi: number, fn: Function): NodeBuffer; + (retType: any, argTypes: any[], fn: Function): NodeBuffer; + } + + export var ffiType: { + /** Get a `ffi_type *` Buffer appropriate for the given type. */ + (type: ref.Type): NodeBuffer + /** Get a `ffi_type *` Buffer appropriate for the given type. */ + (type: string): NodeBuffer + FFI_TYPE: StructType; + } + + export var CIF: Function; + export var CIF_var: Function; + export var HAS_OBJC: boolean; + export var FFI_TYPES: {[key: string]: NodeBuffer}; + export var FFI_OK: number; + export var FFI_BAD_TYPEDEF: number; + export var FFI_BAD_ABI: number; + export var FFI_DEFAULT_ABI: number; + export var FFI_FIRST_ABI: number; + export var FFI_LAST_ABI: number; + export var FFI_SYSV: number; + export var FFI_UNIX64: number; + export var RTLD_LAZY: number; + export var RTLD_NOW: number; + export var RTLD_LOCAL: number; + export var RTLD_GLOBAL: number; + export var RTLD_NOLOAD: number; + export var RTLD_NODELETE: number; + export var RTLD_NEXT: NodeBuffer; + export var RTLD_DEFAULT: NodeBuffer; + export var LIB_EXT: string; + export var FFI_TYPE: StructType; + + /** Default types. */ + export var types: { + void: ref.Type; int64: ref.Type; ushort: ref.Type; + int: ref.Type; uint64: ref.Type; float: ref.Type; + uint: ref.Type; long: ref.Type; double: ref.Type; + int8: ref.Type; ulong: ref.Type; Object: ref.Type; + uint8: ref.Type; longlong: ref.Type; CString: ref.Type; + int16: ref.Type; ulonglong: ref.Type; bool: ref.Type; + uint16: ref.Type; char: ref.Type; byte: ref.Type; + int32: ref.Type; uchar: ref.Type; size_t: ref.Type; + uint32: ref.Type; short: ref.Type; + }; +} + +declare module "ref" { + export interface Type { + /** The size in bytes required to hold this datatype. */ + size: number; + /** The current level of indirection of the buffer. */ + indirection: number; + /** To invoke when `ref.get` is invoked on a buffer of this type. */ + get(buffer: NodeBuffer, offset: number): any; + /** To invoke when `ref.set` is invoked on a buffer of this type. */ + set(buffer: NodeBuffer, offset: number, value: any): void; + /** The name to use during debugging for this datatype. */ + name?: string; + /** The alignment of this datatype when placed inside a struct. */ + alignment?: number; + } + + /** A Buffer that references the C NULL pointer. */ + export var NULL: NodeBuffer; + /** A pointer-sized buffer pointing to NULL. */ + export var NULL_POINTER: NodeBuffer; + /** Get the memory address of buffer. */ + export function address(buffer: NodeBuffer): number; + /** Allocate the memory with the given value written to it. */ + export function alloc(type: Type, value?: any): NodeBuffer; + /** Allocate the memory with the given value written to it. */ + export function alloc(type: string, value?: any): NodeBuffer; + + /** + * Allocate the memory with the given string written to it with the given + * encoding (defaults to utf8). The buffer is 1 byte longer than the + * string itself, and is NULL terminated. + */ + export function allocCString(string: string, encoding?: string): NodeBuffer; + + /** Coerce a type.*/ + export function coerceType(type: Type): Type; + /** Coerce a type. String are looked up from the ref.types object. */ + export function coerceType(type: string): Type; + + /** + * Get value after dereferencing buffer. + * That is, first it checks the indirection count of buffer's type, and + * if it's greater than 1 then it merely returns another Buffer, but with + * one level less indirection. + */ + export function deref(buffer: NodeBuffer): any; + + /** Create clone of the type, with decremented indirection level by 1. */ + export function derefType(type: Type): Type; + /** Create clone of the type, with decremented indirection level by 1. */ + export function derefType(type: string): Type; + /** Represents the native endianness of the processor ("LE" or "BE"). */ + export var endianness: string; + /** Check the indirection level and return a dereferenced when necessary. */ + export function get(buffer: NodeBuffer, offset?: number, type?: Type): any; + /** Check the indirection level and return a dereferenced when necessary. */ + export function get(buffer: NodeBuffer, offset?: number, type?: string): any; + /** Get type of the buffer. Create a default type when none exists. */ + export function getType(buffer: NodeBuffer): Type; + /** Check the NULL. */ + export function isNull(buffer: NodeBuffer): boolean; + /** Read C string until the first NULL. */ + export function readCString(buffer: NodeBuffer, offset?: number): string; + + /** + * Read a big-endian signed 64-bit int. + * If there is losing precision, then return a string, otherwise a number. + * @return {number|string} + */ + export function readInt64BE(buffer: NodeBuffer, offset?: number): any; + + /** + * Read a little-endian signed 64-bit int. + * If there is losing precision, then return a string, otherwise a number. + * @return {number|string} + */ + export function readInt64LE(buffer: NodeBuffer, offset?: number): any; + + /** Read a JS Object that has previously been written. */ + export function readObject(buffer: NodeBuffer, offset?: number): Object; + /** Read data from the pointer. */ + export function readPointer(buffer: NodeBuffer, offset?: number, + length?: number): NodeBuffer; + /** + * Read a big-endian unsigned 64-bit int. + * If there is losing precision, then return a string, otherwise a number. + * @return {number|string} + */ + export function readUInt64BE(buffer: NodeBuffer, offset?: number): any; + + /** + * Read a little-endian unsigned 64-bit int. + * If there is losing precision, then return a string, otherwise a number. + * @return {number|string} + */ + export function readUInt64LE(buffer: NodeBuffer, offset?: number): any; + + /** Create pointer to buffer. */ + export function ref(buffer: NodeBuffer): NodeBuffer; + /** Create clone of the type, with incremented indirection level by 1. */ + export function refType(type: Type): Type; + /** Create clone of the type, with incremented indirection level by 1. */ + export function refType(type: string): Type; + + /** + * Create buffer with the specified size, with the same address as source. + * This function "attaches" source to the returned buffer to prevent it from + * being garbage collected. + */ + export function reinterpret(buffer: NodeBuffer, size: number, + offset?: number): NodeBuffer; + /** + * Scan past the boundary of the buffer's length until it finds size number + * of aligned NULL bytes. + */ + export function reinterpretUntilZeros(buffer: NodeBuffer, size: number, + offset?: number): NodeBuffer; + + /** Write pointer if the indirection is 1, otherwise write value. */ + export function set(buffer: NodeBuffer, offset: number, value: any, type?: Type): void; + /** Write pointer if the indirection is 1, otherwise write value. */ + export function set(buffer: NodeBuffer, offset: number, value: any, type?: string): void; + /** Write the string as a NULL terminated. Default encoding is utf8. */ + export function writeCString(buffer: NodeBuffer, offset: number, + string: string, encoding?: string): void; + /** Write a big-endian signed 64-bit int. */ + export function writeInt64BE(buffer: NodeBuffer, offset: number, input: number): void; + /** Write a big-endian signed 64-bit int. */ + export function writeInt64BE(buffer: NodeBuffer, offset: number, input: string): void; + /** Write a little-endian signed 64-bit int. */ + export function writeInt64LE(buffer: NodeBuffer, offset: number, input: number): void; + /** Write a little-endian signed 64-bit int. */ + export function writeInt64LE(buffer: NodeBuffer, offset: number, input: string): void; + + /** + * Write the JS Object. This function "attaches" object to buffer to prevent + * it from being garbage collected. + */ + export function writeObject(buffer: NodeBuffer, offset: number, object: Object): void; + + /** + * Write the memory address of pointer to buffer at the specified offset. This + * function "attaches" object to buffer to prevent it from being garbage collected. + */ + export function writePointer(buffer: NodeBuffer, offset: number, + pointer: NodeBuffer): void; + + /** Write a little-endian unsigned 64-bit int. */ + export function writeUInt64BE(buffer: NodeBuffer, offset: number, input: number): void; + /** Write a little-endian unsigned 64-bit int. */ + export function writeUInt64BE(buffer: NodeBuffer, offset: number, input: string): void; + + /** + * Attach object to buffer such. + * It prevents object from being garbage collected until buffer does. + */ + export function _attach(buffer: NodeBuffer, object: Object): void; + + /** Same as ref.reinterpret, except that this version does not attach buffer. */ + export function _reinterpret(buffer: NodeBuffer, size: number, + offset?: number): NodeBuffer; + /** Same as ref.reinterpretUntilZeros, except that this version does not attach buffer. */ + export function _reinterpretUntilZeros(buffer: NodeBuffer, size: number, + offset?: number): NodeBuffer; + /** Same as ref.writePointer, except that this version does not attach pointer. */ + export function _writePointer(buffer: NodeBuffer, offset: number, + pointer: NodeBuffer): void; + /** Same as ref.writeObject, except that this version does not attach object. */ + export function _writeObject(buffer: NodeBuffer, offset: number, object: Object): void; + + /** Default types. */ + export var types: { + void: Type; int64: Type; ushort: Type; + int: Type; uint64: Type; float: Type; + uint: Type; long: Type; double: Type; + int8: Type; ulong: Type; Object: Type; + uint8: Type; longlong: Type; CString: Type; + int16: Type; ulonglong: Type; bool: Type; + uint16: Type; char: Type; byte: Type; + int32: Type; uchar: Type; size_t: Type; + uint32: Type; short: Type; + }; +} + +interface NodeBuffer { + /** Shorthand for `ref.address`. */ + address(): number; + /** Shorthand for `ref.deref`. */ + deref(): any; + /** Shorthand for `ref.isNull`. */ + isNull(): boolean; + /** Shorthand for `ref.readCString`. */ + readCString(offset?: number): string; + /** Shorthand for `ref.readInt64BE`. */ + readInt64BE(offset?: number): string; + /** Shorthand for `ref.readInt64LE`. */ + readInt64LE(offset?: number): string; + /** Shorthand for `ref.readObject`. */ + readObject(offset?: number): string; + /** Shorthand for `ref.readPointer`. */ + readPointer(offset?: number): string; + /** Shorthand for `ref.readUInt64BE`. */ + readUInt64BE(offset?: number): string; + /** Shorthand for `ref.readUInt64LE`. */ + readUInt64LE(offset?: number): string; + /** Shorthand for `ref.ref`. */ + ref(): NodeBuffer; + /** Shorthand for `ref.reinterpret`. */ + reinterpret(size: number, offset?: number): NodeBuffer; + /** Shorthand for `ref.reinterpretUntilZeros`. */ + reinterpretUntilZeros(size: number, offset?: number): NodeBuffer; + /** Shorthand for `ref.writeCString`. */ + writeCString(offset: number, string: string, encoding?: string): void; + /** Shorthand for `ref.writeInt64BE`. */ + writeInt64BE(offset: number, input: number): any; + /** Shorthand for `ref.writeInt64BE`. */ + writeInt64BE(offset: number, input: string): any; + /** Shorthand for `ref.writeInt64LE`. */ + writeInt64LE(offset: number, input: number): any; + /** Shorthand for `ref.writeInt64LE`. */ + writeInt64LE(offset: number, input: string): any; + /** Shorthand for `ref.writeObject`. */ + writeObject(offset: number, object: Object): void; + /** Shorthand for `ref.writePointer`. */ + writePointer(offset: number, pointer: NodeBuffer): void; + /** Shorthand for `ref.writeUInt64BE`. */ + writeUInt64BE(offset: number, input: number): any; + /** Shorthand for `ref.writeUInt64BE`. */ + writeUInt64BE(offset: number, input: string): any; + /** Shorthand for `ref.writeUInt64LE`. */ + writeUInt64LE(offset: number, input: number): any; + /** Shorthand for `ref.writeUInt64LE`. */ + writeUInt64LE(offset: number, input: string): any; + + /** + * Generate string for inspecting. + * String includes the hex-encoded memory address of the Buffer instance. + * @override + */ + inspect(): string; + type: any; +} + +declare module "ref-array" { + import ref = require('ref'); + + interface ArrayType extends ref.Type { + BYTES_PER_ELEMENT: number; + fixedLength: number; + /** The reference to the base type. */ + type: ref.Type; + + /** + * Accepts a Buffer instance that should be an already-populated with data + * for the ArrayType. The "length" of the Array is determined by searching + * through the buffer's contents until an aligned NULL pointer is encountered. + */ + untilZeros(buffer: NodeBuffer): { [i: number]: T; length: number; toArray(): T[]; + toJSON(): T[]; inspect(): string; buffer: NodeBuffer; ref(): NodeBuffer; }; + + new (length?: number): { [i: number]: T; length: number; toArray(): T[]; + toJSON(): T[]; inspect(): string; buffer: NodeBuffer; ref(): NodeBuffer; }; + new (data: number[], length?: number): { [i: number]: T; length: number; toArray(): T[]; + toJSON(): T[]; inspect(): string; buffer: NodeBuffer; ref(): NodeBuffer; }; + new (data: NodeBuffer, length?: number): { [i: number]: T; length: number; toArray(): T[]; + toJSON(): T[]; inspect(): string; buffer: NodeBuffer; ref(): NodeBuffer; }; + (length?: number): { [i: number]: T; length: number; toArray(): T[]; + toJSON(): T[]; inspect(): string; buffer: NodeBuffer; ref(): NodeBuffer; }; + (data: number[], length?: number): { [i: number]: T; length: number; toArray(): T[]; + toJSON(): T[]; inspect(): string; buffer: NodeBuffer; ref(): NodeBuffer; }; + (data: NodeBuffer, length?: number): { [i: number]: T; length: number; toArray(): T[]; + toJSON(): T[]; inspect(): string; buffer: NodeBuffer; ref(): NodeBuffer; }; + address: any; + } + + /** + * The array type meta-constructor. + * The returned constructor's API is highly influenced by the WebGL + * TypedArray API. + */ + var ArrayType: { + new (type: ref.Type, length?: number): ArrayType; + new (type: string, length?: number): ArrayType; + (type: ref.Type, length?: number): ArrayType; + (type: string, length?: number): ArrayType; + }; + +export = ArrayType; +} + +declare module "ref-struct" { + import ref = require('ref'); + + /** + * This is the `constructor` of the Struct type that gets returned. + * + * Invoke it with `new` to create a new Buffer instance backing the struct. + * Pass it an existing Buffer instance to use that as the backing buffer. + * Pass in an Object containing the struct fields to auto-populate the + * struct with the data. + * + * @constructor + */ + interface StructType extends ref.Type { + /** Pass it an existing Buffer instance to use that as the backing buffer. */ + new (arg: NodeBuffer, data?: {}): any; + new (data?: {}): any; + /** Pass it an existing Buffer instance to use that as the backing buffer. */ + (arg: NodeBuffer, data?: {}): any; + (data?: {}): any; + + fields: {[key: string]: {type: ref.Type}}; + + /** + * Adds a new field to the struct instance with the given name and type. + * Note that this function will throw an Error if any instances of the struct + * type have already been created, therefore this function must be called at the + * beginning, before any instances are created. + */ + defineProperty(name: string, type: ref.Type): void; + + /** + * Adds a new field to the struct instance with the given name and type. + * Note that this function will throw an Error if any instances of the struct + * type have already been created, therefore this function must be called at the + * beginning, before any instances are created. + */ + defineProperty(name: string, type: string): void; + + /** + * Custom for struct type instances. + * @override + */ + toString(): string; + } + + /** The struct type meta-constructor. */ + var StructType: { + new (fields?: {}): StructType; + new (fields?: any[]): StructType; + (fields?: {}): StructType; + (fields?: any[]): StructType; + } + +export = StructType; +} + +declare module "ref-union" { + import ref = require('ref'); + + /** + * This is the `constructor` of the Struct type that gets returned. + * + * Invoke it with `new` to create a new Buffer instance backing the union. + * Pass it an existing Buffer instance to use that as the backing buffer. + * Pass in an Object containing the union fields to auto-populate the + * union with the data. + * + * @constructor + */ + interface UnionType extends ref.Type { + /** Pass it an existing Buffer instance to use that as the backing buffer. */ + new (arg: NodeBuffer, data?: {}): any; + new (data?: {}): any; + /** Pass it an existing Buffer instance to use that as the backing buffer. */ + (arg: NodeBuffer, data?: {}): any; + (data?: {}): any; + + fields: {[key: string]: {type: ref.Type}}; + + /** + * Adds a new field to the union instance with the given name and type. + * Note that this function will throw an Error if any instances of the union + * type have already been created, therefore this function must be called at the + * beginning, before any instances are created. + */ + defineProperty(name: string, type: ref.Type): void; + + /** + * Adds a new field to the union instance with the given name and type. + * Note that this function will throw an Error if any instances of the union + * type have already been created, therefore this function must be called at the + * beginning, before any instances are created. + */ + defineProperty(name: string, type: string): void; + + /** + * Custom for union type instances. + * @override + */ + toString(): string; + } + + /** The union type meta-constructor. */ + var UnionType: { + new (fields?: {}): UnionType; + new (fields?: any[]): UnionType; + (fields?: {}): UnionType; + (fields?: any[]): UnionType; + } + +export = UnionType; +} \ No newline at end of file diff --git a/definitions/plistlib.d.ts b/definitions/plistlib.d.ts new file mode 100644 index 00000000..fcd9f828 --- /dev/null +++ b/definitions/plistlib.d.ts @@ -0,0 +1,3 @@ +declare module "plistlib" { + export function toString(data: any): string; +} \ No newline at end of file diff --git a/definitions/signals.d.ts b/definitions/signals.d.ts new file mode 100644 index 00000000..2638fdd1 --- /dev/null +++ b/definitions/signals.d.ts @@ -0,0 +1,91 @@ +// Type definitions for JS-Signals +// Project: http://millermedeiros.github.io/js-signals/ +// Definitions by: Diullei Gomes +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped + +interface ISignalBinding { + active: boolean; + context: any; + params: any; + detach(): Function; + execute(paramsArr: any[]): any; + getListener(): any; + getSignal(): ISignal; + isBound(): boolean; + isOnce(): boolean; +} + +interface ISignal { + /** + * If Signal is active and should broadcast events. + */ + active: boolean; + + /** + * If Signal should keep record of previously dispatched parameters and automatically + * execute listener during add()/addOnce() if Signal was already dispatched before. + */ + memorize: boolean; + + /** + * Signals Version Number + */ + VERSION: string; + + /** + * Add a listener to the signal. + * + * @param listener Signal handler function. + * @param listenercontext Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param priority The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) + */ + add(listener: any, listenerContext?: any, priority?: number): ISignalBinding; + + /** + * Add listener to the signal that should be removed after first execution (will be executed only once). + * + * @param listener Signal handler function. + * @param listenercontext Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param priority The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) + */ + addOnce(listener: Function, listenerContext?: any, priority?: number): ISignalBinding; + + /** + * Dispatch/Broadcast Signal to all listeners added to the queue. + * + * @param params Parameters that should be passed to each handler. + */ + dispatch(...params: any[]): void; + + /** + * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object). + */ + dispose(): void; + + /** + * Forget memorized arguments. + */ + forget(): void; + + /** + * Returns a number of listeners attached to the Signal. + */ + getNumListeners(): number; + + /** + * Stop propagation of the event, blocking the dispatch to next listeners on the queue. + */ + halt(): void; + + /** + * Check if listener was attached to Signal. + */ + has(listener: Function, context?: any): boolean; + + /** + * Remove a single listener from the dispatch queue. + */ + remove(listener: Function, context?: any): Function; + + removeAll(): void; +} diff --git a/definitions/temp.d.ts b/definitions/temp.d.ts new file mode 100644 index 00000000..1cd5c58b --- /dev/null +++ b/definitions/temp.d.ts @@ -0,0 +1,12 @@ + +interface ITempPathOptions { + prefix?: string; + suffix?: string; +} + +declare module "temp" { + function track(): void; + function cleanup(): void; + function mkdirSync(affixes: string): string; + function path(options: ITempPathOptions) : string; +} diff --git a/events/signal.ts b/events/signal.ts new file mode 100644 index 00000000..e2d3cdc2 --- /dev/null +++ b/events/signal.ts @@ -0,0 +1,480 @@ +/// +export class SignalBinding implements ISignalBinding { + + /** + * Object that represents a binding between a Signal and a listener function. + *
- This is an internal constructor and shouldn't be called by regular users. + *
- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. + * @author Miller Medeiros + * @constructor + * @internal + * @name SignalBinding + * @param {Signal} signal Reference to Signal object that listener is currently bound to. + * @param {Function} listener Handler function bound to the signal. + * @param {booleanean} isOnce If binding should be executed just once. + * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param {Number} [priority] The priority level of the event listener. (default = 0). + */ + constructor(signal: Signal, listener: Function, isOnce: boolean, listenerContext: any, priority?: number) { + + this._listener = listener; + this._isOnce = isOnce; + this.context = listenerContext; + this._signal = signal; + this.priority = priority || 0; + + } + + /** + * Handler function bound to the signal. + * @type Function + * @private + */ + private _listener: Function; + + /** + * If binding should be executed just once. + * @type booleanean + * @private + */ + private _isOnce: boolean; + + /** + * Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @memberOf SignalBinding.prototype + * @name context + * @type Object|undefined|null + */ + public context: any; + + /** + * Reference to Signal object that listener is currently bound to. + * @type Signal + * @private + */ + private _signal: Signal; + + /** + * Listener priority + * @type Number + */ + public priority: number; + + /** + * If binding is active and should be executed. + * @type booleanean + */ + public active: boolean = true; + + /** + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters) + * @type Array|null + */ + public params: any[] = null; + + /** + * Call listener passing arbitrary parameters. + *

If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.

+ * @param {Array} [paramsArr] Array of parameters that should be passed to the listener + * @return {*} Value returned by the listener. + */ + public execute(paramsArr?: any[]): any { + + var handlerReturn: any; + var params: any[]; + + if (this.active && !!this._listener) + { + params = this.params ? this.params.concat(paramsArr) : paramsArr; + + handlerReturn = this._listener.apply(this.context, params); + + if (this._isOnce) + { + this.detach(); + } + } + + return handlerReturn; + + } + + /** + * Detach binding from signal. + * - alias to: mySignal.remove(myBinding.getListener()); + * @return {Function|null} Handler function bound to the signal or `null` if binding was previously detached. + */ + public detach() { + + return this.isBound() ? this._signal.remove(this._listener, this.context) : null; + + } + + /** + * @return {booleanean} `true` if binding is still bound to the signal and have a listener. + */ + public isBound(): boolean { + + return (!!this._signal && !!this._listener); + + } + + /** + * @return {booleanean} If SignalBinding will only be executed once. + */ + public isOnce(): boolean { + + return this._isOnce; + + } + + /** + * @return {Function} Handler function bound to the signal. + */ + public getListener() { + + return this._listener; + + } + + /** + * @return {Signal} Signal that listener is currently bound to. + */ + public getSignal() { + + return this._signal; + + } + + /** + * Delete instance properties + * @private + */ + public _destroy() { + + delete this._signal; + delete this._listener; + delete this.context; + + } + + /** + * @return {string} String representation of the object. + */ + public toString(): string { + + return '[SignalBinding isOnce:' + this._isOnce + ', isBound:' + this.isBound() + ', active:' + this.active + ']'; + + } + +} + +export class Signal implements ISignal { + + /** + * @property _bindings + * @type Array + * @private + */ + private _bindings: SignalBinding[] = []; + + /** + * @property _prevParams + * @type Any + * @private + */ + private _prevParams: any = null; + + /** + * Signals Version Number + * @property VERSION + * @type String + * @const + */ + public VERSION: string = '1.0.0'; + + /** + * If Signal should keep record of previously dispatched parameters and + * automatically execute listener during `add()`/`addOnce()` if Signal was + * already dispatched before.` + * @type booleanean + */ + public memorize: boolean = false; + + /** + * @type booleanean + * @private + */ + private _shouldPropagate: boolean = true; + + /** + * If Signal is active and should broadcast events. + *

IMPORTANT: Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.

+ * @type booleanean + */ + public active: boolean = true; + + /** + * @method validateListener + * @param {Any} listener + * @param {Any} fnName + */ + public validateListener(listener: Function, fnName: string): void { + + if (typeof listener !== 'function') + { + throw new Error('listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName)); + } + + } + + /** + * @param {Function} listener + * @param {booleanean} isOnce + * @param {Object} [listenerContext] + * @param {Number} [priority] + * @return {SignalBinding} + * @private + */ + private _registerListener(listener: Function, isOnce: boolean, listenerContext: any, priority: number): SignalBinding { + + var prevIndex: number = this._indexOfListener(listener, listenerContext); + var binding: SignalBinding; + + if (prevIndex !== -1) + { + binding = this._bindings[prevIndex]; + + if (binding.isOnce() !== isOnce) + { + throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.'); + } + } + else + { + binding = new SignalBinding(this, listener, isOnce, listenerContext, priority); + + this._addBinding(binding); + } + + if (this.memorize && this._prevParams) + { + binding.execute(this._prevParams); + } + + return binding; + + } + + /** + * @method _addBinding + * @param {SignalBinding} binding + * @private + */ + private _addBinding(binding: SignalBinding) { + + //simplified insertion sort + + var n: number = this._bindings.length; + + do { --n; } while (this._bindings[n] && binding.priority <= this._bindings[n].priority); + + this._bindings.splice(n + 1, 0, binding); + + } + + /** + * @method _indexOfListener + * @param {Function} listener + * @return {number} + * @private + */ + private _indexOfListener(listener: Function, context: any): number { + + var n: number = this._bindings.length; + var cur: SignalBinding; + + while (n--) + { + cur = this._bindings[n]; + + if (cur.getListener() === listener && cur.context === context) + { + return n; + } + } + + return -1; + + } + + /** + * Check if listener was attached to Signal. + * @param {Function} listener + * @param {Object} [context] + * @return {booleanean} if Signal has the specified listener. + */ + public has(listener: Function, context?: any): boolean { + + return this._indexOfListener(listener, context) !== -1; + + } + + /** + * Add a listener to the signal. + * @param {Function} listener Signal handler function. + * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) + * @return {SignalBinding} An Object representing the binding between the Signal and listener. + */ + public add(listener: Function, listenerContext?: any, priority?: number): SignalBinding { + + this.validateListener(listener, 'add'); + + return this._registerListener(listener, false, listenerContext, priority); + + } + + /** + * Add listener to the signal that should be removed after first execution (will be executed only once). + * @param {Function} listener Signal handler function. + * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) + * @return {SignalBinding} An Object representing the binding between the Signal and listener. + */ + public addOnce(listener: Function, listenerContext?: any, priority?: number): SignalBinding { + + this.validateListener(listener, 'addOnce'); + + return this._registerListener(listener, true, listenerContext, priority); + + } + + /** + * Remove a single listener from the dispatch queue. + * @param {Function} listener Handler function that should be removed. + * @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context). + * @return {Function} Listener handler function. + */ + public remove(listener: Function, context?: any): Function { + + this.validateListener(listener, 'remove'); + + var i: number = this._indexOfListener(listener, context); + + if (i !== -1) + { + this._bindings[i]._destroy(); //no reason to a SignalBinding exist if it isn't attached to a signal + this._bindings.splice(i, 1); + } + + return listener; + + } + + /** + * Remove all listeners from the Signal. + */ + public removeAll(): void { + + var n: number = this._bindings.length; + + while (n--) + { + this._bindings[n]._destroy(); + } + + this._bindings.length = 0; + + } + + /** + * @return {number} Number of listeners attached to the Signal. + */ + public getNumListeners(): number { + + return this._bindings.length; + + } + + /** + * Stop propagation of the event, blocking the dispatch to next listeners on the queue. + *

IMPORTANT: should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.

+ * @see Signal.prototype.disable + */ + public halt(): void { + + this._shouldPropagate = false; + + } + + /** + * Dispatch/Broadcast Signal to all listeners added to the queue. + * @param {...*} [params] Parameters that should be passed to each handler. + */ + public dispatch(...paramsArr: any[]): void { + + if (!this.active) + { + return; + } + + var n: number = this._bindings.length; + var bindings: SignalBinding[]; + + if (this.memorize) + { + this._prevParams = paramsArr; + } + + if (!n) + { + //should come after memorize + return; + } + + bindings = this._bindings.slice(0); //clone array in case add/remove items during dispatch + + this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch. + + //execute all callbacks until end of the list or until a callback returns `false` or stops propagation + //reverse loop since listeners with higher priority will be added at the end of the list + do { n--; } while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false); + + } + + /** + * Forget memorized arguments. + * @see Signal.memorize + */ + public forget(): void { + + this._prevParams = null; + + } + + /** + * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object). + *

IMPORTANT: calling any method on the signal instance after calling dispose will throw errors.

+ */ + public dispose(): void { + + this.removeAll(); + + delete this._bindings; + delete this._prevParams; + + } + + /** + * @return {string} String representation of the object. + */ + public toString(): string { + + return '[Signal active:' + this.active + ' numListeners:' + this.getNumListeners() + ']'; + + } + +} + +$injector.register("signal", Signal); \ No newline at end of file diff --git a/file-system.ts b/file-system.ts index 0d7efbe8..68f7864b 100644 --- a/file-system.ts +++ b/file-system.ts @@ -6,7 +6,7 @@ import Future = require("fibers/future"); import path = require("path"); import util = require("util"); import rimraf = require("rimraf"); -import helpers = require("./helpers"); +import hostInfo = require("./../common/host-info"); export class FileSystem implements IFileSystem { private _stat = Future.wrap(fs.stat); @@ -57,7 +57,7 @@ export class FileSystem implements IFileSystem { public unzip(zipFile: string, destinationDir: string): IFuture { return (() => { - if (helpers.isDarwin()) { + if (hostInfo.isDarwin()) { var $childProcess = $injector.resolve("$childProcess"); this.createDirectory(destinationDir).wait(); diff --git a/helpers.ts b/helpers.ts index cd77ef39..e04cfcca 100644 --- a/helpers.ts +++ b/helpers.ts @@ -3,10 +3,6 @@ import fs = require("fs"); import path = require("path"); -export function isDarwin() { - return process.platform === "darwin"; -} - export function stringReplaceAll(string: string, find: any, replace: string): string { return string.split(find).join(replace); } @@ -81,10 +77,6 @@ export function formatListOfNames(names: string[], conjunction = "or"): string { } } -export function isWindows() { - return process.platform === "win32"; -} - export function versionCompare(version1: string, version2: string): number { version1 = version1.split("-")[0]; version2 = version2.split("-")[0]; @@ -113,9 +105,9 @@ export function toBoolean(str: string) { } export function registerCommand(module: string, commandName: any, executor: (module: any, args: string[]) => IFuture, opts?: ICommandOptions) { - var factory = (): ICommand => { + var factory = ():ICommand => { return { - execute: (args: string[]): IFuture => { + execute: (args:string[]):IFuture => { var mod = $injector.resolve(module); return executor(mod, args); }, @@ -124,4 +116,22 @@ export function registerCommand(module: string, commandName: any, executor: (mod }; $injector.registerCommand(commandName, factory); +} + +export function block(operation: () => void): void { + if (isInteractive()) { + process.stdin.setRawMode(false); + } + operation(); + if (isInteractive()) { + process.stdin.setRawMode(true); + } +} + +export function isNumber(n: any): boolean { + return !isNaN(parseFloat(n)) && isFinite(n); +} + +export function fromWindowsRelativePathToUnix(windowsRelativePath: string): string { + return windowsRelativePath.replace(/\\/g, "/"); } \ No newline at end of file diff --git a/host-info.ts b/host-info.ts new file mode 100644 index 00000000..145e7fc5 --- /dev/null +++ b/host-info.ts @@ -0,0 +1,34 @@ +/// +"use strict"; + +export function isWindows() { + return process.platform === "win32"; +} + +export function isWindows64() { + return isWindows() && (process.arch === "x64" || process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")); +} + +export function isWindows32() { + return isWindows() && !isWindows64(); +} + +export function isDarwin() { + return process.platform.toUpperCase() === "DARWIN"; +} + +export function isLinux() { + return process.platform === "linux"; +} + +export var hostCapabilities: { [key:string]: IHostCapabilities } = { + "win32": { + debugToolsSupported: true + }, + "darwin": { + debugToolsSupported: true + }, + "linux": { + debugToolsSupported: false + } +} diff --git a/mobile/android/android-device.ts b/mobile/android/android-device.ts new file mode 100644 index 00000000..d5073256 --- /dev/null +++ b/mobile/android/android-device.ts @@ -0,0 +1,341 @@ +/// +"use strict" +import MobileHelper = require("./../mobile-helper"); +import util = require("util"); +import Future = require("fibers/future"); +import path = require("path"); +import temp = require("temp"); +import byline = require("byline"); +import helpers = require("../../helpers"); +import os = require("os"); +import hostInfo = require("../../host-info"); + +interface IAndroidDeviceDetails { + model: string; + name: string + release: string; + brand: string; +} + +export class AndroidDevice implements Mobile.IDevice { + private static REFRESH_WEB_VIEW_INTENT_NAME = "com.telerik.RefreshWebView"; + private static CHANGE_LIVESYNC_URL_INTENT_NAME = "com.telerik.ChangeLiveSyncUrl"; + private static LIVESYNC_BROADCAST_NAME = "com.telerik.LiveSync"; + + private static DEVICE_TMP_DIR = "/data/local/tmp"; + private static ION_VER_NEW_SYNC_PROTOCOL = "2.5"; + private static SYNC_ROOT = "12590FAA-5EDD-4B12-856D-F52A0A1599F2"; + private static COMMANDS_FILE = "telerik.livesync.commands"; + + private model: string; + private name: string; + private version: string; + private vendor: string; + private _installedApplications: string[]; + + constructor(private identifier: string, private adb: string, + private $logger: ILogger, + private $fs: IFileSystem, + private $childProcess: IChildProcess, + private $errors: IErrors, + private $propertiesParser: IPropertiesParser, + private $staticConfig: IStaticConfig) { + var details: IAndroidDeviceDetails = this.getDeviceDetails().wait(); + this.model = details.model; + this.name = details.name; + this.version = details.release; + this.vendor = details.brand; + } + + private getDeviceDetails(): IFuture { + return (() => { + var requestDeviceDetailsCommand = this.composeCommand("shell cat /system/build.prop"); + var details: string = this.$childProcess.exec(requestDeviceDetailsCommand).wait(); + + var parsedDetails: any = {}; + details.split(/\r?\n|\r/).forEach((value) => { + //sample line is "ro.build.version.release=4.4" + var match = /(?:ro\.build\.version|ro\.product)\.(.+)=(.+)/.exec(value) + if (match) { + parsedDetails[match[1]] = match[2]; + } + }); + + return parsedDetails; + }).future()(); + } + + public getPlatform(): string { + return MobileHelper.DevicePlatforms[MobileHelper.DevicePlatforms.Android]; + } + + public getIdentifier(): string { + return this.identifier; + } + + public getDisplayName(): string { + return this.name; + } + + public getModel(): string { + return this.model; + } + + public getVersion(): string { + return this.version; + } + + public getVendor(): string { + return this.vendor; + } + + public getInstalledApplications(): IFuture { + return (() => { + if (!this._installedApplications) { + var listPackagesCommand = this.composeCommand("shell pm list packages") + var result = this.$childProcess.exec(listPackagesCommand).wait(); + this._installedApplications = _.map(result.split(os.EOL), (packageString: string) => { + var match = packageString.match(/package:(.+)/); + return match ? match[1] : null; + }).filter(parsedPackage => parsedPackage != null); + } + + return this._installedApplications + }).future()(); + } + + private composeCommand(...args: string[]) { + var command = util.format.apply(null, args); + var result = util.format("\"%s\" -s %s", this.adb, this.identifier); + if (command && !command.isEmpty()) { + result += util.format(" %s", command); + } + + return result; + } + + private startPackageOnDevice(packageName: string): IFuture { + return (() => { + var startPackageCommand = this.composeCommand("shell am start -a android.intent.action.MAIN -n %s/%s", packageName, this.$staticConfig.START_PACKAGE_ACTIVITY_NAME); + var result = this.$childProcess.exec(startPackageCommand).wait(); + return result[0]; + }).future()(); + } + + public deploy(packageFile: string, packageName: string): IFuture { + return (() => { + var uninstallCommand = this.composeCommand("shell pm uninstall \"%s\"", packageName) + this.$childProcess.exec(uninstallCommand).wait(); + + var installCommand = this.composeCommand("install -r \"%s\"", packageFile); + this.$childProcess.exec(installCommand).wait(); + + this.startPackageOnDevice(packageName).wait(); + this.$logger.info("Successfully deployed on device with identifier '%s'", this.getIdentifier()); + }).future()(); + } + + private _tmpRoot: IStringDictionary = Object.create(null); + private prepareTmpDir(appIdentifier: Mobile.IAppIdentifier): IFuture { + return (() => { + if (!this._tmpRoot[appIdentifier.appIdentifier]) { + var tmpRoot = this.buildDevicePath(AndroidDevice.DEVICE_TMP_DIR, AndroidDevice.SYNC_ROOT, appIdentifier.appIdentifier); + var filesInTmp = this.buildDevicePath(tmpRoot, "*"); + + var command = this.composeCommand('shell mkdir -p "%s"', tmpRoot); + this.$childProcess.exec(command).wait(); + command = this.composeCommand('shell rm -rf "%s"', filesInTmp); + this.$childProcess.exec(command).wait(); + this._tmpRoot[appIdentifier.appIdentifier] = tmpRoot; + } + return this._tmpRoot[appIdentifier.appIdentifier]; + }).future()(); + } + + private pushFilesOnDevice(localToDevicePaths: Mobile.ILocalToDevicePathData[], appIdentifier: Mobile.IAppIdentifier): IFuture { + return (() => { + // On Samsung Android 4.3 and Nexus KitKat & L devices, one cannot adb push to /data/data/appId/ directly + // Instead, we push to /data/local/tmp, where we have the required permissions and them mv to the final destination + var tmpRoot = this.prepareTmpDir(appIdentifier).wait(); + + localToDevicePaths.forEach((localToDevicePathData) => { + var tmpPath = this.buildDevicePath(tmpRoot, helpers.fromWindowsRelativePathToUnix(localToDevicePathData.getRelativeToProjectBasePath())); + this.pushFileOnDevice(localToDevicePathData.getLocalPath(), tmpPath).wait(); + }); + + // move the files from the tmp dir into their proper path. + // Due to limitation of android toolset, we use a more involved shell script + // the following line finds all files and subfolders in the tmp dir, + // removes the corresponding entries in the data dir and then moves the /tmp files in their proper place on /data + // we set IFS so that for will properly iterate over files with spaces in their names + // we use for `ls`, because android toolbox lacks find + var adbCommand = util.format('IFS=$\'\\n\'; for i in $(ls -a %s); do rm -rf %s/$i && mv %s/$i %s; done; unset IFS', + tmpRoot, appIdentifier.deviceProjectPath, tmpRoot, appIdentifier.deviceProjectPath); + this.$childProcess.execFile(this.adb, [ + "-s", this.identifier, + "shell", + adbCommand + ]).wait(); + }).future()(); + } + + private pushFileOnDevice(localPath: string, devicePath: string): IFuture { + return (() => { + var rmCommand = this.composeCommand('shell rm -r "%s"', devicePath); + this.$childProcess.exec(rmCommand).wait(); + + if (this.$fs.exists(localPath).wait()) { + var isDirectory = this.$fs.getFsStats(localPath).wait().isDirectory(); + + var mkdirCommand = this.composeCommand('shell mkdir -p "%s"', isDirectory ? devicePath : path.dirname(devicePath)); + this.$childProcess.exec(mkdirCommand).wait(); + + var pushFileCommand = this.composeCommand('push "%s" "%s"', isDirectory ? path.join(localPath, ".") : localPath, devicePath); + this.$childProcess.exec(pushFileCommand).wait(); + } + }).future()(); + } + + public sendBroadcastToDevice(action: string, extras: IStringDictionary = {}): IFuture { + return (() => { + var broadcastCommand = this.composeCommand("shell am broadcast -a \"%s\"", action); + + Object.keys(extras).forEach((key) => { + broadcastCommand += util.format(" -e \"%s\" \"%s\"", key, extras[key]); + }); + + var result = this.$childProcess.exec(broadcastCommand).wait(); + var match = result.match(/Broadcast completed: result=(\d+)/); + if (match) { + return +match[1]; + } else { + this.$errors.fail("Unable to broadcast to android device:\n%s", result); + } + }).future()(); + } + + private getLiveSyncUrl(projectType: number): string { + switch (projectType) { + case 0: return "icenium://"; + case 1: return "nativescript://"; + default: throw new Error("Unsupported project type"); + } + } + + public sync(localToDevicePaths: Mobile.ILocalToDevicePathData[], appIdentifier: Mobile.IAppIdentifier, projectType: number, options: Mobile.ISyncOptions = {}): IFuture { + return (() => { + if (appIdentifier.isLiveSyncSupported(this).wait()) { + var ionVer = this.getIonVersion(appIdentifier).wait(); + if (this.isNewProtocol(ionVer, AndroidDevice.ION_VER_NEW_SYNC_PROTOCOL)) { + this.syncNewProtocol(localToDevicePaths, appIdentifier, projectType, options).wait(); + } else { + this.syncOldProtocol(localToDevicePaths, appIdentifier, projectType, options).wait(); + } + this.$logger.info("Successfully synced device with identifier '%s'", this.getIdentifier()); + } else { + this.$errors.fail({formatStr: appIdentifier.getliveSyncNotSupportedError(this), suppressCommandHelp: true }); + } + }).future()(); + } + + private syncOldProtocol(localToDevicePaths: Mobile.ILocalToDevicePathData[], appIdentifier: Mobile.IAppIdentifier, projectType: number, options: Mobile.ISyncOptions = {}): IFuture { + return (() => { + this.pushFilesOnDevice(localToDevicePaths, appIdentifier).wait(); + if (!options.skipRefresh) { + var changeLiveSyncUrlExtras: IStringDictionary = { + "liveSyncUrl": this.getLiveSyncUrl(projectType), + "app-id": appIdentifier.appIdentifier + }; + this.sendBroadcastToDevice(AndroidDevice.CHANGE_LIVESYNC_URL_INTENT_NAME, changeLiveSyncUrlExtras).wait(); + this.sendBroadcastToDevice(AndroidDevice.REFRESH_WEB_VIEW_INTENT_NAME, { "app-id": appIdentifier.appIdentifier }).wait(); + } + }).future()(); + } + + private getTempDir(): string { + temp.track(); + return temp.mkdirSync("ab-"); + } + + private syncNewProtocol(localToDevicePaths: Mobile.ILocalToDevicePathData[], appIdentifier: Mobile.IAppIdentifier, projectType: number, options: Mobile.ISyncOptions = {}): IFuture { + return (() => { + this.pushFilesOnDevice(localToDevicePaths, appIdentifier).wait(); + // create the commands file + var hostTmpDir = this.getTempDir(); + var commandsFileHostPath = path.join(hostTmpDir, AndroidDevice.COMMANDS_FILE); + var commandsFile = this.$fs.createWriteStream(commandsFileHostPath); + var fileWritten = this.$fs.futureFromEvent(commandsFile, 'finish'); + commandsFile.write("DeployProject " + this.getLiveSyncUrl(projectType) + '\r'); + commandsFile.write("ReloadStartView" + '\r'); + commandsFile.end(); + fileWritten.wait(); + // copy it to the device + var commandsFileDevicePath = this.buildDevicePath(this.prepareTmpDir(appIdentifier).wait(), AndroidDevice.COMMANDS_FILE); + this.pushFileOnDevice(commandsFileHostPath, commandsFileDevicePath).wait(); + // send the refresh notification + this.sendBroadcastToDevice(AndroidDevice.LIVESYNC_BROADCAST_NAME, { "app-id": appIdentifier.appIdentifier }).wait(); + }).future()(); + } + + private getIonVersion(appIdentifier: Mobile.IAppIdentifier): IFuture { + return (() => { + var output = (this.$childProcess.execFile(this.adb, [ + "-s", this.getIdentifier(), + "shell", "dumpsys", "package", appIdentifier.appIdentifier + ]).wait()); + return this.$propertiesParser.parse(output)["versionName"]; + }).future()(); + } + + private isNewProtocol(currentIonVersion: string, newProtocolversion: string): boolean { + return helpers.versionCompare(currentIonVersion, newProtocolversion) >= 0; + } + + private buildDevicePath(...args: string[]): string { + return args.join("/"); + } + + openDeviceLogStream() { + var adbLogcat = this.$childProcess.spawn(this.adb, ["-s", this.getIdentifier(), "logcat"]); + var lineStream = byline(adbLogcat.stdout); + + adbLogcat.stderr.on("data", (data: NodeBuffer) => { + this.$logger.trace("ADB logcat stderr: " + data.toString()); + }); + + adbLogcat.on("close", (code: number) => { + if (code !== 0) { + this.$logger.trace("ADB process exited with code " + code.toString()); + } + }); + + lineStream.on('data', (line: NodeBuffer) => { + var lineText = line.toString(); + var log = this.getConsoleLogFromLine(lineText); + if (log) { + if (log.tag) { + this.$logger.out("%s: %s", log.tag, log.message); + } else { + this.$logger.out(log.message); + } + } + }); + } + + private getConsoleLogFromLine(lineText: String): any { + var acceptedTags = ["chromium", "Web Console"]; + + //sample line is "I/Web Console( 4438): Received Event: deviceready at file:///storage/emulated/0/Icenium/com.telerik.TestApp/js/index.js:48" + var match = lineText.match(/.\/(.+?)\(\s*(\d+?)\): (.*)/); + if (match) { + if (acceptedTags.indexOf(match[1]) !== -1) { + return { tag: match[1], message: match[3] }; + } + } + else if (_.any(acceptedTags, (tag: string) => { return lineText.indexOf(tag) !== -1; })) { + return { message: match[3] }; + } + + return null; + } +} diff --git a/mobile/app-identifier.ts b/mobile/app-identifier.ts new file mode 100644 index 00000000..8f9e601d --- /dev/null +++ b/mobile/app-identifier.ts @@ -0,0 +1,197 @@ +/// +"use strict"; + +import path = require("path"); +import Future = require("fibers/future"); +import helpers = require("../helpers"); +import util = require("util"); + +var ANDROID_PROJECT_PATH = "mnt/sdcard/Icenium/"; +var ANDROID_NATIVESCRIPT_PROJECT_PATH = "/data/data/"; +var ANDROID_CHECK_LIVE_SYNC_INTENT = "com.telerik.IsLiveSyncSupported"; +var ANDROID_ION_APP_IDENTIFIER = "com.telerik.AppBuilder"; + +var NATIVESCRIPT_ION_APP_IDENTIFIER = "com.telerik.NativeScript"; + +var IOS_PROJECT_PATH = "/Documents/"; +var IOS_ION_APP_IDENTIFIER = "com.telerik.Icenium"; + +export class AndroidAppIdentifier implements Mobile.IAppIdentifier { + constructor(private _appIdentifier: string) {} + + get appIdentifier(): string { + return this._appIdentifier; + } + + get deviceProjectPath(): string { + return helpers.fromWindowsRelativePathToUnix(path.join(ANDROID_PROJECT_PATH, this.appIdentifier)); + } + + get liveSyncFormat(): string { + return ""; + } + + getliveSyncNotSupportedError(device: Mobile.IDevice): string { + return util.format("You can't LiveSync on %s! Deploy the app with LiveSync enabled and wait for the initial start up before LiveSyncing.", device.getIdentifier()); + } + + isLiveSyncSupported(device: any): IFuture { + return device.sendBroadcastToDevice(ANDROID_CHECK_LIVE_SYNC_INTENT, + { "app-id": this.appIdentifier }); + } +} + +export class AndroidCompanionAppIdentifier implements Mobile.IAppIdentifier { + constructor(private servedApp: string) {} + + get appIdentifier(): string { + return ANDROID_ION_APP_IDENTIFIER; + } + + get deviceProjectPath(): string { + return helpers.fromWindowsRelativePathToUnix(path.join(ANDROID_PROJECT_PATH, this.appIdentifier)); + } + + get liveSyncFormat(): string { + return "icenium://%s?LiveSyncToken=%s"; + } + + getliveSyncNotSupportedError(device: Mobile.IDevice): string { + return util.format("Cannot LiveSync changes to the companion app. The companion app is not installed on %s.", device.getIdentifier()); + } + + isLiveSyncSupported(device: Mobile.IDevice): IFuture { + return (() => { + var applications = device.getInstalledApplications().wait(); + return _.contains(applications, this.appIdentifier); + }).future()(); + } +} + +export class AndroidNativeScriptCompanionAppIdentifier implements Mobile.IAppIdentifier { + constructor(private servedApp: string) { } + + get appIdentifier(): string { + return NATIVESCRIPT_ION_APP_IDENTIFIER; + } + + get deviceProjectPath(): string { + return helpers.fromWindowsRelativePathToUnix(path.join(ANDROID_NATIVESCRIPT_PROJECT_PATH, this.appIdentifier, "files")); + } + + get liveSyncFormat(): string { + return "nativescript://%s?LiveSyncToken=%s"; + } + + getliveSyncNotSupportedError(device: Mobile.IDevice): string { + return util.format("Cannot LiveSync changes to the NativeScript companion app. The NativeScript companion app is not installed on %s.", device.getIdentifier()); + } + + isLiveSyncSupported(device: Mobile.IDevice): IFuture { + return (() => { + var applications = device.getInstalledApplications().wait(); + return _.contains(applications, this.appIdentifier); + }).future()(); + } +} + +export class IOSAppIdentifier implements Mobile.IAppIdentifier { + constructor(private _appIdentifier: string) {} + + get appIdentifier(): string { + return this._appIdentifier; + } + + get deviceProjectPath(): string { + return IOS_PROJECT_PATH; + } + + get liveSyncFormat(): string { + return ""; + } + + getliveSyncNotSupportedError(device: Mobile.IDevice): string { + return ""; + } + + isLiveSyncSupported(device: Mobile.IDevice): IFuture { + return Future.fromResult(true); + } +} + +export class IOSCompanionAppIdentifier implements Mobile.IAppIdentifier { + constructor(private servedApp: string) {} + + get appIdentifier(): string { + return IOS_ION_APP_IDENTIFIER; + } + + get deviceProjectPath(): string { + return IOS_PROJECT_PATH; + } + + get liveSyncFormat(): string { + return "icenium://%s?LiveSyncToken=%s"; + } + + getliveSyncNotSupportedError(device: Mobile.IDevice): string { + return ""; + } + + isLiveSyncSupported(device: Mobile.IDevice): IFuture { + return Future.fromResult(true); + } +} + +export class IOSNativeScriptCompanionAppIdentifier implements Mobile.IAppIdentifier { + constructor(private servedApp: string) { } + + get appIdentifier(): string { + return NATIVESCRIPT_ION_APP_IDENTIFIER; + } + + get deviceProjectPath(): string { + return IOS_PROJECT_PATH; + } + + get liveSyncFormat(): string { + return "nativescript://%s?LiveSyncToken=%s"; + } + + getliveSyncNotSupportedError(device: Mobile.IDevice): string { + return ""; + } + + isLiveSyncSupported(device: Mobile.IDevice): IFuture { + return Future.fromResult(true); + } + +} + +var factoryRules = { + iOS: { + Cordova: { + companion: IOSCompanionAppIdentifier, + vanilla: IOSAppIdentifier + }, + NativeScript: { + companion: IOSNativeScriptCompanionAppIdentifier + } + }, + Android: { + Cordova: { + companion: AndroidCompanionAppIdentifier, + vanilla: AndroidAppIdentifier + }, + NativeScript: { + companion: AndroidNativeScriptCompanionAppIdentifier + } + } +}; + +export function createAppIdentifier(platform: string, appIdentifier: string, companion: boolean, projectType: number): Mobile.IAppIdentifier { + var projectTypes: any = $injector.resolve("projectTypes"); + var projectTypeString = projectTypes[projectType]; + var ctor = factoryRules[platform][projectTypeString][companion ? "companion" : "vanilla"]; + return new ctor(appIdentifier); +} \ No newline at end of file diff --git a/mobile/constants.ts b/mobile/constants.ts new file mode 100644 index 00000000..039ea2ce --- /dev/null +++ b/mobile/constants.ts @@ -0,0 +1,10 @@ +// enumeration taken from ProvisionType.cs + +export class ProvisionType { + static Development = "Development"; + static AdHoc = "AdHoc"; + static AppStore = "AppStore"; + static Enterprise = "Enterprise"; +} + +export var ERROR_NO_DEVICES = "Cannot find connected devices. Reconnect any connected devices, verify that your system recognizes them, and run this command again"; \ No newline at end of file diff --git a/mobile/ios/ios-core.ts b/mobile/ios/ios-core.ts new file mode 100644 index 00000000..01ff45d7 --- /dev/null +++ b/mobile/ios/ios-core.ts @@ -0,0 +1,762 @@ +/// +"use strict"; + +import path = require("path"); +import ref = require("ref"); +import ffi = require("ffi"); +import struct = require("ref-struct"); +import bufferpack = require("bufferpack"); +import plistlib = require("plistlib"); +import helpers = require("../../helpers"); +import hostInfo = require("../../host-info"); +import net = require("net"); +import util = require("util"); +import Future = require("fibers/future"); + +export class CoreTypes { + public static pointerSize = ref.types.size_t.size; + public static voidPtr = ref.refType(ref.types.void); + public static intPtr = ref.refType(ref.types.int); + public static uintPtr = ref.refType(ref.types.uint); + public static charPtr = ref.refType(ref.types.char); + public static ptrToVoidPtr = ref.refType(ref.refType(ref.types.void)); + public static uintType = ref.types.uint; + public static uint32Type = ref.types.uint32; + public static intType = ref.types.int; + public static boolType = ref.types.bool; + public static doubleType = ref.types.double; + + public static am_device_p = CoreTypes.voidPtr; + public static cfDictionaryRef = CoreTypes.voidPtr; + public static cfDataRef = CoreTypes.voidPtr; + public static cfStringRef = CoreTypes.voidPtr; + public static afcConnectionRef = CoreTypes.voidPtr; + public static afcFileRef = ref.types.uint64; + public static afcDirectoryRef = CoreTypes.voidPtr; + public static afcError = ref.types.uint32; + public static amDeviceRef = CoreTypes.voidPtr; + public static amDeviceNotificationRef = CoreTypes.voidPtr; + public static cfTimeInterval = ref.types.double; + public static kCFPropertyListXMLFormat_v1_0 = 100; + public static kCFPropertyListBinaryFormat_v1_0 = 200; + public static kCFPropertyListImmutable = 0; + + public static am_device_notification = struct({ + unknown0: ref.types.uint32, + unknown1: ref.types.uint32, + unknown2: ref.types.uint32, + callback: CoreTypes.voidPtr, + cookie: ref.types.uint32 + }); + + public static am_device_notification_callback_info = struct({ + dev: CoreTypes.am_device_p, + msg: ref.types.uint, + subscription: ref.refType(CoreTypes.am_device_notification) + }); + + public static am_device_notification_callback = ffi.Function("void", [ref.refType(CoreTypes.am_device_notification_callback_info), CoreTypes.voidPtr]); + public static am_device_install_application_callback = ffi.Function("void", [CoreTypes.cfDictionaryRef, CoreTypes.voidPtr]); + public static cf_run_loop_timer_callback = ffi.Function("void", [CoreTypes.voidPtr, CoreTypes.voidPtr]); +} + +class IOSCore implements Mobile.IiOSCore { + + constructor(private $logger: ILogger, + private $fs: IFileSystem, + private $errors: IErrors) { } + + private cfDictionaryKeyCallBacks = struct({ + version: CoreTypes.uintType, + retain: CoreTypes.voidPtr, + release: CoreTypes.voidPtr, + copyDescription: CoreTypes.voidPtr, + equal: CoreTypes.voidPtr, + hash: CoreTypes.voidPtr + }); + + private cfDictionaryValueCallBacks = struct({ + version: CoreTypes.uintType, + retain: CoreTypes.voidPtr, + release: CoreTypes.voidPtr, + copyDescription: CoreTypes.voidPtr, + equal: CoreTypes.voidPtr + }); + + public static kCFStringEncodingUTF8 = 0x08000100; + + private get CoreFoundationDir(): string { + if(hostInfo.isWindows()) { + return path.join(this.CommonProgramFilesPath, "Apple", "Apple Application Support"); + } else if(hostInfo.isDarwin()) { + return "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"; + } + + return null; + } + + private get MobileDeviceDir(): string { + if(hostInfo.isWindows()) { + return path.join(this.CommonProgramFilesPath, "Apple", "Mobile Device Support"); + } else if(hostInfo.isDarwin()) { + return "/System/Library/PrivateFrameworks/MobileDevice.framework/MobileDevice"; + } + + return null; + } + + private get CommonProgramFilesPath(): string { + return hostInfo.isWindows64() ? process.env["CommonProgramFiles(x86)"] : process.env.CommonProgramFiles; + } + + private is32BitProcess(): boolean { + return ref.types.size_t.size === 4; + } + + private getForeignPointer(lib: ffi.DynamicLibrary, name: string, type: ref.Type): NodeBuffer { + var pointer = lib.get(name); + pointer.type = ref.refType(type); + return pointer; + } + + public getCoreFoundationLibrary(): {[key: string]: any} { + if(hostInfo.isWindows()) { + process.env.PATH = this.CoreFoundationDir + ";" + process.env.PATH; + process.env.PATH += ";" + this.MobileDeviceDir; + } + + var coreFoundationDll = hostInfo.isWindows() ? path.join(this.CoreFoundationDir, "CoreFoundation.dll") : this.CoreFoundationDir; + var lib = ffi.DynamicLibrary(coreFoundationDll); + + return { + "CFRunLoopRun": ffi.ForeignFunction(lib.get("CFRunLoopRun"), "void", []), + "CFRunLoopStop": ffi.ForeignFunction(lib.get("CFRunLoopStop"), "void", [CoreTypes.voidPtr]), + "CFRunLoopGetCurrent": ffi.ForeignFunction(lib.get("CFRunLoopGetCurrent"), CoreTypes.voidPtr, []), + "CFStringCreateWithCString": ffi.ForeignFunction(lib.get("CFStringCreateWithCString"), CoreTypes.cfStringRef, [CoreTypes.voidPtr, "string", "uint"]), + "CFDictionaryGetValue": ffi.ForeignFunction(lib.get("CFDictionaryGetValue"), CoreTypes.voidPtr, [CoreTypes.cfDictionaryRef, CoreTypes.cfStringRef]), + "CFNumberGetValue": ffi.ForeignFunction(lib.get("CFNumberGetValue"), CoreTypes.boolType, [CoreTypes.voidPtr, "uint", CoreTypes.voidPtr]), + "CFStringGetCStringPtr": ffi.ForeignFunction(lib.get("CFStringGetCStringPtr"), CoreTypes.charPtr, [CoreTypes.cfStringRef, "uint"]), + "CFStringGetCString": ffi.ForeignFunction(lib.get("CFStringGetCString"), CoreTypes.boolType, [CoreTypes.cfStringRef, CoreTypes.charPtr, "uint", "uint"]), + "CFStringGetLength": ffi.ForeignFunction(lib.get("CFStringGetLength"), "ulong", [CoreTypes.cfStringRef]), + "CFDictionaryGetCount": ffi.ForeignFunction(lib.get("CFDictionaryGetCount"), "int", [CoreTypes.cfDictionaryRef]), + "CFDictionaryGetKeysAndValues": ffi.ForeignFunction(lib.get("CFDictionaryGetKeysAndValues"), "void", [CoreTypes.cfDictionaryRef, CoreTypes.ptrToVoidPtr, CoreTypes.ptrToVoidPtr]), + "CFDictionaryCreate": ffi.ForeignFunction(lib.get("CFDictionaryCreate"), CoreTypes.cfDictionaryRef, [CoreTypes.voidPtr, CoreTypes.ptrToVoidPtr, CoreTypes.ptrToVoidPtr, "int", ref.refType(this.cfDictionaryKeyCallBacks), ref.refType(this.cfDictionaryValueCallBacks)]), + "kCFTypeDictionaryKeyCallBacks": lib.get("kCFTypeDictionaryKeyCallBacks"), + "kCFTypeDictionaryValueCallBacks": lib.get("kCFTypeDictionaryValueCallBacks"), + "CFRunLoopRunInMode": ffi.ForeignFunction(lib.get("CFRunLoopRunInMode"),CoreTypes.intType, [CoreTypes.cfStringRef, CoreTypes.cfTimeInterval, CoreTypes.boolType]), + "kCFRunLoopDefaultMode": this.getForeignPointer(lib, "kCFRunLoopDefaultMode", ref.types.void), + "kCFRunLoopCommonModes": this.getForeignPointer(lib, "kCFRunLoopCommonModes", ref.types.void), + "CFRunLoopTimerCreate": ffi.ForeignFunction(lib.get("CFRunLoopTimerCreate"), CoreTypes.voidPtr, [CoreTypes.voidPtr, CoreTypes.doubleType, CoreTypes.doubleType, CoreTypes.uintType, CoreTypes.uintType, CoreTypes.cf_run_loop_timer_callback, CoreTypes.voidPtr]), + "CFRunLoopAddTimer": ffi.ForeignFunction(lib.get("CFRunLoopAddTimer"), "void", [CoreTypes.voidPtr, CoreTypes.voidPtr, CoreTypes.cfStringRef]), + "CFRunLoopRemoveTimer": ffi.ForeignFunction(lib.get("CFRunLoopRemoveTimer"), "void", [CoreTypes.voidPtr, CoreTypes.voidPtr, CoreTypes.cfStringRef]), + "CFAbsoluteTimeGetCurrent": ffi.ForeignFunction(lib.get("CFAbsoluteTimeGetCurrent"), CoreTypes.doubleType, []), + "CFPropertyListCreateData": ffi.ForeignFunction(lib.get("CFPropertyListCreateData"), CoreTypes.voidPtr, [CoreTypes.voidPtr, CoreTypes.voidPtr, ref.types.long, ref.types.ulong, CoreTypes.voidPtr]), + "CFPropertyListCreateWithData": ffi.ForeignFunction(lib.get("CFPropertyListCreateWithData"), CoreTypes.voidPtr, [CoreTypes.voidPtr, CoreTypes.voidPtr, ref.types.ulong, ref.refType(ref.types.long), CoreTypes.voidPtr]), + "CFGetTypeID": ffi.ForeignFunction(lib.get("CFGetTypeID"), ref.types.long, [CoreTypes.voidPtr]), + "CFStringGetTypeID": ffi.ForeignFunction(lib.get("CFStringGetTypeID"), ref.types.long, []), + "CFDictionaryGetTypeID": ffi.ForeignFunction(lib.get("CFDictionaryGetTypeID"), ref.types.long, []), + "CFDataGetTypeID": ffi.ForeignFunction(lib.get("CFDataGetTypeID"), ref.types.long, []), + "CFNumberGetTypeID": ffi.ForeignFunction(lib.get("CFNumberGetTypeID"), ref.types.long, []), + "CFBooleanGetTypeID": ffi.ForeignFunction(lib.get("CFBooleanGetTypeID"), ref.types.long, []), + "CFArrayGetTypeID": ffi.ForeignFunction(lib.get("CFArrayGetTypeID"), ref.types.long, []), + "CFDateGetTypeID": ffi.ForeignFunction(lib.get("CFDateGetTypeID"), ref.types.long, []), + "CFSetGetTypeID": ffi.ForeignFunction(lib.get("CFSetGetTypeID"), ref.types.long, []), + "CFDataGetBytePtr": ffi.ForeignFunction(lib.get("CFDataGetBytePtr"), ref.refType(ref.types.uint8), [CoreTypes.voidPtr]), + "CFDataGetLength": ffi.ForeignFunction(lib.get("CFDataGetLength"), ref.types.long, [CoreTypes.voidPtr]), + "CFDataCreate": ffi.ForeignFunction(lib.get("CFDataCreate"), CoreTypes.voidPtr, [CoreTypes.voidPtr, CoreTypes.voidPtr, ref.types.long]) + }; + } + + public getMobileDeviceLibrary(): {[key: string]: any} { + var mobileDeviceDll = hostInfo.isWindows() ? path.join(this.MobileDeviceDir, "MobileDevice.dll") : this.MobileDeviceDir; + var lib = ffi.DynamicLibrary(mobileDeviceDll); + + return { + "AMDeviceNotificationSubscribe": ffi.ForeignFunction(lib.get("AMDeviceNotificationSubscribe"), "uint", [CoreTypes.am_device_notification_callback, "uint", "uint", "uint", CoreTypes.ptrToVoidPtr]), + "AMDeviceConnect": ffi.ForeignFunction(lib.get("AMDeviceConnect"), "uint", [CoreTypes.am_device_p]), + "AMDeviceIsPaired": ffi.ForeignFunction(lib.get("AMDeviceIsPaired"), "uint", [CoreTypes.am_device_p]), + "AMDevicePair": ffi.ForeignFunction(lib.get("AMDevicePair"), "uint", [CoreTypes.am_device_p]), + "AMDeviceValidatePairing": ffi.ForeignFunction(lib.get("AMDeviceValidatePairing"), "uint", [CoreTypes.am_device_p]), + "AMDeviceStartSession": ffi.ForeignFunction(lib.get("AMDeviceStartSession"), "uint", [CoreTypes.am_device_p]), + "AMDeviceStopSession": ffi.ForeignFunction(lib.get("AMDeviceStopSession"), "uint", [CoreTypes.am_device_p]), + "AMDeviceDisconnect": ffi.ForeignFunction(lib.get("AMDeviceDisconnect"), "uint", [CoreTypes.am_device_p]), + "AMDeviceStartService": ffi.ForeignFunction(lib.get("AMDeviceStartService"), "uint", [CoreTypes.am_device_p, CoreTypes.cfStringRef, CoreTypes.intPtr, CoreTypes.voidPtr]), + "AMDeviceTransferApplication": ffi.ForeignFunction(lib.get("AMDeviceTransferApplication"), "uint", ["int", CoreTypes.cfStringRef, CoreTypes.cfDictionaryRef, CoreTypes.am_device_install_application_callback, CoreTypes.voidPtr]), + "AMDeviceInstallApplication": ffi.ForeignFunction(lib.get("AMDeviceInstallApplication"), "uint", ["int", CoreTypes.cfStringRef, CoreTypes.cfDictionaryRef, CoreTypes.am_device_install_application_callback, CoreTypes.voidPtr]), + "AMDeviceLookupApplications": ffi.ForeignFunction(lib.get("AMDeviceLookupApplications"), "uint", [CoreTypes.am_device_p, "uint", ref.refType(CoreTypes.cfDictionaryRef)]), + "AMDeviceUninstallApplication": ffi.ForeignFunction(lib.get("AMDeviceUninstallApplication"), "uint", ["int", CoreTypes.cfStringRef, CoreTypes.cfDictionaryRef, CoreTypes.am_device_install_application_callback, CoreTypes.voidPtr]), + "AFCConnectionOpen": ffi.ForeignFunction(lib.get("AFCConnectionOpen"), "uint", ["int", "uint", ref.refType(CoreTypes.afcConnectionRef)]), + "AFCConnectionClose": ffi.ForeignFunction(lib.get("AFCConnectionClose"), "uint", [CoreTypes.afcConnectionRef]), + "AFCDirectoryCreate": ffi.ForeignFunction(lib.get("AFCDirectoryCreate"), "uint", [CoreTypes.afcConnectionRef, "string"]), + "AFCFileRefOpen": hostInfo.isDarwin() ? ffi.ForeignFunction(lib.get("AFCFileRefOpen"), "uint", [CoreTypes.afcConnectionRef, "string", "uint", ref.refType(CoreTypes.afcFileRef)]) : ffi.ForeignFunction(lib.get("AFCFileRefOpen"), "uint", [CoreTypes.afcConnectionRef, "string", "uint", "uint", ref.refType(CoreTypes.afcFileRef)]), + "AFCFileRefClose": ffi.ForeignFunction(lib.get("AFCFileRefClose"), "uint", [CoreTypes.afcConnectionRef, CoreTypes.afcFileRef]), + "AFCFileRefWrite": ffi.ForeignFunction(lib.get("AFCFileRefWrite"), "uint", [CoreTypes.afcConnectionRef, CoreTypes.afcFileRef, CoreTypes.voidPtr, "uint"]), + "AFCFileRefRead": ffi.ForeignFunction(lib.get("AFCFileRefRead"), "uint", [CoreTypes.afcConnectionRef, CoreTypes.afcFileRef, CoreTypes.voidPtr, CoreTypes.uintPtr]), + "AFCRemovePath": ffi.ForeignFunction(lib.get("AFCRemovePath"), "uint", [CoreTypes.afcConnectionRef, "string"]), + "AFCDirectoryOpen": ffi.ForeignFunction(lib.get("AFCDirectoryOpen"), CoreTypes.afcError, [CoreTypes.afcConnectionRef, "string", ref.refType(CoreTypes.afcDirectoryRef)]), + "AFCDirectoryRead": ffi.ForeignFunction(lib.get("AFCDirectoryRead"), CoreTypes.afcError, [CoreTypes.afcConnectionRef, CoreTypes.afcDirectoryRef, ref.refType(CoreTypes.charPtr)]), + "AFCDirectoryClose": ffi.ForeignFunction(lib.get("AFCDirectoryClose"), CoreTypes.afcError, [CoreTypes.afcConnectionRef, CoreTypes.afcDirectoryRef]), + "AMDeviceCopyDeviceIdentifier": ffi.ForeignFunction(lib.get("AMDeviceCopyDeviceIdentifier"), CoreTypes.cfStringRef, [CoreTypes.am_device_p]), + "AMDeviceCopyValue": ffi.ForeignFunction(lib.get("AMDeviceCopyValue"), CoreTypes.cfStringRef, [CoreTypes.am_device_p, CoreTypes.cfStringRef, CoreTypes.cfStringRef]), + "AMDeviceNotificationUnsubscribe": ffi.ForeignFunction(lib.get("AMDeviceNotificationUnsubscribe"), CoreTypes.intType, [CoreTypes.amDeviceNotificationRef]) + }; + } + + public static getWinSocketLibrary(): {[key: string]: any} { + var winSocketDll = path.join(process.env.SystemRoot, "System32", "ws2_32.dll"); + + return ffi.Library(winSocketDll, { + "closesocket": ["int", ["uint"]], + "recv": ["int", ["uint", CoreTypes.charPtr, "int", "int"]], + "send": ["int", ["uint", "string", "int", "int"]], + "setsockopt": ["int", ["uint", "int", "int", CoreTypes.voidPtr, "int"]] + }); + } +} +$injector.register("iOSCore", IOSCore); + +export class CoreFoundation implements Mobile.ICoreFoundation { + private coreFoundationLibrary: any; + + constructor($iOSCore: Mobile.IiOSCore, + private $errors: IErrors){ + this.coreFoundationLibrary = $iOSCore.getCoreFoundationLibrary(); + } + + public runLoopRun(): void { + this.coreFoundationLibrary.CFRunLoopRun(); + } + + public runLoopGetCurrent(): any { + return this.coreFoundationLibrary.CFRunLoopGetCurrent(); + } + + public kCFRunLoopCommonModes(): NodeBuffer { + return this.coreFoundationLibrary.kCFRunLoopCommonModes.deref(); + } + + public kCFRunLoopDefaultMode(): NodeBuffer { + return this.coreFoundationLibrary.kCFRunLoopDefaultMode.deref(); + } + + public kCFTypeDictionaryValueCallBacks(): NodeBuffer { + return this.coreFoundationLibrary.kCFTypeDictionaryValueCallBacks; + } + + public kCFTypeDictionaryKeyCallBacks(): NodeBuffer { + return this.coreFoundationLibrary.kCFTypeDictionaryKeyCallBacks; + } + + public runLoopTimerCreate(allocator: NodeBuffer, fireDate: number, interval: number, flags: number, order: number, callout: NodeBuffer, context: any): NodeBuffer { + return this.coreFoundationLibrary.CFRunLoopTimerCreate(allocator, fireDate, interval, flags, order, callout, context); + } + + public absoluteTimeGetCurrent(): number { + return this.coreFoundationLibrary.CFAbsoluteTimeGetCurrent(); + } + + public runLoopAddTimer(r1: NodeBuffer, timer: NodeBuffer, mode: NodeBuffer): void { + this.coreFoundationLibrary.CFRunLoopAddTimer(r1, timer, mode); + } + + public runLoopRemoveTimer(r1: NodeBuffer, timer: NodeBuffer, mode: NodeBuffer): void { + this.coreFoundationLibrary.CFRunLoopRemoveTimer(r1, timer, mode); + } + + public runLoopStop(r1: any): void { + this.coreFoundationLibrary.CFRunLoopStop(r1); + } + + public stringGetCStringPtr(theString: NodeBuffer, encoding: number): any { + return this.coreFoundationLibrary.CFStringGetCStringPtr(theString, encoding); + } + + public stringGetLength(theString: NodeBuffer): number { + return this.coreFoundationLibrary.CFStringGetLength(theString); + } + + public stringGetCString(theString: NodeBuffer, buffer: any, bufferSize: number, encoding: number): boolean { + return this.coreFoundationLibrary.CFStringGetCString(theString, buffer, bufferSize, encoding); + } + + public stringCreateWithCString(alloc: NodeBuffer, str: string, encoding: number): NodeBuffer { + return this.coreFoundationLibrary.CFStringCreateWithCString(alloc, str, encoding); + } + + public createCFString(str: string): NodeBuffer { + return this.stringCreateWithCString(null, str, IOSCore.kCFStringEncodingUTF8 ); + } + + public dictionaryCreate(allocator: NodeBuffer, keys: NodeBuffer, values: NodeBuffer, count: number, dictionaryKeyCallbacks: NodeBuffer, dictionaryValueCallbacks: NodeBuffer): NodeBuffer { + return this.coreFoundationLibrary.CFDictionaryCreate(allocator, keys, values, count, dictionaryKeyCallbacks, dictionaryValueCallbacks); + } + + public dictionaryGetValue(theDict: NodeBuffer, value: NodeBuffer): NodeBuffer { + return this.coreFoundationLibrary.CFDictionaryGetValue(theDict, value); + } + + public dictionaryGetCount(theDict: NodeBuffer): number { + return this.coreFoundationLibrary.CFDictionaryGetCount(theDict); + } + + public dictionaryGetKeysAndValues(dictionary: NodeBuffer, keys: NodeBuffer, values: NodeBuffer): void { + this.coreFoundationLibrary.CFDictionaryGetKeysAndValues(dictionary, keys, values); + } + + public dictionaryGetTypeID(): number { + return this.coreFoundationLibrary.CFDictionaryGetTypeID(); + } + + public numberGetValue(number: NodeBuffer, theType: number, valuePtr: NodeBuffer): boolean { + return this.coreFoundationLibrary.CFNumberGetValue(number, theType, valuePtr); + } + + public getTypeID(buffer: NodeBuffer): number { + return this.coreFoundationLibrary.CFGetTypeID(buffer); + } + + public propertyListCreateData(allocator: NodeBuffer, propertyListRef: NodeBuffer , propertyListFormat: number, optionFlags: number, error: NodeBuffer): NodeBuffer { + return this.coreFoundationLibrary.CFPropertyListCreateData(allocator, propertyListRef, propertyListFormat, optionFlags, error); + } + + public propertyListCreateWithData(allocator: NodeBuffer, propertyList: NodeBuffer, optionFlags: number, propertyListFormat: NodeBuffer, error: NodeBuffer): NodeBuffer { + return this.coreFoundationLibrary.CFPropertyListCreateWithData(allocator, propertyList, optionFlags, propertyListFormat, error); + } + + public stringGetTypeID(): number { + return this.coreFoundationLibrary.CFStringGetTypeID(); + } + + public dataGetTypeID(): number { + return this.coreFoundationLibrary.CFDataGetTypeID(); + } + + public numberGetTypeID(): number { + return this.coreFoundationLibrary.CFNumberGetTypeID(); + } + + public booleanGetTypeID(): number { + return this.coreFoundationLibrary.CFBooleanGetTypeID(); + } + + public arrayGetTypeID(): number { + return this.coreFoundationLibrary.CFArrayGetTypeID(); + } + + public dateGetTypeID(): number { + return this.coreFoundationLibrary.CFDateGetTypeID(); + } + + public setGetTypeID(): number { + return this.coreFoundationLibrary.CFSetGetTypeID(); + } + + public dataGetBytePtr(buffer: NodeBuffer): NodeBuffer { + return this.coreFoundationLibrary.CFDataGetBytePtr(buffer); + } + + public dataGetLength(buffer: NodeBuffer): number { + return this.coreFoundationLibrary.CFDataGetLength(buffer); + } + + public dataCreate(allocator: NodeBuffer, data: NodeBuffer, length: number) { + return this.coreFoundationLibrary.CFDataCreate(allocator, data, length); + } + + public convertCFStringToCString(cfstr: NodeBuffer): string { + var result: string; + if (cfstr != null) { + var rawData = this.stringGetCStringPtr(cfstr, IOSCore.kCFStringEncodingUTF8); + if (ref.address(rawData) === 0) { + var cfstrLength = this.stringGetLength(cfstr); + var length = cfstrLength + 1; + var stringBuffer = new Buffer(length); + var status = this.stringGetCString(cfstr, stringBuffer, length, IOSCore.kCFStringEncodingUTF8 ); + if (status) { + result = stringBuffer.toString("utf8", 0, cfstrLength); + } else { + this.$errors.fail("Unable to convert string: ", result); + } + } else { + result = ref.readCString(rawData, 0); + } + } + + return result; + } + + private cfTypeFrom(value: {[key: string]: any}): NodeBuffer { + var keys = _.keys(value); + var values = _.values(value); + + var len = keys.length; + var keysBuffer = new Buffer(CoreTypes.pointerSize * len); + var valuesBuffer = new Buffer(CoreTypes.pointerSize * len); + + var offset = 0; + + for(var i=0; i< len; i++) { + var cfKey = this.createCFString(keys[i]); + var cfValue =this.createCFString(values[i]); + + ref.writePointer(keysBuffer, offset, cfKey); + ref.writePointer(valuesBuffer, offset, cfValue); + offset += CoreTypes.pointerSize; + } + + return this.dictionaryCreate(null, keysBuffer, valuesBuffer, len, this.kCFTypeDictionaryKeyCallBacks(), this.kCFTypeDictionaryValueCallBacks()); + } + + private cfTypeTo(value: NodeBuffer): NodeBuffer { + var typeId = this.getTypeID(value); + var retval: NodeBuffer = null; + + if(typeId === this.dataGetTypeID()) { + var len = this.dataGetLength(value); + retval = ref.reinterpret(this.dataGetBytePtr(value), len); + } + + return retval; + } + + public dictToPlistEncoding(dict: {[key: string]: {}}, format: number): NodeBuffer { + + var cfDict = this.cfTypeFrom(dict); + var cfData = this.propertyListCreateData(null, cfDict, format, 0, null); + + return this.cfTypeTo(cfData); + } + + public dictFromPlistEncoding(str: NodeBuffer): NodeBuffer { + var retval: NodeBuffer = null; + + var cfData = this.dataCreate(null, str, str.length); + if(cfData) { + var cfDict = this.propertyListCreateWithData(null, cfData, CoreTypes.kCFPropertyListImmutable, null, null); + if(cfDict) { + retval = this.cfTypeTo(cfDict); + } + } + + return retval; + } +} +$injector.register("coreFoundation", CoreFoundation); + +export class MobileDevice implements Mobile.IMobileDevice { + private mobileDeviceLibrary: any; + + constructor($iOSCore: Mobile.IiOSCore, + private $errors: IErrors) { + this.mobileDeviceLibrary = $iOSCore.getMobileDeviceLibrary(); + } + + public deviceNotificationSubscribe(notificationCallback: NodeBuffer, p1: number, p2: number, p3: number, callbackSignature: NodeBuffer): number { + return this.mobileDeviceLibrary.AMDeviceNotificationSubscribe(notificationCallback, p1, p2, p3, callbackSignature); + } + + public deviceCopyDeviceIdentifier(devicePointer: NodeBuffer): NodeBuffer { + return this.mobileDeviceLibrary.AMDeviceCopyDeviceIdentifier(devicePointer); + } + + public deviceCopyValue(devicePointer: NodeBuffer, domain: NodeBuffer, name: NodeBuffer): NodeBuffer { + return this.mobileDeviceLibrary.AMDeviceCopyValue(devicePointer, domain, name); + } + + public deviceConnect(devicePointer: NodeBuffer): number { + return this.mobileDeviceLibrary.AMDeviceConnect(devicePointer); + } + + public deviceIsPaired(devicePointer: NodeBuffer): number { + return this.mobileDeviceLibrary.AMDeviceIsPaired(devicePointer); + } + + public devicePair(devicePointer: NodeBuffer): number { + return this.mobileDeviceLibrary.AMDevicePair(devicePointer); + } + + public deviceValidatePairing(devicePointer: NodeBuffer): number { + return this.mobileDeviceLibrary.AMDeviceValidatePairing(devicePointer); + } + + public deviceStartSession(devicePointer: NodeBuffer): number { + return this.mobileDeviceLibrary.AMDeviceStartSession(devicePointer); + } + + public deviceStopSession(devicePointer: NodeBuffer): number { + return this.mobileDeviceLibrary.AMDeviceStopSession(devicePointer); + } + + public deviceDisconnect(devicePointer: NodeBuffer): number { + return this.mobileDeviceLibrary.AMDeviceDisconnect(devicePointer); + } + + public deviceStartService(devicePointer: NodeBuffer, serviceName: NodeBuffer, socketNumber: NodeBuffer): number { + return this.mobileDeviceLibrary.AMDeviceStartService(devicePointer, serviceName, socketNumber, null); + } + + public deviceTransferApplication(service: number, packageFile: NodeBuffer, options: NodeBuffer, installationCallback: NodeBuffer): number { + return this.mobileDeviceLibrary.AMDeviceTransferApplication(service, packageFile, options, installationCallback, null); + } + + public deviceInstallApplication(service: number, packageFile: NodeBuffer, options: NodeBuffer, installationCallback: NodeBuffer): number { + return this.mobileDeviceLibrary.AMDeviceInstallApplication(service, packageFile, options, installationCallback, null); + } + + public afcConnectionOpen(service: number, timeout: number, afcConnection: NodeBuffer): number { + return this.mobileDeviceLibrary.AFCConnectionOpen(service, timeout, afcConnection); + } + + public afcConnectionClose(afcConnection: NodeBuffer): number { + return this.mobileDeviceLibrary.AFCConnectionClose(afcConnection); + } + + public afcDirectoryCreate(afcConnection: NodeBuffer, path: string): number { + return this.mobileDeviceLibrary.AFCDirectoryCreate(afcConnection, path); + } + + public afcFileRefOpen(afcConnection: NodeBuffer, path: string, mode: number, afcFileRef: NodeBuffer): number { + if(hostInfo.isWindows()) { + return this.mobileDeviceLibrary.AFCFileRefOpen(afcConnection, path, mode, 0, afcFileRef); + } else if(hostInfo.isDarwin()) { + return this.mobileDeviceLibrary.AFCFileRefOpen(afcConnection, path, mode, afcFileRef); + } + } + + public afcFileRefClose(afcConnection: NodeBuffer, afcFileRef: number): number { + return this.mobileDeviceLibrary.AFCFileRefClose(afcConnection, afcFileRef); + } + + public afcFileRefWrite(afcConnection: NodeBuffer, afcFileRef: number, buffer: NodeBuffer, byteLength: number): number { + return this.mobileDeviceLibrary.AFCFileRefWrite(afcConnection, afcFileRef, buffer, byteLength); + } + + public afcFileRefRead(afcConnection: NodeBuffer, afcFileRef: number, buffer: NodeBuffer, byteLength: number): number { + return this.mobileDeviceLibrary.AFCFileRefRead(afcConnection, afcFileRef, buffer, byteLength); + } + + public afcRemovePath(afcConnection: NodeBuffer, path: string): number { + return this.mobileDeviceLibrary.AFCRemovePath(afcConnection, path); + } + + public afcDirectoryOpen(afcConnection: NodeBuffer, path: string, afcDirectory: NodeBuffer): number { + return this.mobileDeviceLibrary.AFCDirectoryOpen(afcConnection, path, afcDirectory); + } + + public afcDirectoryRead(afcConnection: NodeBuffer, afcDirectory: NodeBuffer, name: NodeBuffer): number { + return this.mobileDeviceLibrary.AFCDirectoryRead(afcConnection, afcDirectory, name); + } + + public afcDirectoryClose(afcConnection: NodeBuffer, afcDirectory: NodeBuffer): number { + return this.mobileDeviceLibrary.AFCDirectoryClose(afcConnection, afcDirectory); + } + + public isDataReceivingCompleted(reply: string): boolean { + //TODO: It should be created parser that converts data from socket to valid javascript dictionary + if(reply.indexOf("Error") >= 0) { + var openingTag = ""; + var closingTag = ""; + if(reply.indexOf(closingTag) >= 0) { + this.$errors.fail(reply.substring(reply.indexOf(openingTag) + openingTag.length, reply.indexOf(closingTag))); + } + } + + return reply.indexOf("Status") >= 0 && reply.indexOf("Complete") >= 0 && reply.indexOf("PercentComplete") < 0; + } + } +$injector.register("mobileDevice", MobileDevice); + +class WinSocket implements Mobile.IiOSDeviceSocket { + private winSocketLibrary: any = null; + private static BYTES_TO_READ = 1024; + + constructor(private service: number, + private $logger: ILogger, + private $mobileDevice: Mobile.IMobileDevice, + private $errors: IErrors) { + this.winSocketLibrary = IOSCore.getWinSocketLibrary(); + } + + private read(bytes: number): NodeBuffer { + var data = new Buffer(bytes); + var result: Number; + helpers.block(() => { + result = this.winSocketLibrary.recv(this.service, data, bytes, 0); + }); + if (result < 0) { + this.$errors.fail("Error receiving data: %s", result); + } + + return data; + } + + public readSystemLog(printData: any) { + var data = this.read(WinSocket.BYTES_TO_READ); + while (data) { + printData(data); + data = this.read(WinSocket.BYTES_TO_READ); + } + this.close(); + } + + public receiveMessage(): IFuture { + return(() => { + var reply = this.receiveMessageHelper(); + if(!this.$mobileDevice.isDataReceivingCompleted(reply)) { + reply = this.receiveMessageHelper(); + } + }).future()(); + } + + public receiveMessageHelper(): string { + var data = this.read(4); + var reply = ""; + + if (data !== null && data.length === 4) { + var l = bufferpack.unpack(">i", data)[0]; + var left = l; + while (left > 0) { + var r = this.read(left); + if (r === null) { + this.$errors.fail("Unable to read reply"); + } + reply += r; + left -= r.length; + } + } + + var result = reply.toString(); + this.$errors.verifyHeap("receiveMessage"); + return result; + } + + public sendMessage(data: {[key: string]: {}}): void { + var payload = plistlib.toString(this.createPlist(data)); + var message = bufferpack.pack(">i", [payload.length]) + payload; + var writtenBytes = this.winSocketLibrary.send(this.service, message, message.length, 0); + this.$logger.debug("WinSocket-> sending message: '%s', written bytes: '%s'", message, writtenBytes); + + this.$errors.verifyHeap("sendMessage"); + } + + private createPlist(data: {[key: string]: {}}) : {} { + var keys = _.keys(data); + var values = _.values(data); + var plist = {type: "dict", value: {}} ; + + for(var i=0; i { + var result = new Future(); + + this.socket + .on("data", (data: NodeBuffer) => { + this.$logger.debug("PosixSocket receiving: '%s'", data.toString()); + this.$errors.verifyHeap("receiveMessage"); + var reply = data.toString(); + + try { + if(this.$mobileDevice.isDataReceivingCompleted(reply)) { + result.return(); + } + } catch(e) { + result.throw(e); + } + + }) + .on("error", (error: Error) => { + result.throw(error); + }); + + return result; + } + + public readSystemLog(action: (data: NodeBuffer) => void) { + this.socket + .on("data", (data: NodeBuffer) => { + action(data); + }) + .on("end", () => { + this.close(); + this.$errors.verifyHeap("readSystemLog"); + }) + .on("error", (error: Error) => { + this.$errors.fail(error); + }); + } + + public sendMessage(message: {[key: string]: {}}, format?: number): void { + var data = this.$coreFoundation.dictToPlistEncoding(message, format); + var payload = bufferpack.pack(">i", [data.length]); + + this.$logger.trace("PlistService sending: "); + this.$logger.trace(data.toString()); + + this.socket.write(payload); + this.socket.write(data); + + this.$errors.verifyHeap("sendMessage"); + } + + public close(): void { + this.socket.destroy(); + this.$errors.verifyHeap("socket close"); + } + } + +export class PlistService implements Mobile.IiOSDeviceSocket { + private socket: Mobile.IiOSDeviceSocket = null; + + constructor(private service: number, + private format: number, + private $injector: IInjector) { + if(hostInfo.isWindows()) { + this.socket = this.$injector.resolve(WinSocket, {service: this.service}); + } else if(hostInfo.isDarwin()) { + this.socket = this.$injector.resolve(PosixSocket, {service: this.service }); + } + } + + public receiveMessage(): IFuture { + return this.socket.receiveMessage(); + } + + public readSystemLog(action: (data: NodeBuffer) => void): any { + this.socket.readSystemLog(action); + } + + public sendMessage(message: {[key: string]: {}}) : void { + this.socket.sendMessage(message, this.format); + } + + public close() { + this.socket.close(); + } +} \ No newline at end of file diff --git a/mobile/ios/ios-device.ts b/mobile/ios/ios-device.ts new file mode 100644 index 00000000..a7027eb1 --- /dev/null +++ b/mobile/ios/ios-device.ts @@ -0,0 +1,169 @@ +/// + +import ref = require("ref"); +import os = require("os"); +import iOSProxyServices = require("./ios-proxy-services"); +import Future = require("fibers/future"); +import MobileHelper = require("./../mobile-helper"); +import helpers = require("./../../helpers"); + +export class IOSDevice implements Mobile.IIOSDevice { + + private identifier: string = null; + private voidPtr = ref.refType(ref.types.void); + + constructor(private devicePointer: NodeBuffer, + private $coreFoundation: Mobile.ICoreFoundation, + private $mobileDevice: Mobile.IMobileDevice, + private $errors: IErrors, + private $logger: ILogger, + private $injector: IInjector) { } + + public getPlatform(): string { + return MobileHelper.DevicePlatforms[MobileHelper.DevicePlatforms.iOS]; + } + + public getIdentifier(): string { + if (this.identifier == null) { + this.identifier = this.$coreFoundation.convertCFStringToCString(this.$mobileDevice.deviceCopyDeviceIdentifier(this.devicePointer)); + } + + return this.identifier; + } + + public getDisplayName(): string { + return this.getValue("ProductType"); + } + + public getModel(): string { + return this.getValue("ProductType"); + } + + public getVersion(): string { + return this.getValue("ProductVersion"); + } + + public getVendor(): string { + return "Apple"; + } + + public getInstalledApplications(): IFuture { + throw new Error("Not implemented"); + } + + private getValue(value: string): string { + this.connect(); + this.startSession(); + try { + var cfValue = this.$coreFoundation.createCFString(value); + return this.$coreFoundation.convertCFStringToCString(this.$mobileDevice.deviceCopyValue(this.devicePointer, null, cfValue)); + } finally { + this.stopSession(); + this.disconnect(); + } + } + + private validateResult(result: number, error: string) { + if (result != 0) { + this.$errors.fail(error); + } + } + + private isPaired(): boolean { + return this.$mobileDevice.deviceIsPaired(this.devicePointer) != 0; + } + + private pair(): number { + var result = this.$mobileDevice.devicePair(this.devicePointer); + this.validateResult(result, "If your phone is locked with a passcode, unlock then reconnect it"); + return result; + } + + private validatePairing() : number{ + var result = this.$mobileDevice.deviceValidatePairing(this.devicePointer); + this.validateResult(result, "Unable to validate pairing"); + return result; + } + + private connect() : number { + var result = this.$mobileDevice.deviceConnect(this.devicePointer); + this.validateResult(result, "Unable to connect to device"); + + if (!this.isPaired()) { + this.pair(); + } + + return this.validatePairing(); + } + + private disconnect() { + var result = this.$mobileDevice.deviceDisconnect(this.devicePointer); + this.validateResult(result, "Unable to disconnect from device"); + } + + private startSession() { + var result = this.$mobileDevice.deviceStartSession(this.devicePointer); + this.validateResult(result, "Unable to start session"); + } + + private stopSession() { + var result = this.$mobileDevice.deviceStopSession(this.devicePointer); + this.validateResult(result, "Unable to stop session"); + } + + public startService(serviceName: string): number { + this.connect(); + try { + this.startSession(); + try { + var socket = ref.alloc("int"); + var result = this.$mobileDevice.deviceStartService(this.devicePointer, this.$coreFoundation.createCFString(serviceName), socket); + this.validateResult(result, "Unable to start service"); + return ref.deref(socket); + } finally { + this.stopSession(); + } + } finally { + this.disconnect(); + } + } + + public deploy(packageFile: string, packageName: string): IFuture { + return (() => { + var installationProxy = this.$injector.resolve(iOSProxyServices.InstallationProxyClient, {device: this }); + installationProxy.deployApplication(packageFile).wait(); + installationProxy.closeSocket(); + }).future()(); + } + + public sync(localToDevicePaths: Mobile.ILocalToDevicePathData[], appIdentifier: Mobile.IAppIdentifier, projectType: number, options: Mobile.ISyncOptions = {}): IFuture { + return(() => { + //TODO: CloseSocket must be part of afcClient. Refactor it. + var houseArrestClient: Mobile.IHouseArrestClient = this.$injector.resolve(iOSProxyServices.HouseArrestClient, {device: this}); + var afcClientForAppDocuments = houseArrestClient.getAfcClientForAppDocuments(appIdentifier.appIdentifier); + afcClientForAppDocuments.transferCollection(localToDevicePaths).wait(); + houseArrestClient.closeSocket(); + + if (!options.skipRefresh) { + var afcClientForContainer = houseArrestClient.getAfcClientForAppContainer(appIdentifier.appIdentifier); + afcClientForContainer.deleteFile("/Library/Preferences/ServerInfo.plist"); + houseArrestClient.closeSocket(); + + var notificationProxyClient = this.$injector.resolve(iOSProxyServices.NotificationProxyClient, {device: this}); + notificationProxyClient.postNotification("com.telerik.app.refreshWebView"); + notificationProxyClient.closeSocket(); + + } + + this.$logger.out("Successfully synced device with identifier '%s'", this.getIdentifier()); + + }).future()(); + } + + public openDeviceLogStream() { + var iOSSystemLog = this.$injector.resolve(iOSProxyServices.IOSSyslog, {device: this}); + iOSSystemLog.read(); + } +} + +$injector.register("iOSDevice", IOSDevice); \ No newline at end of file diff --git a/mobile/ios/ios-proxy-services.ts b/mobile/ios/ios-proxy-services.ts new file mode 100644 index 00000000..3847feea --- /dev/null +++ b/mobile/ios/ios-proxy-services.ts @@ -0,0 +1,297 @@ +/// + +import ref = require("ref"); +import ffi = require("ffi"); +import os = require("os"); +import path = require("path"); +import iOSCore = require("./ios-core"); +import Future = require("fibers/future"); +import util = require("util"); +import helpers = require("./../../helpers"); +import net = require("net"); +import MobileHelpers = require("./../mobile-helper"); + +class MobileServices { + public static APPLE_FILE_CONNECTION: string = "com.apple.afc"; + public static INSTALLATION_PROXY: string = "com.apple.mobile.installation_proxy"; + public static HOUSE_ARREST: string = "com.apple.mobile.house_arrest"; + public static NOTIFICATION_PROXY: string = "com.apple.mobile.notification_proxy"; + public static SYSLOG: string = "com.apple.syslog_relay"; +} + +export class AfcFile { + private open: boolean = false; + private afcFile: number; + + constructor(path: string, + mode: string, + private afcConnection: NodeBuffer, + private $mobileDevice: Mobile.IMobileDevice, + private $errors: IErrors) { + var modeValue = 0; + if (mode.indexOf("r") > -1) { + modeValue = 0x1; + } + if (mode.indexOf("w") > -1) { + modeValue = 0x2; + } + var afcFileRef = ref.alloc(ref.types.uint64); + this.open = false; + + var result = this.$mobileDevice.afcFileRefOpen(afcConnection, path, modeValue, afcFileRef); + if (result !== 0) { + this.$errors.fail("Unable to open file reference: '%s' with path '%s", result, path); + } + + this.afcFile = ref.deref(afcFileRef); + if (this.afcFile === 0) { + this.$errors.fail("Invalid file reference"); + } + + this.open = true; + } + + write(buffer: any, byteLength?: any): boolean { + var result = this.$mobileDevice.afcFileRefWrite(this.afcConnection, this.afcFile, buffer, byteLength); + if (result !== 0) { + this.$errors.fail("Unable to write to file: '%s'. Result is: '%s'", this.afcFile, result); + } + + return true; + } + + close() { + if (this.open) { + var result = this.$mobileDevice.afcFileRefClose(this.afcConnection, this.afcFile); + if (result !== 0) { + this.$errors.fail("Unable to close afc file connection: '%s'. Result is: '%s'", this.afcFile, result); + } + this.open = false; + } + } + + get writable(): boolean { + return true; + } +} + +export class AfcClient implements Mobile.IAfcClient { + private afcConnection: NodeBuffer = null; + + constructor(private service: number, + private $mobileDevice: Mobile.IMobileDevice, + private $fs: IFileSystem, + private $errors: IErrors, + private $logger: ILogger, + private $injector: IInjector) { + var afcConnection = ref.alloc(ref.refType(ref.types.void)); + var result = $mobileDevice.afcConnectionOpen(this.service, 0, afcConnection); + if (result !== 0) { + $errors.fail("Unable to open apple file connection: %s", result); + } + + this.afcConnection = ref.deref(afcConnection); + } + + open(path: string, mode: string) { + return this.$injector.resolve(AfcFile, {path: path, mode: mode, afcConnection: this.afcConnection}); + } + + mkdir(path: string) { + var result = this.$mobileDevice.afcDirectoryCreate(this.afcConnection, path); + if (result !== 0) { + this.$errors.fail("Unable to make directory: %s. Result is %s", path, result); + } + } + + listDir(path: string) { + var afcDirectoryRef = ref.alloc(ref.refType(ref.types.void)); + var result = this.$mobileDevice.afcDirectoryOpen(this.afcConnection, path, afcDirectoryRef); + if (result !== 0) { + this.$errors.fail("Unable to open AFC directory: '%s' %s ", path, result); + } + + var afcDirectoryValue = ref.deref(afcDirectoryRef); + var name = ref.alloc(ref.refType(ref.types.char)); + + while (this.$mobileDevice.afcDirectoryRead(this.afcConnection, afcDirectoryValue, name) === 0) { + var value = ref.deref(name); + if (ref.address(value) === 0) { + break; + } + var filePath = ref.readCString(value, 0); + if (filePath !== "." && filePath !== "..") { + console.log(filePath); + } + } + + this.$mobileDevice.afcDirectoryClose(this.afcConnection, afcDirectoryValue); + } + + public transferPackage(localFilePath: string, devicePath: string): IFuture { + return (() => { + this.transfer(localFilePath, devicePath).wait(); + }).future()(); + } + + public transferCollection(localToDevicePaths: Mobile.ILocalToDevicePathData[]): IFuture { + return (() => { + localToDevicePaths.forEach((localToDevicePathData) => { + this.transfer(localToDevicePathData.getLocalPath(), path.join("/Documents", localToDevicePathData.getRelativeToProjectBasePath())).wait(); + }); + }).future()(); + } + + public deleteFile(devicePath: string): void { + var removeResult = this.$mobileDevice.afcRemovePath(this.afcConnection, devicePath); + this.$logger.trace("Removing device file '%s', result: %s", devicePath, removeResult.toString()); + } + + private transfer(localFilePath: string, devicePath: string): IFuture { + return(() => { + this.ensureDevicePathExist(path.dirname(devicePath)); + var reader = this.$fs.createReadStream(localFilePath); + devicePath = helpers.fromWindowsRelativePathToUnix(devicePath); + + this.deleteFile(devicePath); + + var target = this.open(devicePath, "w"); + var localFilePathSize = this.$fs.getFileSize(localFilePath).wait(); + + reader.on("data", (data: NodeBuffer) => { + target.write(data, data.length); + this.$logger.trace("transfer-> localFilePath: '%s', devicePath: '%s', localFilePathSize: '%s', transferred bytes: '%s'", + localFilePath, devicePath, localFilePathSize.toString(), data.length.toString()); + }) + .on("error", (error: Error) => { + this.$errors.fail(error); + }) + .on("end", () => target.close()); + + this.$fs.futureFromEvent(reader, "close").wait(); + + }).future()(); + } + + private ensureDevicePathExist(deviceDirPath: string): void { + var filePathParts = deviceDirPath.split(path.sep); + var currentDevicePath = ""; + + filePathParts.forEach((filePathPart: string) => { + if (filePathPart !== "") { + currentDevicePath = helpers.fromWindowsRelativePathToUnix(path.join(currentDevicePath, filePathPart)); + this.mkdir(currentDevicePath); + } + }); + } +} + +export class InstallationProxyClient { + private plistService: Mobile.IiOSDeviceSocket = null; + + constructor(private device: Mobile.IIOSDevice, + private $logger: ILogger, + private $injector: IInjector) { } + + public deployApplication(packageFile: string) : IFuture { + return(() => { + var service = this.device.startService(MobileServices.APPLE_FILE_CONNECTION); + var afcClient = this.$injector.resolve(AfcClient, {service: service}); + var devicePath = path.join("PublicStaging", path.basename(packageFile)); + + afcClient.transferPackage(packageFile, devicePath).wait(); + this.plistService = this.$injector.resolve(iOSCore.PlistService, {service: this.device.startService(MobileServices.INSTALLATION_PROXY), format: iOSCore.CoreTypes.kCFPropertyListBinaryFormat_v1_0}); + + this.plistService.sendMessage({ + Command: "Install", + "PackagePath": helpers.fromWindowsRelativePathToUnix(devicePath) + }); + this.plistService.receiveMessage().wait(); + this.$logger.info("Successfully deployed on device %s", this.device.getIdentifier()); + }).future()(); + } + + public closeSocket() { + return this.plistService.close(); + } +} +$injector.register("installationProxyClient", InstallationProxyClient); + +export class NotificationProxyClient { + private plistService: Mobile.IiOSDeviceSocket = null; + + constructor(private device: Mobile.IIOSDevice, + private $injector: IInjector) { } + + postNotification(notificationName: string) { + this.plistService = this.$injector.resolve(iOSCore.PlistService, {service: this.device.startService(MobileServices.NOTIFICATION_PROXY), format: iOSCore.CoreTypes.kCFPropertyListBinaryFormat_v1_0}); + + var result = this.plistService.sendMessage({ + "Command": "PostNotification", + "Name": notificationName, + "ClientOptions": "" + }); + + return result; + } + + public closeSocket() { + this.plistService.close(); + } +} + +export class HouseArrestClient implements Mobile.IHouseArrestClient { + private plistService: Mobile.IiOSDeviceSocket = null; + + constructor(private device: Mobile.IIOSDevice, + private $injector: IInjector) { + } + + private getAfcClientCore(command: string, applicationIdentifier: string): Mobile.IAfcClient { + var service = this.device.startService(MobileServices.HOUSE_ARREST); + this.plistService = this.$injector.resolve(iOSCore.PlistService, {service: service, format: iOSCore.CoreTypes.kCFPropertyListXMLFormat_v1_0}); + + this.plistService.sendMessage({ + "Command": command, + "Identifier": applicationIdentifier + }); + + this.plistService.receiveMessage().wait(); + + return this.$injector.resolve(AfcClient, {service: service}); + } + + public getAfcClientForAppDocuments(applicationIdentifier: string): Mobile.IAfcClient { + return this.getAfcClientCore("VendDocuments", applicationIdentifier); + } + + public getAfcClientForAppContainer(applicationIdentifier: string): Mobile.IAfcClient { + return this.getAfcClientCore("VendContainer", applicationIdentifier); + } + + public closeSocket() { + this.plistService.close(); + } +} + +export class IOSSyslog { + private plistService: Mobile.IiOSDeviceSocket; + private matchRegex = new RegExp(".*?((Cordova.{3}|AppBuilder)\\[\\d+\\] : )", 'i'); + + constructor(private device: Mobile.IIOSDevice, + private $logger: ILogger, + private $injector: IInjector) { + this.plistService = this.$injector.resolve(iOSCore.PlistService, {service: this.device.startService(MobileServices.SYSLOG), format: undefined}); + } + + public read(): void { + var printData = (data: NodeBuffer) => { + var output = ref.readCString(data, 0); + if(this.matchRegex.test(output)) { + this.$logger.out(output); + } + }; + + this.plistService.readSystemLog(printData); + } +} \ No newline at end of file diff --git a/mobile/mobile-core/device-discovery.ts b/mobile/mobile-core/device-discovery.ts new file mode 100644 index 00000000..c18ace77 --- /dev/null +++ b/mobile/mobile-core/device-discovery.ts @@ -0,0 +1,260 @@ +/// + +import ref = require("ref"); +import util = require("util"); +import os = require("os"); +import path = require("path"); +import IOSDevice = require("./../ios/ios-device"); +import AndroidDevice = require("./../android/android-device"); +import CoreTypes = require("./../ios/ios-core"); +import Signal = require("./../../events/signal"); +import Future = require("fibers/future"); +import child_process = require("child_process"); +import helpers = require("./../../helpers"); +import hostInfo = require("../../host-info"); +var options = require("./../../options"); + +export class DeviceDiscovery implements Mobile.IDeviceDiscovery { + private devices: {[key: string]: Mobile.IDevice} = {}; + + public deviceFound :ISignal= null; + public deviceLost: ISignal = null; + + constructor() { + this.deviceFound = new Signal.Signal(); + this.deviceLost = new Signal.Signal(); + } + + public addDevice(device: Mobile.IDevice) { + this.devices[device.getIdentifier()] = device; + this.raiseOnDeviceFound(device); + } + + public removeDevice(deviceIdentifier: string) { + var device = this.devices[deviceIdentifier]; + if(!device) { + return; + } + delete this.devices[deviceIdentifier]; + this.raiseOnDeviceLost(device); + } + + public startLookingForDevices(): IFuture { + return undefined; + } + + private raiseOnDeviceFound(device: Mobile.IDevice) { + this.deviceFound.dispatch(device); + } + + private raiseOnDeviceLost(device: Mobile.IDevice) { + this.deviceLost.dispatch(device); + } +} +$injector.register("deviceDiscovery", DeviceDiscovery); + +class IOSDeviceDiscovery extends DeviceDiscovery { + + private static ADNCI_MSG_CONNECTED = 1; + private static ADNCI_MSG_DISCONNECTED = 2; + private static APPLE_SERVICE_NOT_STARTED_ERROR_CODE = 0xE8000063; + + private timerCallbackPtr: NodeBuffer = null; + private notificationCallbackPtr: NodeBuffer = null; + + constructor(private $coreFoundation: Mobile.ICoreFoundation, + private $mobileDevice: Mobile.IMobileDevice, + private $errors: IErrors, + private $injector: IInjector) { + super(); + this.timerCallbackPtr = CoreTypes.CoreTypes.cf_run_loop_timer_callback.toPointer(IOSDeviceDiscovery.timerCallback); + this.notificationCallbackPtr = CoreTypes.CoreTypes.am_device_notification_callback.toPointer(IOSDeviceDiscovery.deviceNotificationCallback); + } + + public startLookingForDevices(): IFuture { + return (() => { + this.subscribeForNotifications(); + var defaultTimeoutInSeconds = options.timeout ? parseInt(options.timeout, 10)/1000 : 1; + this.startRunLoopWithTimer(defaultTimeoutInSeconds); + }).future()(); + } + + private static deviceNotificationCallback(devicePointer?: NodeBuffer, user?: number) : any { + var iOSDeviceDiscovery = $injector.resolve("iOSDeviceDiscovery"); + var deviceInfo = ref.deref(devicePointer); + + if(deviceInfo.msg === IOSDeviceDiscovery.ADNCI_MSG_CONNECTED) { + iOSDeviceDiscovery.createAndAddDevice(deviceInfo.dev); + } + else if(deviceInfo.msg === IOSDeviceDiscovery.ADNCI_MSG_DISCONNECTED) { + var deviceIdentifier = iOSDeviceDiscovery.$coreFoundation.convertCFStringToCString(iOSDeviceDiscovery.$mobileDevice.deviceCopyDeviceIdentifier(deviceInfo.dev)); + iOSDeviceDiscovery.removeDevice(deviceIdentifier); + } + } + + private static timerCallback(): void { + var iOSDeviceDiscovery = $injector.resolve("iOSDeviceDiscovery"); + iOSDeviceDiscovery.$coreFoundation.runLoopStop(iOSDeviceDiscovery.$coreFoundation.runLoopGetCurrent()); + } + + private validateResult(result: number, error: string) { + if(result != 0) { + this.$errors.fail(error); + } + } + + private subscribeForNotifications() { + var notifyFunction = ref.alloc(CoreTypes.CoreTypes.amDeviceNotificationRef); + + var result = this.$mobileDevice.deviceNotificationSubscribe(this.notificationCallbackPtr, 0, 0, 0, notifyFunction); + var error = IOSDeviceDiscovery.APPLE_SERVICE_NOT_STARTED_ERROR_CODE ? + "Cannot run and complete operations on iOS devices because Apple Mobile Device Service is not started. Verify that iTunes is installed and running on your system." : "Unable to subscribe for notifications"; + this.validateResult(result, error); + this.$errors.verifyHeap("subscribeForNotifications"); + } + + private startRunLoopWithTimer(timeout: number): void { + var kCFRunLoopDefaultMode = this.$coreFoundation.kCFRunLoopDefaultMode(); + var timer: NodeBuffer = null; + + if(timeout > 0) { + var currentTime = this.$coreFoundation.absoluteTimeGetCurrent() + timeout; + timer = this.$coreFoundation.runLoopTimerCreate(null, currentTime , 0, 0, 0, this.timerCallbackPtr, null); + this.$coreFoundation.runLoopAddTimer(this.$coreFoundation.runLoopGetCurrent(), timer, kCFRunLoopDefaultMode); + } + + this.$coreFoundation.runLoopRun(); + + if(timeout > 0) { + this.$coreFoundation.runLoopRemoveTimer(this.$coreFoundation.runLoopGetCurrent(), timer, kCFRunLoopDefaultMode); + } + + this.$errors.verifyHeap("startRunLoopWithTimer"); + } + + private createAndAddDevice(devicePointer: NodeBuffer): void { + var device = this.$injector.resolve(IOSDevice.IOSDevice, {devicePointer: devicePointer}); + this.addDevice(device); + } +} + +class IOSDeviceDiscoveryStub extends DeviceDiscovery { + constructor(private $logger: ILogger, + private error: string) { + super(); + } + + public startLookingForDevices(): IFuture { + this.$logger.warn(this.error); + return Future.fromResult(); + } +} + +class ITunesValidator { + private static NOT_INSTALLED_iTUNES_ERROR_MESSAGE = "iTunes is not installed. Install it on your system and run this command again."; + + constructor(private $fs: IFileSystem) { } + + public getError(): IFuture { + return (() => { + if(hostInfo.isWindows64()) { + if(process.arch === "x64") { + return "To be able to run operations on connected iOS devices, install the 32-bit version of Node.js."; + } + } + + var coreFoundationDir = ""; + var mobileDeviceDir = ""; + + if(hostInfo.isWindows()) { + var commonProgramFiles = hostInfo.isWindows64() ? process.env["CommonProgramFiles(x86)"] : process.env.CommonProgramFiles; + coreFoundationDir = path.join(commonProgramFiles, "Apple", "Apple Application Support"); + mobileDeviceDir = path.join(commonProgramFiles, "Apple", "Mobile Device Support"); + } else if(hostInfo.isDarwin()) { + coreFoundationDir = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"; + mobileDeviceDir = "/System/Library/PrivateFrameworks/MobileDevice.framework/MobileDevice"; + } + + var existsCoreFoundation = this.$fs.exists(coreFoundationDir).wait(); + var existsMobileDevice = this.$fs.exists(mobileDeviceDir).wait(); + + if(!existsCoreFoundation || !existsMobileDevice) { + return ITunesValidator.NOT_INSTALLED_iTUNES_ERROR_MESSAGE; + } + + return null; + + }).future()(); + } +} + +$injector.register("iOSDeviceDiscovery", ($errors: IErrors, $logger: ILogger, $fs: IFileSystem, $injector: IInjector) => { + var iTunesValidator = new ITunesValidator($fs); + var error = iTunesValidator.getError().wait(); + var result: Mobile.IDeviceDiscovery = null; + + if(error) { + result = new IOSDeviceDiscoveryStub($logger, error); + } else { + result = $injector.resolve(IOSDeviceDiscovery); + } + + return result; +}); + +export class AndroidDeviceDiscovery extends DeviceDiscovery { + private static adb: string; + + constructor(private $childProcess: IChildProcess, + private $injector: IInjector, + private $staticConfig: IStaticConfig){ + super(); + } + + private get Adb() { + if (!AndroidDeviceDiscovery.adb) { + AndroidDeviceDiscovery.adb = this.$staticConfig.adbFilePath; + } + + return AndroidDeviceDiscovery.adb; + } + + private createAndAddDevice(deviceIdentifier: string): IFuture { + return (() => { + var device = this.$injector.resolve(AndroidDevice.AndroidDevice, { + identifier: deviceIdentifier, adb: this.Adb + }); + this.addDevice(device); + }).future()(); + } + + public startLookingForDevices(): IFuture { + return(()=> { + this.ensureAdbServerStarted().wait(); + + var requestAllDevicesCommand = util.format("%s devices", this.Adb); + var result = this.$childProcess.exec(requestAllDevicesCommand).wait(); + + var devices = result.toString().split(os.EOL).slice(1) + .filter( (element: string) => { + return element && !element.isEmpty(); + }) + .map((element: string) => { + // http://developer.android.com/tools/help/adb.html#devicestatus + var parts = element.split("\t"); + var identifier = parts[0]; + var state = parts[1]; + if (state === "device"/*ready*/) { + this.createAndAddDevice(identifier).wait(); + } + }); + }).future()(); + } + + private ensureAdbServerStarted(): IFuture { + var startAdbServerCommand = util.format("%s start-server", this.Adb); + return this.$childProcess.exec(startAdbServerCommand); + } +} +$injector.register("androidDeviceDiscovery", AndroidDeviceDiscovery); + diff --git a/mobile/mobile-core/devices-services.ts b/mobile/mobile-core/devices-services.ts new file mode 100644 index 00000000..4366b2ea --- /dev/null +++ b/mobile/mobile-core/devices-services.ts @@ -0,0 +1,252 @@ +/// + +import Signal = require("./../../events/signal"); +import util = require("util"); +import Future = require("fibers/future"); +import MobileHelper = require("./../mobile-helper"); +import helpers = require("./../../helpers"); +var assert = require("assert"); +import constants = require("../constants"); + +export class DevicesServices implements Mobile.IDevicesServices { + private devices: { [key: string]: Mobile.IDevice } = {}; + private platforms: string[] = []; + private static NOT_FOUND_DEVICE_BY_IDENTIFIER_ERROR_MESSAGE = "Could not find device by specified identifier '%s'. To list currently connected devices and verify that the specified identifier exists, run 'appbuilder device'."; + private static NOT_FOUND_DEVICE_BY_INDEX_ERROR_MESSAGE = "Could not find device by specified index %d. To list currently connected devices and verify that the specified index exists, run 'appbuilder device'."; + private _platform: string; + private _device: Mobile.IDevice; + private _isInitialized = false; + + constructor(private $logger: ILogger, + private $errors: IErrors, + private $iOSDeviceDiscovery: Mobile.IDeviceDiscovery, + private $androidDeviceDiscovery: Mobile.IDeviceDiscovery) { + this.attachToDeviceDiscoveryEvents(); + } + + public get platform(): string { + return this._platform; + } + + public get deviceCount(): number { + return this._device ? 1 : this.getDevices().length; + } + + private getDevices(): Mobile.IDevice[] { + return _.values(this.devices); + } + + private getAllPlatforms(): Array { + if(this.platforms.length > 0) { + return this.platforms; + } + + var devicePlatforms = MobileHelper.DevicePlatforms; + for (var platform in devicePlatforms) { + if(typeof devicePlatforms[platform] === "number") { + var platformCapabilities = MobileHelper.platformCapabilities[platform]; + if (platformCapabilities.cableDeploy) { + this.platforms.push(platform); + } + } + } + + return this.platforms; + } + + private getPlatform(platform: string): string { + var allSupportedPlatforms = this.getAllPlatforms(); + var normalizedPlatform = MobileHelper.validatePlatformName(platform, this.$errors) + if(!_.contains(allSupportedPlatforms, normalizedPlatform)) { + this.$errors.fail("Deploying to %s connected devices is not supported. Build the " + + "app using the `build` command and deploy the package manually.", normalizedPlatform); + } + + return normalizedPlatform; + } + + attachToDeviceDiscoveryEvents() { + this.$iOSDeviceDiscovery.deviceFound.add(this.onDeviceFound, this); + this.$iOSDeviceDiscovery.deviceLost.add(this.onDeviceLost, this); + + this.$androidDeviceDiscovery.deviceFound.add(this.onDeviceFound, this); + this.$androidDeviceDiscovery.deviceLost.add(this.onDeviceLost, this); + } + + private onDeviceFound(device: Mobile.IDevice): void { + this.$logger.trace("Found device with identifier '%s'", device.getIdentifier()); + this.devices[device.getIdentifier()] = device; + } + + private onDeviceLost(device: Mobile.IDevice): void { + this.$logger.trace("Lost device with identifier '%s'", device.getIdentifier()); + delete this.devices[device.getIdentifier()]; + } + + private startLookingForDevices(): IFuture { + return (() => { + this.$logger.trace("startLookingForDevices; platform is %s", this._platform); + if(!this._platform) { + this.$iOSDeviceDiscovery.startLookingForDevices().wait(); + this.$androidDeviceDiscovery.startLookingForDevices().wait(); + } else if(MobileHelper.isiOSPlatform(this._platform)) { + this.$iOSDeviceDiscovery.startLookingForDevices().wait(); + } else if(MobileHelper.isAndroidPlatform(this._platform)) { + this.$androidDeviceDiscovery.startLookingForDevices().wait(); + } + }).future()(); + } + + private getAllConnectedDevices(): Mobile.IDevice[] { + if(!this._platform) { + return this.getDevices(); + } else { + return this.filterDevicesByPlatform(); + } + } + + private getDeviceByIndex(index: number): Mobile.IDevice { + this.validateIndex(index-1); + return this.getDevices()[index-1]; + } + + private getDeviceByIdentifier(identifier: string): Mobile.IDevice { + var searchedDevice = _.find(this.getDevices(), (device: Mobile.IDevice) => { return device.getIdentifier() === identifier; }); + if(!searchedDevice) { + this.$errors.fail(DevicesServices.NOT_FOUND_DEVICE_BY_IDENTIFIER_ERROR_MESSAGE, identifier); + } + + return searchedDevice; + } + + private getDevice(deviceOption: string): IFuture { + return (() => { + this.startLookingForDevices().wait(); + var device: Mobile.IDevice = null; + + if(this.hasDevice(deviceOption)) { + device = this.getDeviceByIdentifier(deviceOption); + } else if(helpers.isNumber(deviceOption)) { + device = this.getDeviceByIndex(parseInt(deviceOption, 10)); + } + + if(!device) { + this.$errors.fail("Cannot resolve the specified connected device by the provided index or identifier. To list currently connected devices and verify that the specified index or identifier exists, run 'appbuilder device'."); + } + + return device; + }).future()(); + } + + private executeOnDevice(action: (dev: Mobile.IDevice) => IFuture, canExecute?: (dev: Mobile.IDevice) => boolean): IFuture { + return ((): void => { + if(!canExecute || canExecute(this._device)) { + action(this._device).wait(); + } + }).future()(); + } + + private executeOnAllConnectedDevices(action: (dev: Mobile.IDevice) => IFuture, canExecute?: (dev: Mobile.IDevice) => boolean): IFuture { + return ((): void => { + var allConnectedDevices = this.getAllConnectedDevices(); + var futures = _.map(allConnectedDevices, (device: Mobile.IDevice) => { + if (!canExecute || canExecute(device)) { + var future = action(device); + Future.settle(future); + return future; + } else { + return Future.fromResult(); + } + }); + + Future.wait(futures); //SAFE: all futures settled serially by the above Future.settle call + }).future()(); + } + + public execute(action: (device: Mobile.IDevice) => IFuture, canExecute?: (dev: Mobile.IDevice) => boolean, options?: {[key: string]: boolean}): IFuture { + return ((): void => { + assert.ok(this._isInitialized, "Devices services not initialized!"); + if(this.hasDevices) { + if(this._device) { + this.executeOnDevice(action, canExecute).wait(); + } else { + this.executeOnAllConnectedDevices(action, canExecute).wait(); + } + } else { + var message = constants.ERROR_NO_DEVICES; + if(options && options["allowNoDevices"]) { + this.$logger.info(message); + } else { + this.$errors.fail({formatStr: message, suppressCommandHelp: true}); + } + } + }).future()(); + } + + public initialize(platform: string, deviceOption?: string, options?: Mobile.IDevicesServicesInitializationOptions): IFuture { + options = options || {}; + if (this._isInitialized) { + return Future.fromResult(); + } + return(() => { + if(platform && deviceOption) { + this._device = this.getDevice(deviceOption).wait(); + this._platform = this._device.getPlatform(); + if(this._platform !== this.getPlatform(platform)) { + this.$errors.fail("Cannot resolve the specified connected device. The provided platform does not match the provided index or identifier." + + "To list currently connected devices and verify that the specified pair of platform and index or identifier exists, run 'device'."); + } + this.$logger.warn("Your application will be deployed only on the device specified by the provided index or identifier."); + } else if(!platform && deviceOption) { + this._device = this.getDevice(deviceOption).wait(); + this._platform = this._device.getPlatform(); + } else if(platform && !deviceOption) { + this._platform = this.getPlatform(platform); + this.startLookingForDevices().wait(); + } else if(!platform && !deviceOption) { + this.startLookingForDevices().wait(); + + if (!options.skipInferPlatform) { + var devices = this.getDevices(); + var platforms = _.uniq(_.map(devices, (device) => device.getPlatform())); + + if (platforms.length === 1) { + this._platform = platforms[0]; + } else { + if (platforms.length === 0) { + this.$errors.fail({formatStr: constants.ERROR_NO_DEVICES, suppressCommandHelp: true}); + } else { + this.$errors.fail("Multiple device platforms detected (%s). Specify platform or device on command line.", + helpers.formatListOfNames(platforms, "and")); + } + } + } + } + this._isInitialized = true; + }).future()(); + } + + public get hasDevices(): boolean { + if (!this._platform) { + return this.getDevices().length !== 0; + } else { + return this.filterDevicesByPlatform().length !== 0; + } + } + + private hasDevice(identifier: string): boolean { + return _.some(this.getDevices(), (device: Mobile.IDevice) => { return device.getIdentifier() === identifier }); + } + + private filterDevicesByPlatform(): Mobile.IDevice[] { + return _.filter(this.getDevices(), (device: Mobile.IDevice) => { return device.getPlatform() === this._platform; }); + } + + private validateIndex(index: number): void { + if (index < 0 || index > this.getDevices().length) { + throw new Error(util.format(DevicesServices.NOT_FOUND_DEVICE_BY_INDEX_ERROR_MESSAGE, index)); + } + } +} + +$injector.register("devicesServices", DevicesServices); diff --git a/mobile/mobile-helper.ts b/mobile/mobile-helper.ts new file mode 100644 index 00000000..e8a11964 --- /dev/null +++ b/mobile/mobile-helper.ts @@ -0,0 +1,90 @@ +/// +"use strict"; + +import helpers = require("../helpers"); + +export enum DevicePlatforms { + iOS, + Android, + WP8 +} + +export var platformCapabilities: {[key: string]: Mobile.IPlatformCapabilities } = { + iOS: { + wirelessDeploy: true, + cableDeploy: true, + companion: true, + publishTelerikAppManager: true, + hostPlatformsForDeploy: ["win32", "darwin"] + }, + Android: { + wirelessDeploy: true, + cableDeploy: true, + companion: true, + publishTelerikAppManager: true, + hostPlatformsForDeploy: ["win32", "darwin", "linux"] + }, + WP8: { + wirelessDeploy: true, + cableDeploy: false, + companion: false, + publishTelerikAppManager: false, + hostPlatformsForDeploy: ["win32"] + } +}; + +export var PlatformNames = Object.keys(platformCapabilities); + +export class LocalToDevicePathData implements Mobile.ILocalToDevicePathData { + constructor(private localPath: string, private devicePath: string, private relativeToProjectBasePath: string) {} + + getLocalPath(): string { return this.localPath; } + getDevicePath(): string { return this.devicePath; } + getRelativeToProjectBasePath(): string { return this.relativeToProjectBasePath; } +} + +export function isAndroidPlatform(platform: string): boolean { + return DevicePlatforms[DevicePlatforms.Android].toLowerCase() === platform.toLowerCase(); +} + +export function isiOSPlatform(platform:string): boolean { + return DevicePlatforms[DevicePlatforms.iOS].toLowerCase() === platform.toLowerCase(); +} + +export function isWP8Platform(platform: string): boolean { + return DevicePlatforms[DevicePlatforms.WP8].toLowerCase() === platform.toLowerCase(); +} + +export function normalizePlatformName(platform: string): string { + if (isAndroidPlatform(platform)) { + return "Android"; + } else if (isiOSPlatform(platform)) { + return "iOS"; + } else if (isWP8Platform(platform)) { + return "WP8"; + } + + return undefined; +} + +export function isPlatformSupported(platform: string): boolean { + var platformName = normalizePlatformName(platform); + return _.contains(platformCapabilities[platformName].hostPlatformsForDeploy, process.platform); +} + +export function generateWP8GUID(): string { + return "{" + require("node-uuid").v4() + "}"; +} + +export function validatePlatformName(platform: string, $errors: IErrors): string { + if (!platform) { + $errors.fail("No device platform specified."); + } + + var normalizedPlatform = normalizePlatformName(platform); + if (!normalizedPlatform) { + $errors.fail("'%s' is not a valid device platform. Valid platforms are %s.", + platform, helpers.formatListOfNames(Object.keys(platformCapabilities))); + } + return normalizedPlatform; +}