<commit_before>//
//  Bridge.swift
//  THGBridge
//
//  Created by <NAME> on 3/25/15.
//  Copyright (c) 2015 TheHolyGrail. All rights reserved.
//

import Foundation
import JavaScriptCore
import THGFoundation
import THGLog

public enum THGBridgeError: Int, NSErrorEnum {
    case FileDoesNotExist
    case FailedToDownloadScript
    case FailedToEvaluateScript

    public var domain: String {
        return "io.theholygrail.THGBridgeError"
    }

    public var errorDescription: String {
        switch self {
        case .FileDoesNotExist:
            return "File does not exist."
        case .FailedToDownloadScript:
            return "Failed to download script."
        case .FailedToEvaluateScript:
            return "Failed to evaluate script."
        }
    }
}

@objc(THGBridge)
public class Bridge {

    public var context: JSContext {
        didSet {
            for (name, script) in exports {
                
                println("add \(name) \(script)")
                
                context.setObject(script, forKeyedSubscript: name)
            }
            
            context.exceptionHandler = { context, exception in
                log(.Debug, "JSError = \(exception)")
            }
        }
    }

    private(set) public var exports = [String: JSExport]()

    public init() {
        context = JSContext(virtualMachine: JSVirtualMachine())
    }

    public func loadFromFile(filePath: String, error: NSErrorPointer = nil) {
        let filemanager = NSFileManager.defaultManager()
        if filemanager.fileExistsAtPath(filePath) {
            if let script = String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: error) {
                var loadError: NSError? = nil
                self.load(script, error: &loadError)
                if let loadError = loadError {
                    error.memory = loadError
                }
            }
        } else {
            if (error != nil) {
                error.memory = NSError(THGBridgeError.FileDoesNotExist)
            }
        }
    }

    public func loadFromURL(downloadURL: NSURL, completion: (error: NSError?) -> Void) {
        downloadScript(downloadURL) { (data, error) -> Void in
            if let error = error {
                completion(error: error)
            } else {
                if let data = data, let script = NSString(data: data, encoding: NSUTF8StringEncoding) as String? {
                    var error: NSError? = nil
                    self.load(script, error: &error)
                    completion(error: error)
                } else {
                    completion(error: NSError(THGBridgeError.FailedToDownloadScript))
                }
            }
        }
    }

    public func load(script: String, error: NSErrorPointer = nil) {
        let value = context.evaluateScript(script)
        /*if value.isUndefined() {
            let anError = NSError(THGBridgeError.FailedToEvaluateScript)
            error.memory = anError
        }*/
    }

    private func downloadScript(url: NSURL, completion: (data: NSData?, error: NSError?) -> Void)
    {
        let downloadTask = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
            let httpResponse = response as? NSHTTPURLResponse
            if httpResponse?.statusCode == 404 {
                completion(data: nil, error: NSError(THGBridgeError.FileDoesNotExist))
            } else {
                completion(data: data, error: error)
            }
        }

        downloadTask.resume()
    }
}

// MARK: - Exports API

extension Bridge {
    /**
    Add an exported object to the context
    :param: export Object being exported to JavaScript
    :param: name Name of object being exported
    */
    public func addExport(export: JSExport, name: String) {
        exports[name] = export
        context.setObject(export, forKeyedSubscript: name)
    }
    
    /**
    Retrieve a JSValue out of the context by name.
    :param: name Name of value to retrieve out of context.
    */
    public func contextValueForName(name: String) -> JSValue {
        return context.objectForKeyedSubscript(name)
    }
}
<commit_msg>Added support for using code-only, NOFRAMEWORKS flag.<commit_after>//
//  Bridge.swift
//  THGBridge
//
//  Created by <NAME> on 3/25/15.
//  Copyright (c) 2015 TheHolyGrail. All rights reserved.
//

import Foundation
import JavaScriptCore
#if NOFRAMEWORKS
#else
import THGFoundation
import THGLog
#endif

public enum THGBridgeError: Int, NSErrorEnum {
    case FileDoesNotExist
    case FailedToDownloadScript
    case FailedToEvaluateScript

    public var domain: String {
        return "io.theholygrail.THGBridgeError"
    }

    public var errorDescription: String {
        switch self {
        case .FileDoesNotExist:
            return "File does not exist."
        case .FailedToDownloadScript:
            return "Failed to download script."
        case .FailedToEvaluateScript:
            return "Failed to evaluate script."
        }
    }
}

@objc(THGBridge)
public class Bridge {

    public var context: JSContext {
        didSet {
            for (name, script) in exports {
                
                println("add \(name) \(script)")
                
                context.setObject(script, forKeyedSubscript: name)
            }
            
            context.exceptionHandler = { context, exception in
                log(.Debug, "JSError = \(exception)")
            }
        }
    }

    private(set) public var exports = [String: JSExport]()

    public init() {
        context = JSContext(virtualMachine: JSVirtualMachine())
    }

    public func loadFromFile(filePath: String, error: NSErrorPointer = nil) {
        let filemanager = NSFileManager.defaultManager()
        if filemanager.fileExistsAtPath(filePath) {
            if let script = String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: error) {
                var loadError: NSError? = nil
                self.load(script, error: &loadError)
                if let loadError = loadError {
                    error.memory = loadError
                }
            }
        } else {
            if (error != nil) {
                error.memory = NSError(THGBridgeError.FileDoesNotExist)
            }
        }
    }

    public func loadFromURL(downloadURL: NSURL, completion: (error: NSError?) -> Void) {
        downloadScript(downloadURL) { (data, error) -> Void in
            if let error = error {
                completion(error: error)
            } else {
                if let data = data, let script = NSString(data: data, encoding: NSUTF8StringEncoding) as String? {
                    var error: NSError? = nil
                    self.load(script, error: &error)
                    completion(error: error)
                } else {
                    completion(error: NSError(THGBridgeError.FailedToDownloadScript))
                }
            }
        }
    }

    public func load(script: String, error: NSErrorPointer = nil) {
        let value = context.evaluateScript(script)
        /*if value.isUndefined() {
            let anError = NSError(THGBridgeError.FailedToEvaluateScript)
            error.memory = anError
        }*/
    }

    private func downloadScript(url: NSURL, completion: (data: NSData?, error: NSError?) -> Void)
    {
        let downloadTask = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
            let httpResponse = response as? NSHTTPURLResponse
            if httpResponse?.statusCode == 404 {
                completion(data: nil, error: NSError(THGBridgeError.FileDoesNotExist))
            } else {
                completion(data: data, error: error)
            }
        }

        downloadTask.resume()
    }
}

// MARK: - Exports API

extension Bridge {
    /**
    Add an exported object to the context
    :param: export Object being exported to JavaScript
    :param: name Name of object being exported
    */
    public func addExport(export: JSExport, name: String) {
        exports[name] = export
        context.setObject(export, forKeyedSubscript: name)
    }
    
    /**
    Retrieve a JSValue out of the context by name.
    :param: name Name of value to retrieve out of context.
    */
    public func contextValueForName(name: String) -> JSValue {
        return context.objectForKeyedSubscript(name)
    }
}

{'fraction_non_alphanumeric': 0.08806818181818182, 'fraction_numerical': 0.0033143939393939395, 'mean_word_length': 1.920497753197373, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5145295', 'n_tokens_mistral': 2376, 'n_tokens_neox': 2241, 'n_words': 620}