entities
listlengths
1
8.61k
max_stars_repo_path
stringlengths
7
172
max_stars_repo_name
stringlengths
5
89
max_stars_count
int64
0
82k
content
stringlengths
14
1.05M
id
stringlengths
2
6
new_content
stringlengths
15
1.05M
modified
bool
1 class
references
stringlengths
29
1.05M
[ { "context": "# Author: Josh Bass\n\nmathjs = require(\"mathjs\");\nReact = require(\"rea", "end": 19, "score": 0.9998822808265686, "start": 10, "tag": "NAME", "value": "Josh Bass" } ]
src/client/components/customers/CustomerEdit.coffee
jbass86/Aroma
0
# Author: Josh Bass mathjs = require("mathjs"); React = require("react"); DatePicker = require("react-datepicker"); Moment = require("moment"); module.exports = React.createClass getInitialState: -> @default_state = {_id: undefined, first_name: "", middle_name: "", last_name: "", address: "", \ email: "", phone_number: "", social_media: "", birthday: undefined, \ customer_alert: "", customer_success: false, update_from_props: true}; componentDidMount: -> @checkInitialState(); componentWillUnmount: -> if (@reset_default_timeout) window.clearTimeout(@reset_default_timeout); @reset_default_timeout = undefined; componentDidUpdate: -> @checkInitialState(); checkInitialState: -> if (@props.initialState and @state.update_from_props) first_name = if @props.initialState.first_name then @props.initialState.first_name else @default_state.first_name; middle_name = if @props.initialState.middle_name then @props.initialState.middle_name else @default_state.middle_name; last_name = if @props.initialState.last_name then @props.initialState.last_name else @default_state.last_name; address = if @props.initialState.address then @props.initialState.address else @default_state.address; email = if @props.initialState.email then @props.initialState.email else @default_state.email; phone_number = if @props.initialState.phone_number then @props.initialState.phone_number else @default_state.phone_number; social_media = if @props.initialState.social_media then @props.initialState.social_media else @default_state.social_media; birthday = if @props.initialState.birthday then Moment(new Date(@props.initialState.birthday)) else @default_state.birthday; @setState({_id: @props.initialState._id, first_name: first_name, middle_name: middle_name, last_name: last_name, \ email: email, phone_number: phone_number, social_media: social_media, address: address, birthday: birthday, update_from_props: false}); render: -> <div className="add-item"> {@createInputField("first_name", "First Name:", "text")} {@createInputField("middle_name", "Middle Name:", "text")} {@createInputField("last_name", "Last Name:", "text")} {@createInputField("address", "Address:", "text")} {@createInputField("email", "Email:", "text")} {@createInputField("phone_number", "Phone Number:", "text")} {@createInputField("social_media", "Social Media:", "text")} {@createInputField("birthday", "Birthday:", "date")} {@getCreateItemAlert()} <div className="row common-create-buttons"> <button className="col-md-6 btn button-ok" onClick={@handleCreateItem}>{@getCreateButtonText()}</button> <button className="col-md-6 btn button-cancel" onClick={@handleCancel}>Cancel</button> </div> </div> getCreateButtonText: () -> if (@state._id) "Update Customer" else "Create Customer" getCreateItemAlert: () -> success = if (@state.customer_success) then " alert-success" else " alert-danger"; if (@state.customer_alert) <div className={"general-alert alert alert-dismissible" + success} role="alert"> <button type="button" className="close" aria-label="Close" onClick={@dismissAlert}><span aria-hidden="true">&times;</span></button> <strong>{if (@state.customer_success) then "Success!" else "Error!"}</strong> {@state.customer_alert} </div> else <div></div> dismissAlert: (event) -> @setState({customer_alert: ""}); createInputField: (name, display_name, type) -> inputCreate = () => if (type == "date") <DatePicker className="form-control common-input-field" selected={@state[name]} onChange={(moment) => @handleFieldUpdate(name, moment)} todayButton={'Today'} /> else <div> <input type={type} className="form-control common-input-field" value={@state[name]} onChange={(event) => @handleFieldUpdate(name, event)} /> </div> <div className="row common-create-row"> <div className="col-md-4"> {display_name} </div> <div className="col-md-8"> {inputCreate()} </div> </div> handleFieldUpdate: (field_name, event) -> update = {}; value = ""; if (event._isAMomentObject) value = event; else if (event.target.type == "number") value = event.target.value; value = mathjs.round(value, 2); else if (event.target.type == "text") value = event.target.value; update[field_name] = value; @setState(update); handleCreateItem: () -> form = new FormData(); form.append("token", window.sessionStorage.token); if (@state._id) form.append("_id", @state._id); form.append("first_name", @state.first_name); form.append("middle_name", @state.middle_name); form.append("last_name", @state.last_name); form.append("address", @state.address); form.append("email", @state.email); form.append("phone_number", @state.phone_number); form.append("social_media", @state.social_media); if @state.birthday then form.append("birthday", @state.birthday.toDate()); $.ajax({ url: 'aroma/secure/update_customer', data: form, cache: false, contentType: false, processData: false, type: 'POST', mimeType: 'multipart/form-data', fail: (data) => response = JSON.parse(data); @setState({customer_alert: response.message, customer_success: response.success}); success: (data) => response = JSON.parse(data); @setState({customer_alert: response.message, customer_success: response.success}); @props.updateCustomer(@state._id); window.setTimeout(() => @reset_default_timeout = window.setTimeout(() => @reset_default_timeout = undefined; @setState(@default_state); , 1000); @props.handleFinish(); , 2000); }); handleCancel: () -> @setState(@default_state); @props.handleFinish();
52840
# Author: <NAME> mathjs = require("mathjs"); React = require("react"); DatePicker = require("react-datepicker"); Moment = require("moment"); module.exports = React.createClass getInitialState: -> @default_state = {_id: undefined, first_name: "", middle_name: "", last_name: "", address: "", \ email: "", phone_number: "", social_media: "", birthday: undefined, \ customer_alert: "", customer_success: false, update_from_props: true}; componentDidMount: -> @checkInitialState(); componentWillUnmount: -> if (@reset_default_timeout) window.clearTimeout(@reset_default_timeout); @reset_default_timeout = undefined; componentDidUpdate: -> @checkInitialState(); checkInitialState: -> if (@props.initialState and @state.update_from_props) first_name = if @props.initialState.first_name then @props.initialState.first_name else @default_state.first_name; middle_name = if @props.initialState.middle_name then @props.initialState.middle_name else @default_state.middle_name; last_name = if @props.initialState.last_name then @props.initialState.last_name else @default_state.last_name; address = if @props.initialState.address then @props.initialState.address else @default_state.address; email = if @props.initialState.email then @props.initialState.email else @default_state.email; phone_number = if @props.initialState.phone_number then @props.initialState.phone_number else @default_state.phone_number; social_media = if @props.initialState.social_media then @props.initialState.social_media else @default_state.social_media; birthday = if @props.initialState.birthday then Moment(new Date(@props.initialState.birthday)) else @default_state.birthday; @setState({_id: @props.initialState._id, first_name: first_name, middle_name: middle_name, last_name: last_name, \ email: email, phone_number: phone_number, social_media: social_media, address: address, birthday: birthday, update_from_props: false}); render: -> <div className="add-item"> {@createInputField("first_name", "First Name:", "text")} {@createInputField("middle_name", "Middle Name:", "text")} {@createInputField("last_name", "Last Name:", "text")} {@createInputField("address", "Address:", "text")} {@createInputField("email", "Email:", "text")} {@createInputField("phone_number", "Phone Number:", "text")} {@createInputField("social_media", "Social Media:", "text")} {@createInputField("birthday", "Birthday:", "date")} {@getCreateItemAlert()} <div className="row common-create-buttons"> <button className="col-md-6 btn button-ok" onClick={@handleCreateItem}>{@getCreateButtonText()}</button> <button className="col-md-6 btn button-cancel" onClick={@handleCancel}>Cancel</button> </div> </div> getCreateButtonText: () -> if (@state._id) "Update Customer" else "Create Customer" getCreateItemAlert: () -> success = if (@state.customer_success) then " alert-success" else " alert-danger"; if (@state.customer_alert) <div className={"general-alert alert alert-dismissible" + success} role="alert"> <button type="button" className="close" aria-label="Close" onClick={@dismissAlert}><span aria-hidden="true">&times;</span></button> <strong>{if (@state.customer_success) then "Success!" else "Error!"}</strong> {@state.customer_alert} </div> else <div></div> dismissAlert: (event) -> @setState({customer_alert: ""}); createInputField: (name, display_name, type) -> inputCreate = () => if (type == "date") <DatePicker className="form-control common-input-field" selected={@state[name]} onChange={(moment) => @handleFieldUpdate(name, moment)} todayButton={'Today'} /> else <div> <input type={type} className="form-control common-input-field" value={@state[name]} onChange={(event) => @handleFieldUpdate(name, event)} /> </div> <div className="row common-create-row"> <div className="col-md-4"> {display_name} </div> <div className="col-md-8"> {inputCreate()} </div> </div> handleFieldUpdate: (field_name, event) -> update = {}; value = ""; if (event._isAMomentObject) value = event; else if (event.target.type == "number") value = event.target.value; value = mathjs.round(value, 2); else if (event.target.type == "text") value = event.target.value; update[field_name] = value; @setState(update); handleCreateItem: () -> form = new FormData(); form.append("token", window.sessionStorage.token); if (@state._id) form.append("_id", @state._id); form.append("first_name", @state.first_name); form.append("middle_name", @state.middle_name); form.append("last_name", @state.last_name); form.append("address", @state.address); form.append("email", @state.email); form.append("phone_number", @state.phone_number); form.append("social_media", @state.social_media); if @state.birthday then form.append("birthday", @state.birthday.toDate()); $.ajax({ url: 'aroma/secure/update_customer', data: form, cache: false, contentType: false, processData: false, type: 'POST', mimeType: 'multipart/form-data', fail: (data) => response = JSON.parse(data); @setState({customer_alert: response.message, customer_success: response.success}); success: (data) => response = JSON.parse(data); @setState({customer_alert: response.message, customer_success: response.success}); @props.updateCustomer(@state._id); window.setTimeout(() => @reset_default_timeout = window.setTimeout(() => @reset_default_timeout = undefined; @setState(@default_state); , 1000); @props.handleFinish(); , 2000); }); handleCancel: () -> @setState(@default_state); @props.handleFinish();
true
# Author: PI:NAME:<NAME>END_PI mathjs = require("mathjs"); React = require("react"); DatePicker = require("react-datepicker"); Moment = require("moment"); module.exports = React.createClass getInitialState: -> @default_state = {_id: undefined, first_name: "", middle_name: "", last_name: "", address: "", \ email: "", phone_number: "", social_media: "", birthday: undefined, \ customer_alert: "", customer_success: false, update_from_props: true}; componentDidMount: -> @checkInitialState(); componentWillUnmount: -> if (@reset_default_timeout) window.clearTimeout(@reset_default_timeout); @reset_default_timeout = undefined; componentDidUpdate: -> @checkInitialState(); checkInitialState: -> if (@props.initialState and @state.update_from_props) first_name = if @props.initialState.first_name then @props.initialState.first_name else @default_state.first_name; middle_name = if @props.initialState.middle_name then @props.initialState.middle_name else @default_state.middle_name; last_name = if @props.initialState.last_name then @props.initialState.last_name else @default_state.last_name; address = if @props.initialState.address then @props.initialState.address else @default_state.address; email = if @props.initialState.email then @props.initialState.email else @default_state.email; phone_number = if @props.initialState.phone_number then @props.initialState.phone_number else @default_state.phone_number; social_media = if @props.initialState.social_media then @props.initialState.social_media else @default_state.social_media; birthday = if @props.initialState.birthday then Moment(new Date(@props.initialState.birthday)) else @default_state.birthday; @setState({_id: @props.initialState._id, first_name: first_name, middle_name: middle_name, last_name: last_name, \ email: email, phone_number: phone_number, social_media: social_media, address: address, birthday: birthday, update_from_props: false}); render: -> <div className="add-item"> {@createInputField("first_name", "First Name:", "text")} {@createInputField("middle_name", "Middle Name:", "text")} {@createInputField("last_name", "Last Name:", "text")} {@createInputField("address", "Address:", "text")} {@createInputField("email", "Email:", "text")} {@createInputField("phone_number", "Phone Number:", "text")} {@createInputField("social_media", "Social Media:", "text")} {@createInputField("birthday", "Birthday:", "date")} {@getCreateItemAlert()} <div className="row common-create-buttons"> <button className="col-md-6 btn button-ok" onClick={@handleCreateItem}>{@getCreateButtonText()}</button> <button className="col-md-6 btn button-cancel" onClick={@handleCancel}>Cancel</button> </div> </div> getCreateButtonText: () -> if (@state._id) "Update Customer" else "Create Customer" getCreateItemAlert: () -> success = if (@state.customer_success) then " alert-success" else " alert-danger"; if (@state.customer_alert) <div className={"general-alert alert alert-dismissible" + success} role="alert"> <button type="button" className="close" aria-label="Close" onClick={@dismissAlert}><span aria-hidden="true">&times;</span></button> <strong>{if (@state.customer_success) then "Success!" else "Error!"}</strong> {@state.customer_alert} </div> else <div></div> dismissAlert: (event) -> @setState({customer_alert: ""}); createInputField: (name, display_name, type) -> inputCreate = () => if (type == "date") <DatePicker className="form-control common-input-field" selected={@state[name]} onChange={(moment) => @handleFieldUpdate(name, moment)} todayButton={'Today'} /> else <div> <input type={type} className="form-control common-input-field" value={@state[name]} onChange={(event) => @handleFieldUpdate(name, event)} /> </div> <div className="row common-create-row"> <div className="col-md-4"> {display_name} </div> <div className="col-md-8"> {inputCreate()} </div> </div> handleFieldUpdate: (field_name, event) -> update = {}; value = ""; if (event._isAMomentObject) value = event; else if (event.target.type == "number") value = event.target.value; value = mathjs.round(value, 2); else if (event.target.type == "text") value = event.target.value; update[field_name] = value; @setState(update); handleCreateItem: () -> form = new FormData(); form.append("token", window.sessionStorage.token); if (@state._id) form.append("_id", @state._id); form.append("first_name", @state.first_name); form.append("middle_name", @state.middle_name); form.append("last_name", @state.last_name); form.append("address", @state.address); form.append("email", @state.email); form.append("phone_number", @state.phone_number); form.append("social_media", @state.social_media); if @state.birthday then form.append("birthday", @state.birthday.toDate()); $.ajax({ url: 'aroma/secure/update_customer', data: form, cache: false, contentType: false, processData: false, type: 'POST', mimeType: 'multipart/form-data', fail: (data) => response = JSON.parse(data); @setState({customer_alert: response.message, customer_success: response.success}); success: (data) => response = JSON.parse(data); @setState({customer_alert: response.message, customer_success: response.success}); @props.updateCustomer(@state._id); window.setTimeout(() => @reset_default_timeout = window.setTimeout(() => @reset_default_timeout = undefined; @setState(@default_state); , 1000); @props.handleFinish(); , 2000); }); handleCancel: () -> @setState(@default_state); @props.handleFinish();
[ { "context": "#Copyright 2014 - 2015\n#Author: Varuna Jayasiri http://blog.varunajayasiri.com\n\nMod.require ->\n U", "end": 47, "score": 0.9998943209648132, "start": 32, "tag": "NAME", "value": "Varuna Jayasiri" } ]
js/util.coffee
vpj/predict
0
#Copyright 2014 - 2015 #Author: Varuna Jayasiri http://blog.varunajayasiri.com Mod.require -> Util = extend: -> return null if arguments.length is 0 obj = arguments[0] if (typeof obj) isnt 'object' throw new Error "Cannot extend #{typeof obj}" for i in [1...arguments.length] o = arguments[i] if (typeof o) isnt 'object' throw new Error "Cannot extend #{typeof o}" for k, v of o obj[k] = v return obj Mod.set 'Util', Util
191241
#Copyright 2014 - 2015 #Author: <NAME> http://blog.varunajayasiri.com Mod.require -> Util = extend: -> return null if arguments.length is 0 obj = arguments[0] if (typeof obj) isnt 'object' throw new Error "Cannot extend #{typeof obj}" for i in [1...arguments.length] o = arguments[i] if (typeof o) isnt 'object' throw new Error "Cannot extend #{typeof o}" for k, v of o obj[k] = v return obj Mod.set 'Util', Util
true
#Copyright 2014 - 2015 #Author: PI:NAME:<NAME>END_PI http://blog.varunajayasiri.com Mod.require -> Util = extend: -> return null if arguments.length is 0 obj = arguments[0] if (typeof obj) isnt 'object' throw new Error "Cannot extend #{typeof obj}" for i in [1...arguments.length] o = arguments[i] if (typeof o) isnt 'object' throw new Error "Cannot extend #{typeof o}" for k, v of o obj[k] = v return obj Mod.set 'Util', Util
[ { "context": "3-2016 TheGrid (Rituwall Inc.)\n# (c) 2011-2012 Henri Bergius, Nemein\n# NoFlo may be freely distributed und", "end": 129, "score": 0.9998435974121094, "start": 116, "tag": "NAME", "value": "Henri Bergius" }, { "context": "(Rituwall Inc.)\n# (c) 2011-2012 Henri Bergius, Nemein\n# NoFlo may be freely distributed under the M", "end": 137, "score": 0.9982976913452148, "start": 131, "tag": "NAME", "value": "Nemein" } ]
src/lib/Component.coffee
aretecode/noflo-built
1
# NoFlo - Flow-Based Programming for JavaScript # (c) 2013-2016 TheGrid (Rituwall Inc.) # (c) 2011-2012 Henri Bergius, Nemein # NoFlo may be freely distributed under the MIT license # # Baseclass for regular NoFlo components. {EventEmitter} = require 'events' ports = require './Ports' IP = require './IP' class Component extends EventEmitter description: '' icon: null constructor: (options) -> options = {} unless options options.inPorts = {} unless options.inPorts if options.inPorts instanceof ports.InPorts @inPorts = options.inPorts else @inPorts = new ports.InPorts options.inPorts options.outPorts = {} unless options.outPorts if options.outPorts instanceof ports.OutPorts @outPorts = options.outPorts else @outPorts = new ports.OutPorts options.outPorts @icon = options.icon if options.icon @description = options.description if options.description @started = false @load = 0 @ordered = options.ordered ? false @autoOrdering = options.autoOrdering ? null @outputQ = [] @activateOnInput = options.activateOnInput ? true @forwardBrackets = in: ['out', 'error'] @bracketCounter = {} if 'forwardBrackets' of options @forwardBrackets = options.forwardBrackets if typeof options.process is 'function' @process options.process getDescription: -> @description isReady: -> true isSubgraph: -> false setIcon: (@icon) -> @emit 'icon', @icon getIcon: -> @icon error: (e, groups = [], errorPort = 'error', scope = null) => if @outPorts[errorPort] and (@outPorts[errorPort].isAttached() or not @outPorts[errorPort].isRequired()) @outPorts[errorPort].openBracket group, scope: scope for group in groups @outPorts[errorPort].data e, scope: scope @outPorts[errorPort].closeBracket group, scope: scope for group in groups # @outPorts[errorPort].disconnect() return throw e shutdown: -> @started = false # The startup function performs initialization for the component. start: -> @started = true @started isStarted: -> @started # Ensures braket forwarding map is correct for the existing ports prepareForwarding: -> for inPort, outPorts of @forwardBrackets unless inPort of @inPorts.ports delete @forwardBrackets[inPort] continue tmp = [] for outPort in outPorts tmp.push outPort if outPort of @outPorts.ports if tmp.length is 0 delete @forwardBrackets[inPort] else @forwardBrackets[inPort] = tmp @bracketCounter[inPort] = 0 # Sets process handler function process: (handle) -> unless typeof handle is 'function' throw new Error "Process handler must be a function" unless @inPorts throw new Error "Component ports must be defined before process function" @prepareForwarding() @handle = handle for name, port of @inPorts.ports do (name, port) => port.name = name unless port.name port.on 'ip', (ip) => @handleIP ip, port @ # Handles an incoming IP object handleIP: (ip, port) -> if ip.type is 'openBracket' @autoOrdering = true if @autoOrdering is null @bracketCounter[port.name]++ if port.name of @forwardBrackets and (ip.type is 'openBracket' or ip.type is 'closeBracket') # Bracket forwarding outputEntry = __resolved: true __forwarded: true __type: ip.type __scope: ip.scope for outPort in @forwardBrackets[port.name] outputEntry[outPort] = [] unless outPort of outputEntry outputEntry[outPort].push ip if ip.scope? port.scopedBuffer[ip.scope].pop() else port.buffer.pop() @outputQ.push outputEntry @processOutputQueue() return return unless port.options.triggering result = {} input = new ProcessInput @inPorts, ip, @, port, result output = new ProcessOutput @outPorts, ip, @, result @load++ @handle input, output, -> output.done() processOutputQueue: -> while @outputQ.length > 0 result = @outputQ[0] break unless result.__resolved for port, ips of result continue if port.indexOf('__') is 0 continue unless @outPorts.ports[port].isAttached() for ip in ips @bracketCounter[port]-- if ip.type is 'closeBracket' @outPorts[port].sendIP ip @outputQ.shift() bracketsClosed = true for name, port of @outPorts.ports if @bracketCounter[port] isnt 0 bracketsClosed = false break @autoOrdering = null if bracketsClosed and @autoOrdering is true exports.Component = Component class ProcessInput constructor: (@ports, @ip, @nodeInstance, @port, @result) -> @scope = @ip.scope @buffer = new PortBuffer(@) # Sets component state to `activated` activate: -> @result.__resolved = false if @nodeInstance.ordered or @nodeInstance.autoOrdering @nodeInstance.outputQ.push @result # Returns true if a port (or ports joined by logical AND) has a new IP # Passing a validation callback as a last argument allows more selective # checking of packets. has: (args...) -> args = ['in'] unless args.length if typeof args[args.length - 1] is 'function' validate = args.pop() for port in args return false unless @ports[port].has @scope, validate return true res = true res and= @ports[port].ready @scope for port in args res # Fetches IP object(s) for port(s) get: (args...) -> args = ['in'] unless args.length if (@nodeInstance.ordered or @nodeInstance.autoOrdering) and @nodeInstance.activateOnInput and not ('__resolved' of @result) @activate() res = (@ports[port].get @scope for port in args) if args.length is 1 then res[0] else res # Fetches `data` property of IP object(s) for given port(s) getData: (args...) -> args = ['in'] unless args.length ips = @get.apply this, args if args.length is 1 return ips?.data ? undefined (ip?.data ? undefined for ip in ips) hasStream: (port) -> buffer = @buffer.get port return false if buffer.length is 0 # check if we have everything until "disconnect" received = 0 for packet in buffer if packet.type is 'openBracket' ++received else if packet.type is 'closeBracket' --received received is 0 getStream: (port, withoutConnectAndDisconnect = false) -> buf = @buffer.get port @buffer.filter port, (ip) -> false if withoutConnectAndDisconnect buf = buf.slice 1 buf.pop() buf class PortBuffer constructor: (@context) -> set: (name, buffer) -> if name? and typeof name isnt 'string' buffer = name name = null if @context.scope? if name? @context.ports[name].scopedBuffer[@context.scope] = buffer return @context.ports[name].scopedBuffer[@context.scope] @context.port.scopedBuffer[@context.scope] = buffer return @context.port.scopedBuffer[@context.scope] if name? @context.ports[name].buffer = buffer return @context.ports[name].buffer @context.port.buffer = buffer return @context.port.buffer # Get a buffer (scoped or not) for a given port # if name is optional, use the current port get: (name = null) -> if @context.scope? if name? return @context.ports[name].scopedBuffer[@context.scope] return @context.port.scopedBuffer[@context.scope] if name? return @context.ports[name].buffer return @context.port.buffer # Find packets matching a callback and return them without modifying the buffer find: (name, cb) -> b = @get name b.filter cb # Find packets and modify the original buffer # cb is a function with 2 arguments (ip, index) filter: (name, cb) -> if name? and typeof name isnt 'string' cb = name name = null b = @get name b = b.filter cb @set name, b class ProcessOutput constructor: (@ports, @ip, @nodeInstance, @result) -> @scope = @ip.scope # Sets component state to `activated` activate: -> @result.__resolved = false if @nodeInstance.ordered or @nodeInstance.autoOrdering @nodeInstance.outputQ.push @result # Checks if a value is an Error isError: (err) -> err instanceof Error or Array.isArray(err) and err.length > 0 and err[0] instanceof Error # Sends an error object error: (err) -> multiple = Array.isArray err err = [err] unless multiple if 'error' of @ports and (@ports.error.isAttached() or not @ports.error.isRequired()) @sendIP 'error', new IP 'openBracket' if multiple @sendIP 'error', e for e in err @sendIP 'error', new IP 'closeBracket' if multiple else throw e for e in err # Sends a single IP object to a port sendIP: (port, packet) -> if typeof packet isnt 'object' or IP.types.indexOf(packet.type) is -1 ip = new IP 'data', packet else ip = packet ip.scope = @scope if @scope isnt null and ip.scope is null if @nodeInstance.ordered or @nodeInstance.autoOrdering @result[port] = [] unless port of @result @result[port].push ip else @nodeInstance.outPorts[port].sendIP ip # Sends packets for each port as a key in the map # or sends Error or a list of Errors if passed such send: (outputMap) -> if (@nodeInstance.ordered or @nodeInstance.autoOrdering) and not ('__resolved' of @result) @activate() return @error outputMap if @isError outputMap componentPorts = [] mapIsInPorts = false for port in Object.keys @ports.ports componentPorts.push port if port isnt 'error' and port isnt 'ports' and port isnt '_callbacks' if not mapIsInPorts and typeof outputMap is 'object' and Object.keys(outputMap).indexOf(port) isnt -1 mapIsInPorts = true if componentPorts.length is 1 and not mapIsInPorts @sendIP componentPorts[0], outputMap return for port, packet of outputMap @sendIP port, packet # Sends the argument via `send()` and marks activation as `done()` sendDone: (outputMap) -> @send outputMap @done() # Makes a map-style component pass a result value to `out` # keeping all IP metadata received from `in`, # or modifying it if `options` is provided pass: (data, options = {}) -> unless 'out' of @ports throw new Error 'output.pass() requires port "out" to be present' for key, val of options @ip[key] = val @ip.data = data @sendIP 'out', @ip @done() # Finishes process activation gracefully done: (error) -> @error error if error if @nodeInstance.ordered or @nodeInstance.autoOrdering @result.__resolved = true @nodeInstance.processOutputQueue() @nodeInstance.load--
143882
# NoFlo - Flow-Based Programming for JavaScript # (c) 2013-2016 TheGrid (Rituwall Inc.) # (c) 2011-2012 <NAME>, <NAME> # NoFlo may be freely distributed under the MIT license # # Baseclass for regular NoFlo components. {EventEmitter} = require 'events' ports = require './Ports' IP = require './IP' class Component extends EventEmitter description: '' icon: null constructor: (options) -> options = {} unless options options.inPorts = {} unless options.inPorts if options.inPorts instanceof ports.InPorts @inPorts = options.inPorts else @inPorts = new ports.InPorts options.inPorts options.outPorts = {} unless options.outPorts if options.outPorts instanceof ports.OutPorts @outPorts = options.outPorts else @outPorts = new ports.OutPorts options.outPorts @icon = options.icon if options.icon @description = options.description if options.description @started = false @load = 0 @ordered = options.ordered ? false @autoOrdering = options.autoOrdering ? null @outputQ = [] @activateOnInput = options.activateOnInput ? true @forwardBrackets = in: ['out', 'error'] @bracketCounter = {} if 'forwardBrackets' of options @forwardBrackets = options.forwardBrackets if typeof options.process is 'function' @process options.process getDescription: -> @description isReady: -> true isSubgraph: -> false setIcon: (@icon) -> @emit 'icon', @icon getIcon: -> @icon error: (e, groups = [], errorPort = 'error', scope = null) => if @outPorts[errorPort] and (@outPorts[errorPort].isAttached() or not @outPorts[errorPort].isRequired()) @outPorts[errorPort].openBracket group, scope: scope for group in groups @outPorts[errorPort].data e, scope: scope @outPorts[errorPort].closeBracket group, scope: scope for group in groups # @outPorts[errorPort].disconnect() return throw e shutdown: -> @started = false # The startup function performs initialization for the component. start: -> @started = true @started isStarted: -> @started # Ensures braket forwarding map is correct for the existing ports prepareForwarding: -> for inPort, outPorts of @forwardBrackets unless inPort of @inPorts.ports delete @forwardBrackets[inPort] continue tmp = [] for outPort in outPorts tmp.push outPort if outPort of @outPorts.ports if tmp.length is 0 delete @forwardBrackets[inPort] else @forwardBrackets[inPort] = tmp @bracketCounter[inPort] = 0 # Sets process handler function process: (handle) -> unless typeof handle is 'function' throw new Error "Process handler must be a function" unless @inPorts throw new Error "Component ports must be defined before process function" @prepareForwarding() @handle = handle for name, port of @inPorts.ports do (name, port) => port.name = name unless port.name port.on 'ip', (ip) => @handleIP ip, port @ # Handles an incoming IP object handleIP: (ip, port) -> if ip.type is 'openBracket' @autoOrdering = true if @autoOrdering is null @bracketCounter[port.name]++ if port.name of @forwardBrackets and (ip.type is 'openBracket' or ip.type is 'closeBracket') # Bracket forwarding outputEntry = __resolved: true __forwarded: true __type: ip.type __scope: ip.scope for outPort in @forwardBrackets[port.name] outputEntry[outPort] = [] unless outPort of outputEntry outputEntry[outPort].push ip if ip.scope? port.scopedBuffer[ip.scope].pop() else port.buffer.pop() @outputQ.push outputEntry @processOutputQueue() return return unless port.options.triggering result = {} input = new ProcessInput @inPorts, ip, @, port, result output = new ProcessOutput @outPorts, ip, @, result @load++ @handle input, output, -> output.done() processOutputQueue: -> while @outputQ.length > 0 result = @outputQ[0] break unless result.__resolved for port, ips of result continue if port.indexOf('__') is 0 continue unless @outPorts.ports[port].isAttached() for ip in ips @bracketCounter[port]-- if ip.type is 'closeBracket' @outPorts[port].sendIP ip @outputQ.shift() bracketsClosed = true for name, port of @outPorts.ports if @bracketCounter[port] isnt 0 bracketsClosed = false break @autoOrdering = null if bracketsClosed and @autoOrdering is true exports.Component = Component class ProcessInput constructor: (@ports, @ip, @nodeInstance, @port, @result) -> @scope = @ip.scope @buffer = new PortBuffer(@) # Sets component state to `activated` activate: -> @result.__resolved = false if @nodeInstance.ordered or @nodeInstance.autoOrdering @nodeInstance.outputQ.push @result # Returns true if a port (or ports joined by logical AND) has a new IP # Passing a validation callback as a last argument allows more selective # checking of packets. has: (args...) -> args = ['in'] unless args.length if typeof args[args.length - 1] is 'function' validate = args.pop() for port in args return false unless @ports[port].has @scope, validate return true res = true res and= @ports[port].ready @scope for port in args res # Fetches IP object(s) for port(s) get: (args...) -> args = ['in'] unless args.length if (@nodeInstance.ordered or @nodeInstance.autoOrdering) and @nodeInstance.activateOnInput and not ('__resolved' of @result) @activate() res = (@ports[port].get @scope for port in args) if args.length is 1 then res[0] else res # Fetches `data` property of IP object(s) for given port(s) getData: (args...) -> args = ['in'] unless args.length ips = @get.apply this, args if args.length is 1 return ips?.data ? undefined (ip?.data ? undefined for ip in ips) hasStream: (port) -> buffer = @buffer.get port return false if buffer.length is 0 # check if we have everything until "disconnect" received = 0 for packet in buffer if packet.type is 'openBracket' ++received else if packet.type is 'closeBracket' --received received is 0 getStream: (port, withoutConnectAndDisconnect = false) -> buf = @buffer.get port @buffer.filter port, (ip) -> false if withoutConnectAndDisconnect buf = buf.slice 1 buf.pop() buf class PortBuffer constructor: (@context) -> set: (name, buffer) -> if name? and typeof name isnt 'string' buffer = name name = null if @context.scope? if name? @context.ports[name].scopedBuffer[@context.scope] = buffer return @context.ports[name].scopedBuffer[@context.scope] @context.port.scopedBuffer[@context.scope] = buffer return @context.port.scopedBuffer[@context.scope] if name? @context.ports[name].buffer = buffer return @context.ports[name].buffer @context.port.buffer = buffer return @context.port.buffer # Get a buffer (scoped or not) for a given port # if name is optional, use the current port get: (name = null) -> if @context.scope? if name? return @context.ports[name].scopedBuffer[@context.scope] return @context.port.scopedBuffer[@context.scope] if name? return @context.ports[name].buffer return @context.port.buffer # Find packets matching a callback and return them without modifying the buffer find: (name, cb) -> b = @get name b.filter cb # Find packets and modify the original buffer # cb is a function with 2 arguments (ip, index) filter: (name, cb) -> if name? and typeof name isnt 'string' cb = name name = null b = @get name b = b.filter cb @set name, b class ProcessOutput constructor: (@ports, @ip, @nodeInstance, @result) -> @scope = @ip.scope # Sets component state to `activated` activate: -> @result.__resolved = false if @nodeInstance.ordered or @nodeInstance.autoOrdering @nodeInstance.outputQ.push @result # Checks if a value is an Error isError: (err) -> err instanceof Error or Array.isArray(err) and err.length > 0 and err[0] instanceof Error # Sends an error object error: (err) -> multiple = Array.isArray err err = [err] unless multiple if 'error' of @ports and (@ports.error.isAttached() or not @ports.error.isRequired()) @sendIP 'error', new IP 'openBracket' if multiple @sendIP 'error', e for e in err @sendIP 'error', new IP 'closeBracket' if multiple else throw e for e in err # Sends a single IP object to a port sendIP: (port, packet) -> if typeof packet isnt 'object' or IP.types.indexOf(packet.type) is -1 ip = new IP 'data', packet else ip = packet ip.scope = @scope if @scope isnt null and ip.scope is null if @nodeInstance.ordered or @nodeInstance.autoOrdering @result[port] = [] unless port of @result @result[port].push ip else @nodeInstance.outPorts[port].sendIP ip # Sends packets for each port as a key in the map # or sends Error or a list of Errors if passed such send: (outputMap) -> if (@nodeInstance.ordered or @nodeInstance.autoOrdering) and not ('__resolved' of @result) @activate() return @error outputMap if @isError outputMap componentPorts = [] mapIsInPorts = false for port in Object.keys @ports.ports componentPorts.push port if port isnt 'error' and port isnt 'ports' and port isnt '_callbacks' if not mapIsInPorts and typeof outputMap is 'object' and Object.keys(outputMap).indexOf(port) isnt -1 mapIsInPorts = true if componentPorts.length is 1 and not mapIsInPorts @sendIP componentPorts[0], outputMap return for port, packet of outputMap @sendIP port, packet # Sends the argument via `send()` and marks activation as `done()` sendDone: (outputMap) -> @send outputMap @done() # Makes a map-style component pass a result value to `out` # keeping all IP metadata received from `in`, # or modifying it if `options` is provided pass: (data, options = {}) -> unless 'out' of @ports throw new Error 'output.pass() requires port "out" to be present' for key, val of options @ip[key] = val @ip.data = data @sendIP 'out', @ip @done() # Finishes process activation gracefully done: (error) -> @error error if error if @nodeInstance.ordered or @nodeInstance.autoOrdering @result.__resolved = true @nodeInstance.processOutputQueue() @nodeInstance.load--
true
# NoFlo - Flow-Based Programming for JavaScript # (c) 2013-2016 TheGrid (Rituwall Inc.) # (c) 2011-2012 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI # NoFlo may be freely distributed under the MIT license # # Baseclass for regular NoFlo components. {EventEmitter} = require 'events' ports = require './Ports' IP = require './IP' class Component extends EventEmitter description: '' icon: null constructor: (options) -> options = {} unless options options.inPorts = {} unless options.inPorts if options.inPorts instanceof ports.InPorts @inPorts = options.inPorts else @inPorts = new ports.InPorts options.inPorts options.outPorts = {} unless options.outPorts if options.outPorts instanceof ports.OutPorts @outPorts = options.outPorts else @outPorts = new ports.OutPorts options.outPorts @icon = options.icon if options.icon @description = options.description if options.description @started = false @load = 0 @ordered = options.ordered ? false @autoOrdering = options.autoOrdering ? null @outputQ = [] @activateOnInput = options.activateOnInput ? true @forwardBrackets = in: ['out', 'error'] @bracketCounter = {} if 'forwardBrackets' of options @forwardBrackets = options.forwardBrackets if typeof options.process is 'function' @process options.process getDescription: -> @description isReady: -> true isSubgraph: -> false setIcon: (@icon) -> @emit 'icon', @icon getIcon: -> @icon error: (e, groups = [], errorPort = 'error', scope = null) => if @outPorts[errorPort] and (@outPorts[errorPort].isAttached() or not @outPorts[errorPort].isRequired()) @outPorts[errorPort].openBracket group, scope: scope for group in groups @outPorts[errorPort].data e, scope: scope @outPorts[errorPort].closeBracket group, scope: scope for group in groups # @outPorts[errorPort].disconnect() return throw e shutdown: -> @started = false # The startup function performs initialization for the component. start: -> @started = true @started isStarted: -> @started # Ensures braket forwarding map is correct for the existing ports prepareForwarding: -> for inPort, outPorts of @forwardBrackets unless inPort of @inPorts.ports delete @forwardBrackets[inPort] continue tmp = [] for outPort in outPorts tmp.push outPort if outPort of @outPorts.ports if tmp.length is 0 delete @forwardBrackets[inPort] else @forwardBrackets[inPort] = tmp @bracketCounter[inPort] = 0 # Sets process handler function process: (handle) -> unless typeof handle is 'function' throw new Error "Process handler must be a function" unless @inPorts throw new Error "Component ports must be defined before process function" @prepareForwarding() @handle = handle for name, port of @inPorts.ports do (name, port) => port.name = name unless port.name port.on 'ip', (ip) => @handleIP ip, port @ # Handles an incoming IP object handleIP: (ip, port) -> if ip.type is 'openBracket' @autoOrdering = true if @autoOrdering is null @bracketCounter[port.name]++ if port.name of @forwardBrackets and (ip.type is 'openBracket' or ip.type is 'closeBracket') # Bracket forwarding outputEntry = __resolved: true __forwarded: true __type: ip.type __scope: ip.scope for outPort in @forwardBrackets[port.name] outputEntry[outPort] = [] unless outPort of outputEntry outputEntry[outPort].push ip if ip.scope? port.scopedBuffer[ip.scope].pop() else port.buffer.pop() @outputQ.push outputEntry @processOutputQueue() return return unless port.options.triggering result = {} input = new ProcessInput @inPorts, ip, @, port, result output = new ProcessOutput @outPorts, ip, @, result @load++ @handle input, output, -> output.done() processOutputQueue: -> while @outputQ.length > 0 result = @outputQ[0] break unless result.__resolved for port, ips of result continue if port.indexOf('__') is 0 continue unless @outPorts.ports[port].isAttached() for ip in ips @bracketCounter[port]-- if ip.type is 'closeBracket' @outPorts[port].sendIP ip @outputQ.shift() bracketsClosed = true for name, port of @outPorts.ports if @bracketCounter[port] isnt 0 bracketsClosed = false break @autoOrdering = null if bracketsClosed and @autoOrdering is true exports.Component = Component class ProcessInput constructor: (@ports, @ip, @nodeInstance, @port, @result) -> @scope = @ip.scope @buffer = new PortBuffer(@) # Sets component state to `activated` activate: -> @result.__resolved = false if @nodeInstance.ordered or @nodeInstance.autoOrdering @nodeInstance.outputQ.push @result # Returns true if a port (or ports joined by logical AND) has a new IP # Passing a validation callback as a last argument allows more selective # checking of packets. has: (args...) -> args = ['in'] unless args.length if typeof args[args.length - 1] is 'function' validate = args.pop() for port in args return false unless @ports[port].has @scope, validate return true res = true res and= @ports[port].ready @scope for port in args res # Fetches IP object(s) for port(s) get: (args...) -> args = ['in'] unless args.length if (@nodeInstance.ordered or @nodeInstance.autoOrdering) and @nodeInstance.activateOnInput and not ('__resolved' of @result) @activate() res = (@ports[port].get @scope for port in args) if args.length is 1 then res[0] else res # Fetches `data` property of IP object(s) for given port(s) getData: (args...) -> args = ['in'] unless args.length ips = @get.apply this, args if args.length is 1 return ips?.data ? undefined (ip?.data ? undefined for ip in ips) hasStream: (port) -> buffer = @buffer.get port return false if buffer.length is 0 # check if we have everything until "disconnect" received = 0 for packet in buffer if packet.type is 'openBracket' ++received else if packet.type is 'closeBracket' --received received is 0 getStream: (port, withoutConnectAndDisconnect = false) -> buf = @buffer.get port @buffer.filter port, (ip) -> false if withoutConnectAndDisconnect buf = buf.slice 1 buf.pop() buf class PortBuffer constructor: (@context) -> set: (name, buffer) -> if name? and typeof name isnt 'string' buffer = name name = null if @context.scope? if name? @context.ports[name].scopedBuffer[@context.scope] = buffer return @context.ports[name].scopedBuffer[@context.scope] @context.port.scopedBuffer[@context.scope] = buffer return @context.port.scopedBuffer[@context.scope] if name? @context.ports[name].buffer = buffer return @context.ports[name].buffer @context.port.buffer = buffer return @context.port.buffer # Get a buffer (scoped or not) for a given port # if name is optional, use the current port get: (name = null) -> if @context.scope? if name? return @context.ports[name].scopedBuffer[@context.scope] return @context.port.scopedBuffer[@context.scope] if name? return @context.ports[name].buffer return @context.port.buffer # Find packets matching a callback and return them without modifying the buffer find: (name, cb) -> b = @get name b.filter cb # Find packets and modify the original buffer # cb is a function with 2 arguments (ip, index) filter: (name, cb) -> if name? and typeof name isnt 'string' cb = name name = null b = @get name b = b.filter cb @set name, b class ProcessOutput constructor: (@ports, @ip, @nodeInstance, @result) -> @scope = @ip.scope # Sets component state to `activated` activate: -> @result.__resolved = false if @nodeInstance.ordered or @nodeInstance.autoOrdering @nodeInstance.outputQ.push @result # Checks if a value is an Error isError: (err) -> err instanceof Error or Array.isArray(err) and err.length > 0 and err[0] instanceof Error # Sends an error object error: (err) -> multiple = Array.isArray err err = [err] unless multiple if 'error' of @ports and (@ports.error.isAttached() or not @ports.error.isRequired()) @sendIP 'error', new IP 'openBracket' if multiple @sendIP 'error', e for e in err @sendIP 'error', new IP 'closeBracket' if multiple else throw e for e in err # Sends a single IP object to a port sendIP: (port, packet) -> if typeof packet isnt 'object' or IP.types.indexOf(packet.type) is -1 ip = new IP 'data', packet else ip = packet ip.scope = @scope if @scope isnt null and ip.scope is null if @nodeInstance.ordered or @nodeInstance.autoOrdering @result[port] = [] unless port of @result @result[port].push ip else @nodeInstance.outPorts[port].sendIP ip # Sends packets for each port as a key in the map # or sends Error or a list of Errors if passed such send: (outputMap) -> if (@nodeInstance.ordered or @nodeInstance.autoOrdering) and not ('__resolved' of @result) @activate() return @error outputMap if @isError outputMap componentPorts = [] mapIsInPorts = false for port in Object.keys @ports.ports componentPorts.push port if port isnt 'error' and port isnt 'ports' and port isnt '_callbacks' if not mapIsInPorts and typeof outputMap is 'object' and Object.keys(outputMap).indexOf(port) isnt -1 mapIsInPorts = true if componentPorts.length is 1 and not mapIsInPorts @sendIP componentPorts[0], outputMap return for port, packet of outputMap @sendIP port, packet # Sends the argument via `send()` and marks activation as `done()` sendDone: (outputMap) -> @send outputMap @done() # Makes a map-style component pass a result value to `out` # keeping all IP metadata received from `in`, # or modifying it if `options` is provided pass: (data, options = {}) -> unless 'out' of @ports throw new Error 'output.pass() requires port "out" to be present' for key, val of options @ip[key] = val @ip.data = data @sendIP 'out', @ip @done() # Finishes process activation gracefully done: (error) -> @error error if error if @nodeInstance.ordered or @nodeInstance.autoOrdering @result.__resolved = true @nodeInstance.processOutputQueue() @nodeInstance.load--
[ { "context": "get me started with Hubot scripts.\n#\n# Author:\n# Chris Coveney <xkickflip@gmail.com>\n\nmodule.exports = (robot) -", "end": 486, "score": 0.9998174905776978, "start": 473, "tag": "NAME", "value": "Chris Coveney" }, { "context": "ith Hubot scripts.\n#\n# Author:\n# Chris Coveney <xkickflip@gmail.com>\n\nmodule.exports = (robot) ->\n\n responseString =", "end": 507, "score": 0.9999293088912964, "start": 488, "tag": "EMAIL", "value": "xkickflip@gmail.com" } ]
src/cybernetic.coffee
xkickflip/hubot-cybernetic
0
# Description # Allows hubot to identify itself to users when asked who or what it is. # # Configuration: # None # # Commands: # hubot who are you? - hubot identifies itself # hubot what are you? - hubot identifies itself # who is hubot? - hubot idenfities itself # what is hubot? - hubot identifies itself # what's a hubot? - hubot identifies itself # # Notes: # Just a fun little script to get me started with Hubot scripts. # # Author: # Chris Coveney <xkickflip@gmail.com> module.exports = (robot) -> responseString = "I am #{robot.name}. I'm a cybernetic organism. Living tissue over a metal endoskeleton. My mission is to protect you." robot.respond /(who|what) are you/i, (res) -> res.send responseString hearRegExp = new RegExp "(who|what|what's) (is|a) #{robot.name}", "i" robot.hear hearRegExp, (res) -> res.send responseString
189900
# Description # Allows hubot to identify itself to users when asked who or what it is. # # Configuration: # None # # Commands: # hubot who are you? - hubot identifies itself # hubot what are you? - hubot identifies itself # who is hubot? - hubot idenfities itself # what is hubot? - hubot identifies itself # what's a hubot? - hubot identifies itself # # Notes: # Just a fun little script to get me started with Hubot scripts. # # Author: # <NAME> <<EMAIL>> module.exports = (robot) -> responseString = "I am #{robot.name}. I'm a cybernetic organism. Living tissue over a metal endoskeleton. My mission is to protect you." robot.respond /(who|what) are you/i, (res) -> res.send responseString hearRegExp = new RegExp "(who|what|what's) (is|a) #{robot.name}", "i" robot.hear hearRegExp, (res) -> res.send responseString
true
# Description # Allows hubot to identify itself to users when asked who or what it is. # # Configuration: # None # # Commands: # hubot who are you? - hubot identifies itself # hubot what are you? - hubot identifies itself # who is hubot? - hubot idenfities itself # what is hubot? - hubot identifies itself # what's a hubot? - hubot identifies itself # # Notes: # Just a fun little script to get me started with Hubot scripts. # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> module.exports = (robot) -> responseString = "I am #{robot.name}. I'm a cybernetic organism. Living tissue over a metal endoskeleton. My mission is to protect you." robot.respond /(who|what) are you/i, (res) -> res.send responseString hearRegExp = new RegExp "(who|what|what's) (is|a) #{robot.name}", "i" robot.hear hearRegExp, (res) -> res.send responseString
[ { "context": "# @author mr.doob / http://mrdoob.com/\n# @author philogb / htt", "end": 12, "score": 0.9487613439559937, "start": 10, "tag": "USERNAME", "value": "mr" }, { "context": "# @author mr.doob / http://mrdoob.com/\n# @author philogb / http", "end": 12, "score": 0.5536468029022217, "start": 12, "tag": "NAME", "value": "" }, { "context": "# @author mr.doob / http://mrdoob.com/\n# @author philogb / http://b", "end": 17, "score": 0.5645135045051575, "start": 13, "tag": "USERNAME", "value": "doob" }, { "context": "# @author mr.doob / http://mrdoob.com/\n# @author philogb / http://blog.thejit.org/\n# @author egraether / h", "end": 56, "score": 0.9996501803398132, "start": 49, "tag": "USERNAME", "value": "philogb" }, { "context": "author philogb / http://blog.thejit.org/\n# @author egraether / http://egraether.com/\n# @author zz85 / http://w", "end": 102, "score": 0.9962329864501953, "start": 93, "tag": "USERNAME", "value": "egraether" }, { "context": "author egraether / http://egraether.com/\n# @author zz85 / http://www.lab4games.net/zz85/blog\n# @author al", "end": 141, "score": 0.9996218681335449, "start": 137, "tag": "USERNAME", "value": "zz85" }, { "context": "z85 / http://www.lab4games.net/zz85/blog\n# @author aladjev.andrew@gmail.com\n\nclass Vector2\n constructor: (x, y) ->\n @x = ", "end": 213, "score": 0.9999198317527771, "start": 189, "tag": "EMAIL", "value": "aladjev.andrew@gmail.com" } ]
source/javascripts/new_src/core/vector_2.coffee
andrew-aladev/three.js
0
# @author mr.doob / http://mrdoob.com/ # @author philogb / http://blog.thejit.org/ # @author egraether / http://egraether.com/ # @author zz85 / http://www.lab4games.net/zz85/blog # @author aladjev.andrew@gmail.com class Vector2 constructor: (x, y) -> @x = x or 0 @y = y or 0 set: (x, y) -> @x = x @y = y this copy: (v) -> @x = v.x @y = v.y this add: (a, b) -> @x = a.x + b.x @y = a.y + b.y this addSelf: (v) -> @x += v.x @y += v.y this sub: (a, b) -> @x = a.x - b.x @y = a.y - b.y this subSelf: (v) -> @x -= v.x @y -= v.y this multiplyScalar: (s) -> @x *= s @y *= s this divideScalar: (s) -> if s @x /= s @y /= s else @set 0, 0 this negate: -> @multiplyScalar -1 dot: (v) -> @x * v.x + @y * v.y lengthSq: -> @x * @x + @y * @y length: -> Math.sqrt @lengthSq() normalize: -> @divideScalar @length() distanceTo: (v) -> Math.sqrt @distanceToSquared(v) distanceToSquared: (v) -> dx = @x - v.x dy = @y - v.y dx * dx + dy * dy setLength: (l) -> @normalize().multiplyScalar l lerpSelf: (v, alpha) -> @x += (v.x - @x) * alpha @y += (v.y - @y) * alpha this equals: (v) -> (v.x is @x) and (v.y is @y) isZero: -> @lengthSq() < 0.0001 clone: -> new Vector2 @x, @y namespace "THREE", (exports) -> exports.Vector2 = Vector2
114579
# @author mr<NAME>.doob / http://mrdoob.com/ # @author philogb / http://blog.thejit.org/ # @author egraether / http://egraether.com/ # @author zz85 / http://www.lab4games.net/zz85/blog # @author <EMAIL> class Vector2 constructor: (x, y) -> @x = x or 0 @y = y or 0 set: (x, y) -> @x = x @y = y this copy: (v) -> @x = v.x @y = v.y this add: (a, b) -> @x = a.x + b.x @y = a.y + b.y this addSelf: (v) -> @x += v.x @y += v.y this sub: (a, b) -> @x = a.x - b.x @y = a.y - b.y this subSelf: (v) -> @x -= v.x @y -= v.y this multiplyScalar: (s) -> @x *= s @y *= s this divideScalar: (s) -> if s @x /= s @y /= s else @set 0, 0 this negate: -> @multiplyScalar -1 dot: (v) -> @x * v.x + @y * v.y lengthSq: -> @x * @x + @y * @y length: -> Math.sqrt @lengthSq() normalize: -> @divideScalar @length() distanceTo: (v) -> Math.sqrt @distanceToSquared(v) distanceToSquared: (v) -> dx = @x - v.x dy = @y - v.y dx * dx + dy * dy setLength: (l) -> @normalize().multiplyScalar l lerpSelf: (v, alpha) -> @x += (v.x - @x) * alpha @y += (v.y - @y) * alpha this equals: (v) -> (v.x is @x) and (v.y is @y) isZero: -> @lengthSq() < 0.0001 clone: -> new Vector2 @x, @y namespace "THREE", (exports) -> exports.Vector2 = Vector2
true
# @author mrPI:NAME:<NAME>END_PI.doob / http://mrdoob.com/ # @author philogb / http://blog.thejit.org/ # @author egraether / http://egraether.com/ # @author zz85 / http://www.lab4games.net/zz85/blog # @author PI:EMAIL:<EMAIL>END_PI class Vector2 constructor: (x, y) -> @x = x or 0 @y = y or 0 set: (x, y) -> @x = x @y = y this copy: (v) -> @x = v.x @y = v.y this add: (a, b) -> @x = a.x + b.x @y = a.y + b.y this addSelf: (v) -> @x += v.x @y += v.y this sub: (a, b) -> @x = a.x - b.x @y = a.y - b.y this subSelf: (v) -> @x -= v.x @y -= v.y this multiplyScalar: (s) -> @x *= s @y *= s this divideScalar: (s) -> if s @x /= s @y /= s else @set 0, 0 this negate: -> @multiplyScalar -1 dot: (v) -> @x * v.x + @y * v.y lengthSq: -> @x * @x + @y * @y length: -> Math.sqrt @lengthSq() normalize: -> @divideScalar @length() distanceTo: (v) -> Math.sqrt @distanceToSquared(v) distanceToSquared: (v) -> dx = @x - v.x dy = @y - v.y dx * dx + dy * dy setLength: (l) -> @normalize().multiplyScalar l lerpSelf: (v, alpha) -> @x += (v.x - @x) * alpha @y += (v.y - @y) * alpha this equals: (v) -> (v.x is @x) and (v.y is @y) isZero: -> @lengthSq() < 0.0001 clone: -> new Vector2 @x, @y namespace "THREE", (exports) -> exports.Vector2 = Vector2
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999126195907593, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/react/profile-page/historical.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { BeatmapPlaycount } from './beatmap-playcount' import { ExtraHeader } from './extra-header' import { PlayDetailList } from 'play-detail-list' import * as React from 'react' import { a, div, h2, h3, img, p, small, span } from 'react-dom-factories' import { ShowMoreLink } from 'show-more-link' el = React.createElement export class Historical extends React.PureComponent constructor: (props) -> super props @id = "users-show-historical-#{osu.uuid()}" @monthlyPlaycountsChartArea = React.createRef() @replaysWatchedCountsChartArea = React.createRef() @charts = {} componentDidMount: => $(window).on "throttled-resize.#{@id}", @resizeCharts @monthlyPlaycountsChartUpdate() @replaysWatchedCountsChartUpdate() componentDidUpdate: => @monthlyPlaycountsChartUpdate() @replaysWatchedCountsChartUpdate() componentWillUnmount: => $(window).off ".#{@id}" render: => div className: 'page-extra' el ExtraHeader, name: @props.name, withEdit: @props.withEdit if @hasMonthlyPlaycounts() div null, h3 className: 'title title--page-extra-small' osu.trans('users.show.extra.historical.monthly_playcounts.title') div className: 'page-extra__chart' ref: @monthlyPlaycountsChartArea h3 className: 'title title--page-extra-small' osu.trans('users.show.extra.historical.most_played.title') if @props.beatmapPlaycounts?.length [ for playcount in @props.beatmapPlaycounts el BeatmapPlaycount, key: playcount.beatmap.id playcount: playcount el ShowMoreLink, key: 'show-more-row' modifiers: ['profile-page', 't-greyseafoam-dark'] event: 'profile:showMore' hasMore: @props.pagination.beatmapPlaycounts.hasMore loading: @props.pagination.beatmapPlaycounts.loading data: name: 'beatmapPlaycounts' url: laroute.route 'users.beatmapsets', user: @props.user.id type: 'most_played' ] else p null, osu.trans('users.show.extra.historical.empty') h3 className: 'title title--page-extra-small' osu.trans('users.show.extra.historical.recent_plays.title') if @props.scoresRecent?.length [ el PlayDetailList, key: 'play-detail-list', scores: @props.scoresRecent el ShowMoreLink, key: 'show-more-row' modifiers: ['profile-page', 't-greyseafoam-dark'] event: 'profile:showMore' hasMore: @props.pagination.scoresRecent.hasMore loading: @props.pagination.scoresRecent.loading data: name: 'scoresRecent' url: laroute.route 'users.scores', user: @props.user.id type: 'recent' mode: @props.currentMode ] else p null, osu.trans('users.show.extra.historical.empty') if @hasReplaysWatchedCounts() div null, h3 className: 'title title--page-extra-small' osu.trans('users.show.extra.historical.replays_watched_counts.title') div className: 'page-extra__chart' ref: @replaysWatchedCountsChartArea chartUpdate: (attribute, area) => dataPadder = (padded, entry) -> if padded.length > 0 lastEntry = _.last(padded) missingMonths = entry.x.diff(lastEntry.x, 'months') - 1 _.times missingMonths, (i) -> padded.push x: lastEntry.x.clone().add(i + 1, 'months') y: 0 padded.push entry padded data = _(@props.user[attribute]) .sortBy 'start_date' .map (count) -> x: moment(count.start_date) y: count.count .reduce dataPadder, [] if data.length == 1 data.unshift x: data[0].x.clone().subtract(1, 'month') y: 0 if !@charts[attribute]? options = curve: d3.curveLinear formats: x: (d) -> moment(d).format(osu.trans('common.datetime.year_month_short.moment')) y: (d) -> osu.formatNumber(d) margins: right: 60 # more spacing for x axis label infoBoxFormats: x: (d) -> moment(d).format(osu.trans('common.datetime.year_month.moment')) y: (d) -> "<strong>#{osu.trans("users.show.extra.historical.#{attribute}.count_label")}</strong> #{_.escape(osu.formatNumber(d))}" tickValues: {} ticks: {} circleLine: true modifiers: ['profile-page'] @charts[attribute] = new LineChart(area, options) @updateTicks @charts[attribute], data @charts[attribute].loadData data hasMonthlyPlaycounts: => @props.user.monthly_playcounts.length > 0 hasReplaysWatchedCounts: => @props.user.replays_watched_counts.length > 0 monthlyPlaycountsChartUpdate: => return if !@hasMonthlyPlaycounts() @chartUpdate 'monthly_playcounts', @monthlyPlaycountsChartArea.current replaysWatchedCountsChartUpdate: => return if !@hasReplaysWatchedCounts() @chartUpdate 'replays_watched_counts', @replaysWatchedCountsChartArea.current updateTicks: (chart, data) => if osu.isDesktop() chart.options.ticks.x = null data ?= chart.data chart.options.tickValues.x = if data.length < 10 data.map (d) -> d.x else null else chart.options.ticks.x = Math.min(6, (data ? chart.data).length) chart.options.tickValues.x = null resizeCharts: => for own _name, chart of @charts @updateTicks chart chart.resize()
16769
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { BeatmapPlaycount } from './beatmap-playcount' import { ExtraHeader } from './extra-header' import { PlayDetailList } from 'play-detail-list' import * as React from 'react' import { a, div, h2, h3, img, p, small, span } from 'react-dom-factories' import { ShowMoreLink } from 'show-more-link' el = React.createElement export class Historical extends React.PureComponent constructor: (props) -> super props @id = "users-show-historical-#{osu.uuid()}" @monthlyPlaycountsChartArea = React.createRef() @replaysWatchedCountsChartArea = React.createRef() @charts = {} componentDidMount: => $(window).on "throttled-resize.#{@id}", @resizeCharts @monthlyPlaycountsChartUpdate() @replaysWatchedCountsChartUpdate() componentDidUpdate: => @monthlyPlaycountsChartUpdate() @replaysWatchedCountsChartUpdate() componentWillUnmount: => $(window).off ".#{@id}" render: => div className: 'page-extra' el ExtraHeader, name: @props.name, withEdit: @props.withEdit if @hasMonthlyPlaycounts() div null, h3 className: 'title title--page-extra-small' osu.trans('users.show.extra.historical.monthly_playcounts.title') div className: 'page-extra__chart' ref: @monthlyPlaycountsChartArea h3 className: 'title title--page-extra-small' osu.trans('users.show.extra.historical.most_played.title') if @props.beatmapPlaycounts?.length [ for playcount in @props.beatmapPlaycounts el BeatmapPlaycount, key: playcount.beatmap.id playcount: playcount el ShowMoreLink, key: 'show-more-row' modifiers: ['profile-page', 't-greyseafoam-dark'] event: 'profile:showMore' hasMore: @props.pagination.beatmapPlaycounts.hasMore loading: @props.pagination.beatmapPlaycounts.loading data: name: 'beatmapPlaycounts' url: laroute.route 'users.beatmapsets', user: @props.user.id type: 'most_played' ] else p null, osu.trans('users.show.extra.historical.empty') h3 className: 'title title--page-extra-small' osu.trans('users.show.extra.historical.recent_plays.title') if @props.scoresRecent?.length [ el PlayDetailList, key: 'play-detail-list', scores: @props.scoresRecent el ShowMoreLink, key: 'show-more-row' modifiers: ['profile-page', 't-greyseafoam-dark'] event: 'profile:showMore' hasMore: @props.pagination.scoresRecent.hasMore loading: @props.pagination.scoresRecent.loading data: name: 'scoresRecent' url: laroute.route 'users.scores', user: @props.user.id type: 'recent' mode: @props.currentMode ] else p null, osu.trans('users.show.extra.historical.empty') if @hasReplaysWatchedCounts() div null, h3 className: 'title title--page-extra-small' osu.trans('users.show.extra.historical.replays_watched_counts.title') div className: 'page-extra__chart' ref: @replaysWatchedCountsChartArea chartUpdate: (attribute, area) => dataPadder = (padded, entry) -> if padded.length > 0 lastEntry = _.last(padded) missingMonths = entry.x.diff(lastEntry.x, 'months') - 1 _.times missingMonths, (i) -> padded.push x: lastEntry.x.clone().add(i + 1, 'months') y: 0 padded.push entry padded data = _(@props.user[attribute]) .sortBy 'start_date' .map (count) -> x: moment(count.start_date) y: count.count .reduce dataPadder, [] if data.length == 1 data.unshift x: data[0].x.clone().subtract(1, 'month') y: 0 if !@charts[attribute]? options = curve: d3.curveLinear formats: x: (d) -> moment(d).format(osu.trans('common.datetime.year_month_short.moment')) y: (d) -> osu.formatNumber(d) margins: right: 60 # more spacing for x axis label infoBoxFormats: x: (d) -> moment(d).format(osu.trans('common.datetime.year_month.moment')) y: (d) -> "<strong>#{osu.trans("users.show.extra.historical.#{attribute}.count_label")}</strong> #{_.escape(osu.formatNumber(d))}" tickValues: {} ticks: {} circleLine: true modifiers: ['profile-page'] @charts[attribute] = new LineChart(area, options) @updateTicks @charts[attribute], data @charts[attribute].loadData data hasMonthlyPlaycounts: => @props.user.monthly_playcounts.length > 0 hasReplaysWatchedCounts: => @props.user.replays_watched_counts.length > 0 monthlyPlaycountsChartUpdate: => return if !@hasMonthlyPlaycounts() @chartUpdate 'monthly_playcounts', @monthlyPlaycountsChartArea.current replaysWatchedCountsChartUpdate: => return if !@hasReplaysWatchedCounts() @chartUpdate 'replays_watched_counts', @replaysWatchedCountsChartArea.current updateTicks: (chart, data) => if osu.isDesktop() chart.options.ticks.x = null data ?= chart.data chart.options.tickValues.x = if data.length < 10 data.map (d) -> d.x else null else chart.options.ticks.x = Math.min(6, (data ? chart.data).length) chart.options.tickValues.x = null resizeCharts: => for own _name, chart of @charts @updateTicks chart chart.resize()
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { BeatmapPlaycount } from './beatmap-playcount' import { ExtraHeader } from './extra-header' import { PlayDetailList } from 'play-detail-list' import * as React from 'react' import { a, div, h2, h3, img, p, small, span } from 'react-dom-factories' import { ShowMoreLink } from 'show-more-link' el = React.createElement export class Historical extends React.PureComponent constructor: (props) -> super props @id = "users-show-historical-#{osu.uuid()}" @monthlyPlaycountsChartArea = React.createRef() @replaysWatchedCountsChartArea = React.createRef() @charts = {} componentDidMount: => $(window).on "throttled-resize.#{@id}", @resizeCharts @monthlyPlaycountsChartUpdate() @replaysWatchedCountsChartUpdate() componentDidUpdate: => @monthlyPlaycountsChartUpdate() @replaysWatchedCountsChartUpdate() componentWillUnmount: => $(window).off ".#{@id}" render: => div className: 'page-extra' el ExtraHeader, name: @props.name, withEdit: @props.withEdit if @hasMonthlyPlaycounts() div null, h3 className: 'title title--page-extra-small' osu.trans('users.show.extra.historical.monthly_playcounts.title') div className: 'page-extra__chart' ref: @monthlyPlaycountsChartArea h3 className: 'title title--page-extra-small' osu.trans('users.show.extra.historical.most_played.title') if @props.beatmapPlaycounts?.length [ for playcount in @props.beatmapPlaycounts el BeatmapPlaycount, key: playcount.beatmap.id playcount: playcount el ShowMoreLink, key: 'show-more-row' modifiers: ['profile-page', 't-greyseafoam-dark'] event: 'profile:showMore' hasMore: @props.pagination.beatmapPlaycounts.hasMore loading: @props.pagination.beatmapPlaycounts.loading data: name: 'beatmapPlaycounts' url: laroute.route 'users.beatmapsets', user: @props.user.id type: 'most_played' ] else p null, osu.trans('users.show.extra.historical.empty') h3 className: 'title title--page-extra-small' osu.trans('users.show.extra.historical.recent_plays.title') if @props.scoresRecent?.length [ el PlayDetailList, key: 'play-detail-list', scores: @props.scoresRecent el ShowMoreLink, key: 'show-more-row' modifiers: ['profile-page', 't-greyseafoam-dark'] event: 'profile:showMore' hasMore: @props.pagination.scoresRecent.hasMore loading: @props.pagination.scoresRecent.loading data: name: 'scoresRecent' url: laroute.route 'users.scores', user: @props.user.id type: 'recent' mode: @props.currentMode ] else p null, osu.trans('users.show.extra.historical.empty') if @hasReplaysWatchedCounts() div null, h3 className: 'title title--page-extra-small' osu.trans('users.show.extra.historical.replays_watched_counts.title') div className: 'page-extra__chart' ref: @replaysWatchedCountsChartArea chartUpdate: (attribute, area) => dataPadder = (padded, entry) -> if padded.length > 0 lastEntry = _.last(padded) missingMonths = entry.x.diff(lastEntry.x, 'months') - 1 _.times missingMonths, (i) -> padded.push x: lastEntry.x.clone().add(i + 1, 'months') y: 0 padded.push entry padded data = _(@props.user[attribute]) .sortBy 'start_date' .map (count) -> x: moment(count.start_date) y: count.count .reduce dataPadder, [] if data.length == 1 data.unshift x: data[0].x.clone().subtract(1, 'month') y: 0 if !@charts[attribute]? options = curve: d3.curveLinear formats: x: (d) -> moment(d).format(osu.trans('common.datetime.year_month_short.moment')) y: (d) -> osu.formatNumber(d) margins: right: 60 # more spacing for x axis label infoBoxFormats: x: (d) -> moment(d).format(osu.trans('common.datetime.year_month.moment')) y: (d) -> "<strong>#{osu.trans("users.show.extra.historical.#{attribute}.count_label")}</strong> #{_.escape(osu.formatNumber(d))}" tickValues: {} ticks: {} circleLine: true modifiers: ['profile-page'] @charts[attribute] = new LineChart(area, options) @updateTicks @charts[attribute], data @charts[attribute].loadData data hasMonthlyPlaycounts: => @props.user.monthly_playcounts.length > 0 hasReplaysWatchedCounts: => @props.user.replays_watched_counts.length > 0 monthlyPlaycountsChartUpdate: => return if !@hasMonthlyPlaycounts() @chartUpdate 'monthly_playcounts', @monthlyPlaycountsChartArea.current replaysWatchedCountsChartUpdate: => return if !@hasReplaysWatchedCounts() @chartUpdate 'replays_watched_counts', @replaysWatchedCountsChartArea.current updateTicks: (chart, data) => if osu.isDesktop() chart.options.ticks.x = null data ?= chart.data chart.options.tickValues.x = if data.length < 10 data.map (d) -> d.x else null else chart.options.ticks.x = Math.min(6, (data ? chart.data).length) chart.options.tickValues.x = null resizeCharts: => for own _name, chart of @charts @updateTicks chart chart.resize()
[ { "context": "\n title: 'history topic#' + i\n author: 'James Johnny'\n timestamp: '2004-9-4 21:20:22'\n readi", "end": 396, "score": 0.9998745918273926, "start": 384, "tag": "NAME", "value": "James Johnny" } ]
redisdb/create4seesee.coffee
android1and1/easti
0
RJ = require '../modules/md-readingjournals.js' nohm = (require 'nohm').Nohm client = (require 'redis').createClient() client.on 'connect',-> nohm.setPrefix 'seesee' nohm.setClient @ # if nessary,purge db 'seesee' #await nohm.purgeDb() # really. rj = nohm.register RJ for i in [1..4] ins = new rj ins.property title: 'history topic#' + i author: 'James Johnny' timestamp: '2004-9-4 21:20:22' reading_history:'2014-10-1,am' journal:'it is funny,fnufunny #' + i try await ins.save() console.log 'saved.' catch error console.dir ins.errors console.log 'done.' definitions = RJ.getDefinitions() setTimeout -> console.dir definitions client.quit() , 1500
47316
RJ = require '../modules/md-readingjournals.js' nohm = (require 'nohm').Nohm client = (require 'redis').createClient() client.on 'connect',-> nohm.setPrefix 'seesee' nohm.setClient @ # if nessary,purge db 'seesee' #await nohm.purgeDb() # really. rj = nohm.register RJ for i in [1..4] ins = new rj ins.property title: 'history topic#' + i author: '<NAME>' timestamp: '2004-9-4 21:20:22' reading_history:'2014-10-1,am' journal:'it is funny,fnufunny #' + i try await ins.save() console.log 'saved.' catch error console.dir ins.errors console.log 'done.' definitions = RJ.getDefinitions() setTimeout -> console.dir definitions client.quit() , 1500
true
RJ = require '../modules/md-readingjournals.js' nohm = (require 'nohm').Nohm client = (require 'redis').createClient() client.on 'connect',-> nohm.setPrefix 'seesee' nohm.setClient @ # if nessary,purge db 'seesee' #await nohm.purgeDb() # really. rj = nohm.register RJ for i in [1..4] ins = new rj ins.property title: 'history topic#' + i author: 'PI:NAME:<NAME>END_PI' timestamp: '2004-9-4 21:20:22' reading_history:'2014-10-1,am' journal:'it is funny,fnufunny #' + i try await ins.save() console.log 'saved.' catch error console.dir ins.errors console.log 'done.' definitions = RJ.getDefinitions() setTimeout -> console.dir definitions client.quit() , 1500
[ { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri", "end": 42, "score": 0.9998445510864258, "start": 24, "tag": "NAME", "value": "Alexander Cherniuk" }, { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistribution and use in ", "end": 60, "score": 0.9999306797981262, "start": 44, "tag": "EMAIL", "value": "ts33kr@gmail.com" } ]
library/nucleus/toolkit.coffee
ts33kr/granite
6
### Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" query = require "querystring" asciify = require "asciify" connect = require "connect" logger = require "winston" colors = require "colors" assert = require "assert" nconf = require "nconf" https = require "https" http = require "http" util = require "util" # Get the entire host information that includes hostname and port # that are in use by the current kernel and the servers. It may # be very useful for automatic generation of correct URLs and all # other content that requires the specific reference to the host. # This uses the hostname and port of the immediate server object. module.exports.urlOfServer = (ssl, parts, params, segment) -> parts = parts.join "/" if _.isArray parts qparams = query.stringify params if params assert server = try nconf.get "server:http" assert secure = try nconf.get "server:https" assert hostname = try nconf.get "server:host" assert port = if ssl then secure else server assert scheme = if ssl then "https" else "http" dedup = (string) -> try string.replace "//", "/" assert url = "#{scheme}://#{hostname}:#{port}" assert url += (try dedup("/#{parts}")) if parts assert url += (try "?#{qparams}") if qparams assert url += (try "##{segment}") if segment return try _.escape url.toString() or null # Get the entire host information that includes hostname and port # that are in use by the current kernel and the servers. It may # be very useful for automatic generation of correct URLs and all # other content that requires the specific reference to the host. # This uses the hostname and port of the master instance server. module.exports.urlOfMaster = (ssl, parts, params, segment) -> parts = parts.join "/" if _.isArray parts qparams = query.stringify params if params assert server = try nconf.get "master:http" assert secure = try nconf.get "master:https" assert hostname = try nconf.get "master:host" assert port = if ssl then secure else server assert scheme = if ssl then "https" else "http" dedup = (string) -> try string.replace "//", "/" assert url = "#{scheme}://#{hostname}:#{port}" assert url += (try dedup("/#{parts}")) if parts assert url += (try "?#{qparams}") if qparams assert url += (try "##{segment}") if segment return try _.escape url.toString() or null
181352
### Copyright (c) 2013, <NAME> <<EMAIL>> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" query = require "querystring" asciify = require "asciify" connect = require "connect" logger = require "winston" colors = require "colors" assert = require "assert" nconf = require "nconf" https = require "https" http = require "http" util = require "util" # Get the entire host information that includes hostname and port # that are in use by the current kernel and the servers. It may # be very useful for automatic generation of correct URLs and all # other content that requires the specific reference to the host. # This uses the hostname and port of the immediate server object. module.exports.urlOfServer = (ssl, parts, params, segment) -> parts = parts.join "/" if _.isArray parts qparams = query.stringify params if params assert server = try nconf.get "server:http" assert secure = try nconf.get "server:https" assert hostname = try nconf.get "server:host" assert port = if ssl then secure else server assert scheme = if ssl then "https" else "http" dedup = (string) -> try string.replace "//", "/" assert url = "#{scheme}://#{hostname}:#{port}" assert url += (try dedup("/#{parts}")) if parts assert url += (try "?#{qparams}") if qparams assert url += (try "##{segment}") if segment return try _.escape url.toString() or null # Get the entire host information that includes hostname and port # that are in use by the current kernel and the servers. It may # be very useful for automatic generation of correct URLs and all # other content that requires the specific reference to the host. # This uses the hostname and port of the master instance server. module.exports.urlOfMaster = (ssl, parts, params, segment) -> parts = parts.join "/" if _.isArray parts qparams = query.stringify params if params assert server = try nconf.get "master:http" assert secure = try nconf.get "master:https" assert hostname = try nconf.get "master:host" assert port = if ssl then secure else server assert scheme = if ssl then "https" else "http" dedup = (string) -> try string.replace "//", "/" assert url = "#{scheme}://#{hostname}:#{port}" assert url += (try dedup("/#{parts}")) if parts assert url += (try "?#{qparams}") if qparams assert url += (try "##{segment}") if segment return try _.escape url.toString() or null
true
### Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" query = require "querystring" asciify = require "asciify" connect = require "connect" logger = require "winston" colors = require "colors" assert = require "assert" nconf = require "nconf" https = require "https" http = require "http" util = require "util" # Get the entire host information that includes hostname and port # that are in use by the current kernel and the servers. It may # be very useful for automatic generation of correct URLs and all # other content that requires the specific reference to the host. # This uses the hostname and port of the immediate server object. module.exports.urlOfServer = (ssl, parts, params, segment) -> parts = parts.join "/" if _.isArray parts qparams = query.stringify params if params assert server = try nconf.get "server:http" assert secure = try nconf.get "server:https" assert hostname = try nconf.get "server:host" assert port = if ssl then secure else server assert scheme = if ssl then "https" else "http" dedup = (string) -> try string.replace "//", "/" assert url = "#{scheme}://#{hostname}:#{port}" assert url += (try dedup("/#{parts}")) if parts assert url += (try "?#{qparams}") if qparams assert url += (try "##{segment}") if segment return try _.escape url.toString() or null # Get the entire host information that includes hostname and port # that are in use by the current kernel and the servers. It may # be very useful for automatic generation of correct URLs and all # other content that requires the specific reference to the host. # This uses the hostname and port of the master instance server. module.exports.urlOfMaster = (ssl, parts, params, segment) -> parts = parts.join "/" if _.isArray parts qparams = query.stringify params if params assert server = try nconf.get "master:http" assert secure = try nconf.get "master:https" assert hostname = try nconf.get "master:host" assert port = if ssl then secure else server assert scheme = if ssl then "https" else "http" dedup = (string) -> try string.replace "//", "/" assert url = "#{scheme}://#{hostname}:#{port}" assert url += (try dedup("/#{parts}")) if parts assert url += (try "?#{qparams}") if qparams assert url += (try "##{segment}") if segment return try _.escape url.toString() or null
[ { "context": "tch: (uri, options) ->\n token = getAuthTokenCookie()\n if token?\n o", "end": 5453, "score": 0.8275678157806396, "start": 5438, "tag": "KEY", "value": "AuthTokenCookie" } ]
services/apollo.coffee
alin23/nextjs-coffee
2
import React from "react" import { ApolloProvider, getDataFromTree } from "react-apollo" import fetch from "isomorphic-fetch" import _ from "lodash" import getConfig from "next/config" import Head from "next/head" import { InMemoryCache } from "apollo-cache-inmemory" import { ReduxCache } from "apollo-cache-redux" import { ApolloClient } from "apollo-client" import { HttpLink } from "apollo-link-http" import { getAuthTokenCookie } from "~/lib/cookie" import Raven from "~/lib/raven" import config from "~/config" { serverRuntimeConfig, publicRuntimeConfig } = getConfig() apolloClient = null # Polyfill fetch() on the server (used by apollo-client) if not process.browser global.fetch = fetch createDefaultCache = () -> new InMemoryCache() createReduxCache = (store) -> new ReduxCache({ store }) create = (apolloConfig, initialState, reduxStore) -> createCache = apolloConfig.createCache ? ( if reduxStore? () -> createReduxCache(reduxStore) else createDefaultCache ) clientConfig = { connectToDevTools: process.browser # Disables forceFetch on the server (so queries are only run once) ssrMode: not process.browser cache: createCache().restore(initialState or {}) apolloConfig... } delete clientConfig.createCache return new ApolloClient(clientConfig) initApollo = (apolloConfig, initialState, { store, ctx... } = {}) -> if _.isFunction(apolloConfig) apolloConfig = apolloConfig(ctx) # Make sure to create a new client for every server-side request so that data # isn't shared between connections (which would be bad) if not process.browser return create(apolloConfig, initialState, store) # Reuse client on the client-side apolloClient ?= create(apolloConfig, initialState, store) return apolloClient # Gets the display name of a JSX component for dev tools getComponentDisplayName = (Component) -> return Component.displayName or Component.name or "Unknown" withData = (apolloConfig) -> (ComposedComponent) -> class WithData extends React.Component @displayName: "WithData(#{ getComponentDisplayName(ComposedComponent) })" @getInitialProps: ({ Component, router, ctx }) -> serverState = apollo: {} # Evaluate the composed component's getInitialProps() composedInitialProps = {} if ComposedComponent.getInitialProps composedInitialProps = await ComposedComponent.getInitialProps({ Component, router, ctx }) # Run all GraphQL queries in the component tree # and extract the resulting data if not process.browser apollo = initApollo(apolloConfig, null, ctx) # Provide the `url` prop data in case a GraphQL query uses it url = query: ctx.query, pathname: ctx.pathname try # Run all GraphQL queries await getDataFromTree( <ApolloProvider client={ apollo }> <ComposedComponent url={ url } ctx={ ctx } Component={ Component } router={ router } store={ ctx.store } {composedInitialProps...} /> </ApolloProvider> router: asPath: ctx.asPath pathname: ctx.pathname query: ctx.query ) catch error console.error(error) Raven.captureException(error) # Prevent Apollo Client GraphQL errors from crashing SSR. # Handle them in components via the data.error prop: # http:#dev.apollodata.com/react/api-queries.html#graphql-query-data-error # getDataFromTree does not call componentWillUnmount # head side effect therefore need to be cleared manually Head.rewind() # Extract query data from the Apollo store serverState = apollo: data: apollo.cache.extract() return { serverState composedInitialProps... } constructor: (props) -> super(props) @apollo = initApollo(apolloConfig, @props.serverState?.apollo?.data) render: () -> <ApolloProvider client={ @apollo }> <ComposedComponent {@props...} /> </ApolloProvider> getApolloConfig = ({ isServer = false, req } = {}) -> httpOpts = if isServer uri: publicRuntimeConfig.localGraphQlUrl credentials: "same-origin" headers: cookie: req?.headers?.cookie else uri: publicRuntimeConfig.remoteGraphQlUrl credentials: "same-origin" fetch: (uri, options) -> token = getAuthTokenCookie() if token? options.headers.Authorization = "Bearer #{ token }" return fetch(uri, options) if isServer token = getAuthTokenCookie(req) if token httpOpts.headers.Authorization = "Bearer #{ token }" return link: new HttpLink(httpOpts) export getApolloClient = (store) -> apolloClient ? initApollo(getApolloConfig, null, { store }) export default withData(getApolloConfig)
99060
import React from "react" import { ApolloProvider, getDataFromTree } from "react-apollo" import fetch from "isomorphic-fetch" import _ from "lodash" import getConfig from "next/config" import Head from "next/head" import { InMemoryCache } from "apollo-cache-inmemory" import { ReduxCache } from "apollo-cache-redux" import { ApolloClient } from "apollo-client" import { HttpLink } from "apollo-link-http" import { getAuthTokenCookie } from "~/lib/cookie" import Raven from "~/lib/raven" import config from "~/config" { serverRuntimeConfig, publicRuntimeConfig } = getConfig() apolloClient = null # Polyfill fetch() on the server (used by apollo-client) if not process.browser global.fetch = fetch createDefaultCache = () -> new InMemoryCache() createReduxCache = (store) -> new ReduxCache({ store }) create = (apolloConfig, initialState, reduxStore) -> createCache = apolloConfig.createCache ? ( if reduxStore? () -> createReduxCache(reduxStore) else createDefaultCache ) clientConfig = { connectToDevTools: process.browser # Disables forceFetch on the server (so queries are only run once) ssrMode: not process.browser cache: createCache().restore(initialState or {}) apolloConfig... } delete clientConfig.createCache return new ApolloClient(clientConfig) initApollo = (apolloConfig, initialState, { store, ctx... } = {}) -> if _.isFunction(apolloConfig) apolloConfig = apolloConfig(ctx) # Make sure to create a new client for every server-side request so that data # isn't shared between connections (which would be bad) if not process.browser return create(apolloConfig, initialState, store) # Reuse client on the client-side apolloClient ?= create(apolloConfig, initialState, store) return apolloClient # Gets the display name of a JSX component for dev tools getComponentDisplayName = (Component) -> return Component.displayName or Component.name or "Unknown" withData = (apolloConfig) -> (ComposedComponent) -> class WithData extends React.Component @displayName: "WithData(#{ getComponentDisplayName(ComposedComponent) })" @getInitialProps: ({ Component, router, ctx }) -> serverState = apollo: {} # Evaluate the composed component's getInitialProps() composedInitialProps = {} if ComposedComponent.getInitialProps composedInitialProps = await ComposedComponent.getInitialProps({ Component, router, ctx }) # Run all GraphQL queries in the component tree # and extract the resulting data if not process.browser apollo = initApollo(apolloConfig, null, ctx) # Provide the `url` prop data in case a GraphQL query uses it url = query: ctx.query, pathname: ctx.pathname try # Run all GraphQL queries await getDataFromTree( <ApolloProvider client={ apollo }> <ComposedComponent url={ url } ctx={ ctx } Component={ Component } router={ router } store={ ctx.store } {composedInitialProps...} /> </ApolloProvider> router: asPath: ctx.asPath pathname: ctx.pathname query: ctx.query ) catch error console.error(error) Raven.captureException(error) # Prevent Apollo Client GraphQL errors from crashing SSR. # Handle them in components via the data.error prop: # http:#dev.apollodata.com/react/api-queries.html#graphql-query-data-error # getDataFromTree does not call componentWillUnmount # head side effect therefore need to be cleared manually Head.rewind() # Extract query data from the Apollo store serverState = apollo: data: apollo.cache.extract() return { serverState composedInitialProps... } constructor: (props) -> super(props) @apollo = initApollo(apolloConfig, @props.serverState?.apollo?.data) render: () -> <ApolloProvider client={ @apollo }> <ComposedComponent {@props...} /> </ApolloProvider> getApolloConfig = ({ isServer = false, req } = {}) -> httpOpts = if isServer uri: publicRuntimeConfig.localGraphQlUrl credentials: "same-origin" headers: cookie: req?.headers?.cookie else uri: publicRuntimeConfig.remoteGraphQlUrl credentials: "same-origin" fetch: (uri, options) -> token = get<KEY>() if token? options.headers.Authorization = "Bearer #{ token }" return fetch(uri, options) if isServer token = getAuthTokenCookie(req) if token httpOpts.headers.Authorization = "Bearer #{ token }" return link: new HttpLink(httpOpts) export getApolloClient = (store) -> apolloClient ? initApollo(getApolloConfig, null, { store }) export default withData(getApolloConfig)
true
import React from "react" import { ApolloProvider, getDataFromTree } from "react-apollo" import fetch from "isomorphic-fetch" import _ from "lodash" import getConfig from "next/config" import Head from "next/head" import { InMemoryCache } from "apollo-cache-inmemory" import { ReduxCache } from "apollo-cache-redux" import { ApolloClient } from "apollo-client" import { HttpLink } from "apollo-link-http" import { getAuthTokenCookie } from "~/lib/cookie" import Raven from "~/lib/raven" import config from "~/config" { serverRuntimeConfig, publicRuntimeConfig } = getConfig() apolloClient = null # Polyfill fetch() on the server (used by apollo-client) if not process.browser global.fetch = fetch createDefaultCache = () -> new InMemoryCache() createReduxCache = (store) -> new ReduxCache({ store }) create = (apolloConfig, initialState, reduxStore) -> createCache = apolloConfig.createCache ? ( if reduxStore? () -> createReduxCache(reduxStore) else createDefaultCache ) clientConfig = { connectToDevTools: process.browser # Disables forceFetch on the server (so queries are only run once) ssrMode: not process.browser cache: createCache().restore(initialState or {}) apolloConfig... } delete clientConfig.createCache return new ApolloClient(clientConfig) initApollo = (apolloConfig, initialState, { store, ctx... } = {}) -> if _.isFunction(apolloConfig) apolloConfig = apolloConfig(ctx) # Make sure to create a new client for every server-side request so that data # isn't shared between connections (which would be bad) if not process.browser return create(apolloConfig, initialState, store) # Reuse client on the client-side apolloClient ?= create(apolloConfig, initialState, store) return apolloClient # Gets the display name of a JSX component for dev tools getComponentDisplayName = (Component) -> return Component.displayName or Component.name or "Unknown" withData = (apolloConfig) -> (ComposedComponent) -> class WithData extends React.Component @displayName: "WithData(#{ getComponentDisplayName(ComposedComponent) })" @getInitialProps: ({ Component, router, ctx }) -> serverState = apollo: {} # Evaluate the composed component's getInitialProps() composedInitialProps = {} if ComposedComponent.getInitialProps composedInitialProps = await ComposedComponent.getInitialProps({ Component, router, ctx }) # Run all GraphQL queries in the component tree # and extract the resulting data if not process.browser apollo = initApollo(apolloConfig, null, ctx) # Provide the `url` prop data in case a GraphQL query uses it url = query: ctx.query, pathname: ctx.pathname try # Run all GraphQL queries await getDataFromTree( <ApolloProvider client={ apollo }> <ComposedComponent url={ url } ctx={ ctx } Component={ Component } router={ router } store={ ctx.store } {composedInitialProps...} /> </ApolloProvider> router: asPath: ctx.asPath pathname: ctx.pathname query: ctx.query ) catch error console.error(error) Raven.captureException(error) # Prevent Apollo Client GraphQL errors from crashing SSR. # Handle them in components via the data.error prop: # http:#dev.apollodata.com/react/api-queries.html#graphql-query-data-error # getDataFromTree does not call componentWillUnmount # head side effect therefore need to be cleared manually Head.rewind() # Extract query data from the Apollo store serverState = apollo: data: apollo.cache.extract() return { serverState composedInitialProps... } constructor: (props) -> super(props) @apollo = initApollo(apolloConfig, @props.serverState?.apollo?.data) render: () -> <ApolloProvider client={ @apollo }> <ComposedComponent {@props...} /> </ApolloProvider> getApolloConfig = ({ isServer = false, req } = {}) -> httpOpts = if isServer uri: publicRuntimeConfig.localGraphQlUrl credentials: "same-origin" headers: cookie: req?.headers?.cookie else uri: publicRuntimeConfig.remoteGraphQlUrl credentials: "same-origin" fetch: (uri, options) -> token = getPI:KEY:<KEY>END_PI() if token? options.headers.Authorization = "Bearer #{ token }" return fetch(uri, options) if isServer token = getAuthTokenCookie(req) if token httpOpts.headers.Authorization = "Bearer #{ token }" return link: new HttpLink(httpOpts) export getApolloClient = (store) -> apolloClient ? initApollo(getApolloConfig, null, { store }) export default withData(getApolloConfig)
[ { "context": "(value) is false then return result\n\n\t\t\t\tkeys = ['prefix', 'first', 'middle', 'last', 'sufix']\n\n\t\t\t\tremoveUnauthorizedKeys value, keys\n\n\t\t\t\tfu", "end": 10488, "score": 0.9594817161560059, "start": 10446, "tag": "KEY", "value": "prefix', 'first', 'middle', 'last', 'sufix" }, { "context": "e) is false then return result\n\n\t\t\t\tvalidKeys = ['countryCode', 'phoneNumber', 'extention', 'type']\n\n\t\t\t\tremove", "end": 10910, "score": 0.8756882548332214, "start": 10899, "tag": "KEY", "value": "countryCode" }, { "context": "n return result\n\n\t\t\t\tvalidKeys = ['countryCode', 'phoneNumber', 'extention', 'type']\n\n\t\t\t\tremoveUnauthorizedKey", "end": 10925, "score": 0.4549073576927185, "start": 10914, "tag": "KEY", "value": "phoneNumber" }, { "context": "if field.isRequired is true\n\t\t\t\t\trequiredKeys = ['country', 'state', 'city', 'place', 'number']\n\t\t\t\t\toption", "end": 13504, "score": 0.7562662363052368, "start": 13497, "tag": "KEY", "value": "country" }, { "context": "Required is true\n\t\t\t\t\trequiredKeys = ['country', 'state', 'city', 'place', 'number']\n\t\t\t\t\toptionalKeys = ", "end": 13513, "score": 0.6348085403442383, "start": 13508, "tag": "KEY", "value": "state" }, { "context": "is true\n\t\t\t\t\trequiredKeys = ['country', 'state', 'city', 'place', 'number']\n\t\t\t\t\toptionalKeys = ['postal", "end": 13521, "score": 0.5235188007354736, "start": 13517, "tag": "KEY", "value": "city" }, { "context": "ceType', 'complement', 'type']\n\n\t\t\t\textraKeys = ['geolocation']\n\n\t\t\t\tremoveUnauthorizedKeys value, requiredKeys", "end": 13816, "score": 0.9739898443222046, "start": 13805, "tag": "KEY", "value": "geolocation" }, { "context": "t(value) is false then return result\n\t\t\t\tkeys = ['key', 'name', 'size', 'created', 'etag', 'headers', 'kind', 'last_modified', 'description', 'label', 'wildcard']\n\t\t\t\tremoveUnauthorizedKeys value, keys\n\n\t\t\telse", "end": 16405, "score": 0.9811353087425232, "start": 16295, "tag": "KEY", "value": "key', 'name', 'size', 'created', 'etag', 'headers', 'kind', 'last_modified', 'description', 'label', 'wildcard" } ]
server/metaUtils.coffee
Konecty/Konecty.Utils
0
crypto = Npm.require 'crypto' metaUtils = {} metaUtils.validateAndProcessValueFor = (meta, fieldName, value, actionType, model, objectOriginalValues, objectNewValues, idsToUpdate) -> field = meta.fields[fieldName] if not field? return new Meteor.Error 'utils-internal-error', "Field #{fieldName} does not exists on #{meta._id}" # Validate required fields if field.isRequired is true and not value? return new Meteor.Error 'utils-internal-error', "O Campo '#{fieldName}' é obrigatório, mas não está presente no dado." # Validate List fields if field.isList is true if field.maxElements? and field.maxElements > 0 if not _.isArray(value) or value.length > field.maxElements return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be array with the maximum of #{field.maxElements} item(s)" if field.minElements? and field.minElements > 0 if not _.isArray(value) or value.length < field.minElements return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be array with at least #{field.minElements} item(s)" if field.isAllowDuplicates is false and _.isArray(value) for itemA in value for itemB in value if utils.deepEqual(itemA, itemB) is true return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be array no duplicated values" # Validate picklist min selected if field.type is 'picklist' if _.isNumber(field.minSelected) if field.minSelected is 1 if not value? or (_.isArray(value) and value.length is 0) return new Meteor.Error 'utils-internal-error', "A lista de escolha '#{fieldName}' exige o mínimo de 1 valores selecionados. Mas não está presente no dado." if actionType is 'update' and not value? and field.type is 'lookup' lookupUtils.removeInheritedFields field, objectNewValues if not value? and field.type isnt 'autoNumber' return value # If field is Unique verify if exists another record on db with same value if value? and field.isUnique is true and field.type isnt 'autoNumber' query = {} query[fieldName] = value multiUpdate = idsToUpdate?.length > 1 # If is a single update exclude self record in verification if actionType is 'update' and multiUpdate isnt true query._id = $ne: idsToUpdate[0] count = model.find(query).count() if count > 0 return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be unique" result = true removeUnauthorizedKeys = (obj, keys, path) -> objKeys = Object.keys obj unauthorizedKeys = objKeys.filter (key) -> return keys.indexOf(key) is -1 for key in unauthorizedKeys delete obj[key] return obj mustBeValidFilter = (v) -> if not v.match in ['and', 'or'] result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains a property named 'match' with one of values ['and', 'or']" return false if _.isArray(v.conditions) objectOfConditions = {} for condition in v.conditions objectOfConditions[condition.term.replace(/\./g, ':') + ':' + condition.operator] = condition v.conditions = objectOfConditions if not _.isObject(v.conditions) result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains a property named 'conditions' of type Object with at least 1 item" return false for key, condition of v.conditions if mustBeString(condition.term) is false or mustBeString(condition.operator) is false result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains conditions with properties 'term' and 'operator' of type String" return false operators = ['exists', 'equals', 'not_equals', 'in', 'not_in', 'contains', 'not_contains', 'starts_with', 'end_with', 'less_than', 'greater_than', 'less_or_equals', 'greater_or_equals', 'between'] if not condition.operator in operators result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains conditions with valid operators such as [#{operators.join(', ')}]" return false if not condition.value? result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains conditions property named 'value'" return false if _.isArray(v.filters) for filter in v.filters if mustBeValidFilter(filter) is false return false mustBeString = (v, path) -> if not _.isString v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid String" return false mustBeStringOrNull = (v, path) -> if not v? then return true return mustBeString v, path mustBeNumber = (v, path) -> if not _.isNumber v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid Number" return false mustBeNumberOrNull = (v, path) -> if not v? then return true return mustBeNumber v, path mustBeBoolean = (v, path) -> if not _.isBoolean v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid Boolean" return false mustBeBooleanOrNull = (v, path) -> if not v? then return true return mustBeBoolean v, path mustBeObject = (v, path) -> if not _.isObject v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid Object" return false mustBeObjectOrNull = (v, path) -> if not v? then return true return mustBeObject v, path mustBeArray = (v, path) -> if not _.isArray v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid Array" return false mustBeArrayOrNull = (v, path) -> if not v? then return true return mustBeArray v, path mustBeDate = (v, path) -> date = new Date v if isNaN date result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid string or number representation of date" return false mustBeDateOrNull = (v, path) -> if not v? then return true return mustBeDate v, path validate = (value) -> switch field.type when 'boolean' if mustBeBoolean(value) is false then return result when 'number', 'percentage' if mustBeNumber(value) is false then return result if _.isNumber(field.maxValue) and value > field.maxValue return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be less than #{field.maxValue}" if _.isNumber(field.minValue) and value < field.minValue return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be greater than #{field.minValue}" when 'picklist' if _.isNumber(field.maxSelected) and field.maxSelected > 1 if mustBeArray(value) is false then return result if value.length > field.maxSelected return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be an array with max of #{field.maxSelected} item(s)" if _.isNumber(field.minSelected) and field.minSelected > 0 if value.length < field.minSelected return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be an array with min of #{field.minSelected} item(s)" valuesToVerify = [].concat value for valueToVerify in valuesToVerify if not field.options[valueToVerify]? return new Meteor.Error 'utils-internal-error', "Value #{valueToVerify} for field #{fieldName} is invalid" when 'text', 'richText' if _.isNumber value value = String value if mustBeString(value) is false then return result if field.normalization? and changeCase["#{field.normalization}Case"]? value = changeCase["#{field.normalization}Case"] value if _.isNumber(field.size) and field.size > 0 if value.length > field.size return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be smaller than #{field.size}" when 'dateTime', 'date' if mustBeObject(value) is false then return result if mustBeDate((value.$date || value), "#{fieldName}.$date") is false then return result value = new Date(value.$date || value) if field.maxValue? or field.minValue? compareValue = new Date(value) maxValue = field.maxValue minValue = field.minValue if field.type is 'date' compareValue.setHours(0) compareValue.setMinutes(0) compareValue.setSeconds(0) compareValue.setMilliseconds(0) if maxValue? and maxValue is '$now' maxValue = new Date() if field.type is 'date' maxValue.setHours(0) maxValue.setMinutes(0) maxValue.setSeconds(0) maxValue.setMilliseconds(0) if minValue? and minValue is '$now' minValue = new Date() if field.type is 'date' minValue.setHours(0) minValue.setMinutes(0) minValue.setSeconds(0) minValue.setMilliseconds(0) if field.type is 'date' momentFormat = 'DD/MM/YYYY' else momentFormat = 'DD/MM/YYYY HH:mm:ss' if mustBeDate(maxValue) isnt false and compareValue > maxValue return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be less than or equals to #{moment(maxValue).format(momentFormat)}" if mustBeDate(minValue) isnt false and compareValue < minValue return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be greater than or equals to #{moment(minValue).format(momentFormat)}" when 'time' if mustBeNumber(value) is false then return result if value < 0 or value > 86400000 return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be agreater then 0 and less then 86400000" when 'email' if mustBeObject(value) is false then return result if mustBeString(value.address) is false then return result if mustBeStringOrNull(value.type) is false then return result if regexUtils.email.test(value.address) is false return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.address must be a valid email" value.address = value.address.toLowerCase() when 'url' if mustBeString(value) is false then return result if regexUtils.url.test(value) is false return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be a valid url" when 'personName' if mustBeObject(value) is false then return result keys = ['prefix', 'first', 'middle', 'last', 'sufix'] removeUnauthorizedKeys value, keys fullName = [] for key in keys if mustBeStringOrNull(value[key], "#{fieldName}.#{key}") is false then return result if _.isString value[key] value[key] = changeCase.titleCase value[key] fullName.push value[key] value.full = fullName.join ' ' when 'phone' if mustBeObject(value) is false then return result validKeys = ['countryCode', 'phoneNumber', 'extention', 'type'] removeUnauthorizedKeys value, validKeys for validKey in validKeys if _.isNumber value[validKey] value[validKey] = String value[validKey] if _.isString value.countryCode value.countryCode = parseInt value.countryCode if mustBeNumber(value.countryCode, "#{fieldName}.countryCode") is false then return result if mustBeString(value.phoneNumber, "#{fieldName}.phoneNumber") is false then return result if mustBeStringOrNull(value.extention, "#{fieldName}.extention") is false then return result if mustBeStringOrNull(value.extention, "#{fieldName}.type") is false then return result if value.countryCode < 0 or value.countryCode > 999 return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.countryCode must contains 1, 2 or 3 digits" if value.countryCode is 55 and not /^[0-9]{10,12}$/.test value.phoneNumber return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.phoneNumber with countryCode '55' must contains from 10 to 12 digits" when 'geoloc' if mustBeArray(value) is false then return result if value.length isnt 2 or not _.isNumber(value[0]) or not _.isNumber(value[1]) return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be an array with longitude and latitude" when 'money' if mustBeObject(value) is false then return result removeUnauthorizedKeys value, ['currency', 'value'] currencies = ['BRL'] if not _.isString(value.currency) or not value.currency in currencies return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.currency must be one of [#{currencies.join(', ')}]" if not _.isNumber value.value return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.value must be a valid Number" when 'json' if not _.isObject(value) and not _.isArray(value) return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be a valid Array or Object" when 'password' if mustBeString(value) is false then return result value = password.encrypt value when 'encrypted' if mustBeString(value) is false then return result value = crypto.createHash('md5').update(value).digest 'hex' when 'autoNumber' if actionType is 'update' value = undefined else value = metaUtils.getNextCode meta.name, fieldName when 'address' if mustBeObject(value) is false then return result if field.isRequired is true requiredKeys = ['country', 'state', 'city', 'place', 'number'] optionalKeys = ['postalCode', 'district', 'placeType', 'complement', 'type'] else requiredKeys = [] optionalKeys = ['country', 'state', 'city', 'place', 'number', 'postalCode', 'district', 'placeType', 'complement', 'type'] extraKeys = ['geolocation'] removeUnauthorizedKeys value, requiredKeys.concat(optionalKeys).concat(extraKeys) for key in requiredKeys if _.isNumber value[key] value[key] = String value[key] if mustBeString(value[key], "#{fieldName}.#{key}") is false then return result for key in optionalKeys if _.isNumber value[key] value[key] = String value[key] if mustBeStringOrNull(value[key], "#{fieldName}.#{key}") is false then return result if mustBeArrayOrNull(value.geolocation, "#{fieldName}.geolocation") is false then return result if _.isArray(value.geolocation) and (value.geolocation.length isnt 2 or not _.isNumber(value.geolocation[0]) or not _.isNumber(value.geolocation[1])) return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.geolocation must be an array with longitude and latitude" when 'filter' if mustBeObject(value) is false then return result if mustBeValidFilter(value) is false then return result utils.recursiveObject value, (key, value, parent) -> if value?['$date'] parent[key] = new Date value['$date'] when 'composite' if mustBeObject(value) is false then return result if field.compositeType is 'reference' meta = Meta[field.objectRefId] if not meta? return new Meteor.Error 'utils-internal-error', "Document #{field.objectRefId} not found" for key, subValue of value validation = metaUtils.validateAndProcessValueFor meta, key, subValue, actionType, model, value, value, idsToUpdate if validation instanceof Error return validation value[key] = validation when 'lookup', 'inheritLookup' if mustBeObject(value) is false then return result if mustBeString(value._id, "#{fieldName}._id") is false then return result lookupModel = Models[field.document] if not lookupModel? return new Meteor.Error 'utils-internal-error', "Document #{field.document} not found" query = _id: value._id record = lookupModel.findOne(query) if not record? return new Meteor.Error 'utils-internal-error', "Record not found for field #{fieldName} with _id [#{value._id}] on document [#{field.document}]" lookupUtils.copyDescriptionAndInheritedFields field, value, record, meta, actionType, model, objectOriginalValues, objectNewValues, idsToUpdate # when 'masked' # when 'calculated' when 'file' if mustBeObject(value) is false then return result keys = ['key', 'name', 'size', 'created', 'etag', 'headers', 'kind', 'last_modified', 'description', 'label', 'wildcard'] removeUnauthorizedKeys value, keys else e = new Meteor.Error 'utils-internal-error', "Field #{fieldName} of type #{field.type} can not be validated" NotifyErrors.notify 'ValidateError', e return e return value if field.isList isnt true return validate value if not _.isArray value if value? value = [value] else return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be array" for item, index in value value[index] = validate item if value[index] instanceof Error return value[index] return value metaUtils.getNextUserFromQueue = (queueStrId, user) -> # Get Collection collection = Models.QueueUser._getCollection() # Create sync version of findAndModify in scope of collection findAndModify = Meteor.wrapAsync _.bind(collection.findAndModify, collection) # Mount query, sort, update, and options query = 'queue._id': queueStrId sort = count: 1 order: 1 update = $inc: count: 1 $set: _updatedAt: new Date _updatedBy: _id: user._id name: user.name group: user.group options = 'new': true # Execute findAndModify queueUser = findAndModify query, sort, update, options if not _.isObject queueUser queueUser = Models.Queue.findOne queueStrId if queueUser?._user?[0]? return { user: queueUser._user[0] } return undefined # ConvertIds utils.convertObjectIdsToFn queueUser, (id) -> id.valueOf() # Return queueUser return queueUser metaUtils.getNextCode = (documentName, fieldName) -> meta = Meta[documentName] fieldName ?= 'code' # Get Collection collection = Models["#{documentName}.AutoNumber"]._getCollection() # Force autoNumber record to exists Models["#{documentName}.AutoNumber"].upsert {_id: fieldName}, {$set: {_id: fieldName}} # Create sync version of findAndModify in scope of collection findAndModify = Meteor.wrapAsync _.bind(collection.findAndModify, collection) # Mount query, sort, update, and options query = _id: fieldName sort = {} update = $inc: next_val: 1 options = 'new': true # Try to get next code try result = findAndModify query, sort, update, options if result and result.next_val return result.next_val catch e throw err # If no results return 0 return 0 ### Populate passed data with more lookup information @param {String} documentName @param {Object} data @param {Object} fields An Object with names of fields to populate with witch fields to populate @example metaUtils.populateLookupsData('Recruitment', record, {job: {code: 1}, contact: {code: 1, name: 1}}) ### metaUtils.populateLookupsData = (documentName, data, fields) -> check fields, Object meta = Meta[documentName] for fieldName, field of meta.fields when field.type is 'lookup' and data[fieldName]? and fields[fieldName]? options = {} if Match.test fields[fieldName], Object options.fields = fields[fieldName] if field.isList isnt true data[fieldName] = Models[field.document].findOne({_id: data[fieldName]._id}, options) else ids = data[fieldName]?.map (item) -> return item._id if ids.length > 0 data[fieldName] = Models[field.document].find({_id: $in: ids}, options).fetch() return data
116806
crypto = Npm.require 'crypto' metaUtils = {} metaUtils.validateAndProcessValueFor = (meta, fieldName, value, actionType, model, objectOriginalValues, objectNewValues, idsToUpdate) -> field = meta.fields[fieldName] if not field? return new Meteor.Error 'utils-internal-error', "Field #{fieldName} does not exists on #{meta._id}" # Validate required fields if field.isRequired is true and not value? return new Meteor.Error 'utils-internal-error', "O Campo '#{fieldName}' é obrigatório, mas não está presente no dado." # Validate List fields if field.isList is true if field.maxElements? and field.maxElements > 0 if not _.isArray(value) or value.length > field.maxElements return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be array with the maximum of #{field.maxElements} item(s)" if field.minElements? and field.minElements > 0 if not _.isArray(value) or value.length < field.minElements return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be array with at least #{field.minElements} item(s)" if field.isAllowDuplicates is false and _.isArray(value) for itemA in value for itemB in value if utils.deepEqual(itemA, itemB) is true return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be array no duplicated values" # Validate picklist min selected if field.type is 'picklist' if _.isNumber(field.minSelected) if field.minSelected is 1 if not value? or (_.isArray(value) and value.length is 0) return new Meteor.Error 'utils-internal-error', "A lista de escolha '#{fieldName}' exige o mínimo de 1 valores selecionados. Mas não está presente no dado." if actionType is 'update' and not value? and field.type is 'lookup' lookupUtils.removeInheritedFields field, objectNewValues if not value? and field.type isnt 'autoNumber' return value # If field is Unique verify if exists another record on db with same value if value? and field.isUnique is true and field.type isnt 'autoNumber' query = {} query[fieldName] = value multiUpdate = idsToUpdate?.length > 1 # If is a single update exclude self record in verification if actionType is 'update' and multiUpdate isnt true query._id = $ne: idsToUpdate[0] count = model.find(query).count() if count > 0 return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be unique" result = true removeUnauthorizedKeys = (obj, keys, path) -> objKeys = Object.keys obj unauthorizedKeys = objKeys.filter (key) -> return keys.indexOf(key) is -1 for key in unauthorizedKeys delete obj[key] return obj mustBeValidFilter = (v) -> if not v.match in ['and', 'or'] result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains a property named 'match' with one of values ['and', 'or']" return false if _.isArray(v.conditions) objectOfConditions = {} for condition in v.conditions objectOfConditions[condition.term.replace(/\./g, ':') + ':' + condition.operator] = condition v.conditions = objectOfConditions if not _.isObject(v.conditions) result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains a property named 'conditions' of type Object with at least 1 item" return false for key, condition of v.conditions if mustBeString(condition.term) is false or mustBeString(condition.operator) is false result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains conditions with properties 'term' and 'operator' of type String" return false operators = ['exists', 'equals', 'not_equals', 'in', 'not_in', 'contains', 'not_contains', 'starts_with', 'end_with', 'less_than', 'greater_than', 'less_or_equals', 'greater_or_equals', 'between'] if not condition.operator in operators result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains conditions with valid operators such as [#{operators.join(', ')}]" return false if not condition.value? result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains conditions property named 'value'" return false if _.isArray(v.filters) for filter in v.filters if mustBeValidFilter(filter) is false return false mustBeString = (v, path) -> if not _.isString v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid String" return false mustBeStringOrNull = (v, path) -> if not v? then return true return mustBeString v, path mustBeNumber = (v, path) -> if not _.isNumber v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid Number" return false mustBeNumberOrNull = (v, path) -> if not v? then return true return mustBeNumber v, path mustBeBoolean = (v, path) -> if not _.isBoolean v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid Boolean" return false mustBeBooleanOrNull = (v, path) -> if not v? then return true return mustBeBoolean v, path mustBeObject = (v, path) -> if not _.isObject v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid Object" return false mustBeObjectOrNull = (v, path) -> if not v? then return true return mustBeObject v, path mustBeArray = (v, path) -> if not _.isArray v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid Array" return false mustBeArrayOrNull = (v, path) -> if not v? then return true return mustBeArray v, path mustBeDate = (v, path) -> date = new Date v if isNaN date result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid string or number representation of date" return false mustBeDateOrNull = (v, path) -> if not v? then return true return mustBeDate v, path validate = (value) -> switch field.type when 'boolean' if mustBeBoolean(value) is false then return result when 'number', 'percentage' if mustBeNumber(value) is false then return result if _.isNumber(field.maxValue) and value > field.maxValue return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be less than #{field.maxValue}" if _.isNumber(field.minValue) and value < field.minValue return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be greater than #{field.minValue}" when 'picklist' if _.isNumber(field.maxSelected) and field.maxSelected > 1 if mustBeArray(value) is false then return result if value.length > field.maxSelected return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be an array with max of #{field.maxSelected} item(s)" if _.isNumber(field.minSelected) and field.minSelected > 0 if value.length < field.minSelected return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be an array with min of #{field.minSelected} item(s)" valuesToVerify = [].concat value for valueToVerify in valuesToVerify if not field.options[valueToVerify]? return new Meteor.Error 'utils-internal-error', "Value #{valueToVerify} for field #{fieldName} is invalid" when 'text', 'richText' if _.isNumber value value = String value if mustBeString(value) is false then return result if field.normalization? and changeCase["#{field.normalization}Case"]? value = changeCase["#{field.normalization}Case"] value if _.isNumber(field.size) and field.size > 0 if value.length > field.size return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be smaller than #{field.size}" when 'dateTime', 'date' if mustBeObject(value) is false then return result if mustBeDate((value.$date || value), "#{fieldName}.$date") is false then return result value = new Date(value.$date || value) if field.maxValue? or field.minValue? compareValue = new Date(value) maxValue = field.maxValue minValue = field.minValue if field.type is 'date' compareValue.setHours(0) compareValue.setMinutes(0) compareValue.setSeconds(0) compareValue.setMilliseconds(0) if maxValue? and maxValue is '$now' maxValue = new Date() if field.type is 'date' maxValue.setHours(0) maxValue.setMinutes(0) maxValue.setSeconds(0) maxValue.setMilliseconds(0) if minValue? and minValue is '$now' minValue = new Date() if field.type is 'date' minValue.setHours(0) minValue.setMinutes(0) minValue.setSeconds(0) minValue.setMilliseconds(0) if field.type is 'date' momentFormat = 'DD/MM/YYYY' else momentFormat = 'DD/MM/YYYY HH:mm:ss' if mustBeDate(maxValue) isnt false and compareValue > maxValue return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be less than or equals to #{moment(maxValue).format(momentFormat)}" if mustBeDate(minValue) isnt false and compareValue < minValue return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be greater than or equals to #{moment(minValue).format(momentFormat)}" when 'time' if mustBeNumber(value) is false then return result if value < 0 or value > 86400000 return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be agreater then 0 and less then 86400000" when 'email' if mustBeObject(value) is false then return result if mustBeString(value.address) is false then return result if mustBeStringOrNull(value.type) is false then return result if regexUtils.email.test(value.address) is false return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.address must be a valid email" value.address = value.address.toLowerCase() when 'url' if mustBeString(value) is false then return result if regexUtils.url.test(value) is false return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be a valid url" when 'personName' if mustBeObject(value) is false then return result keys = ['<KEY>'] removeUnauthorizedKeys value, keys fullName = [] for key in keys if mustBeStringOrNull(value[key], "#{fieldName}.#{key}") is false then return result if _.isString value[key] value[key] = changeCase.titleCase value[key] fullName.push value[key] value.full = fullName.join ' ' when 'phone' if mustBeObject(value) is false then return result validKeys = ['<KEY>', '<KEY>', 'extention', 'type'] removeUnauthorizedKeys value, validKeys for validKey in validKeys if _.isNumber value[validKey] value[validKey] = String value[validKey] if _.isString value.countryCode value.countryCode = parseInt value.countryCode if mustBeNumber(value.countryCode, "#{fieldName}.countryCode") is false then return result if mustBeString(value.phoneNumber, "#{fieldName}.phoneNumber") is false then return result if mustBeStringOrNull(value.extention, "#{fieldName}.extention") is false then return result if mustBeStringOrNull(value.extention, "#{fieldName}.type") is false then return result if value.countryCode < 0 or value.countryCode > 999 return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.countryCode must contains 1, 2 or 3 digits" if value.countryCode is 55 and not /^[0-9]{10,12}$/.test value.phoneNumber return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.phoneNumber with countryCode '55' must contains from 10 to 12 digits" when 'geoloc' if mustBeArray(value) is false then return result if value.length isnt 2 or not _.isNumber(value[0]) or not _.isNumber(value[1]) return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be an array with longitude and latitude" when 'money' if mustBeObject(value) is false then return result removeUnauthorizedKeys value, ['currency', 'value'] currencies = ['BRL'] if not _.isString(value.currency) or not value.currency in currencies return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.currency must be one of [#{currencies.join(', ')}]" if not _.isNumber value.value return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.value must be a valid Number" when 'json' if not _.isObject(value) and not _.isArray(value) return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be a valid Array or Object" when 'password' if mustBeString(value) is false then return result value = password.encrypt value when 'encrypted' if mustBeString(value) is false then return result value = crypto.createHash('md5').update(value).digest 'hex' when 'autoNumber' if actionType is 'update' value = undefined else value = metaUtils.getNextCode meta.name, fieldName when 'address' if mustBeObject(value) is false then return result if field.isRequired is true requiredKeys = ['<KEY>', '<KEY>', '<KEY>', 'place', 'number'] optionalKeys = ['postalCode', 'district', 'placeType', 'complement', 'type'] else requiredKeys = [] optionalKeys = ['country', 'state', 'city', 'place', 'number', 'postalCode', 'district', 'placeType', 'complement', 'type'] extraKeys = ['<KEY>'] removeUnauthorizedKeys value, requiredKeys.concat(optionalKeys).concat(extraKeys) for key in requiredKeys if _.isNumber value[key] value[key] = String value[key] if mustBeString(value[key], "#{fieldName}.#{key}") is false then return result for key in optionalKeys if _.isNumber value[key] value[key] = String value[key] if mustBeStringOrNull(value[key], "#{fieldName}.#{key}") is false then return result if mustBeArrayOrNull(value.geolocation, "#{fieldName}.geolocation") is false then return result if _.isArray(value.geolocation) and (value.geolocation.length isnt 2 or not _.isNumber(value.geolocation[0]) or not _.isNumber(value.geolocation[1])) return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.geolocation must be an array with longitude and latitude" when 'filter' if mustBeObject(value) is false then return result if mustBeValidFilter(value) is false then return result utils.recursiveObject value, (key, value, parent) -> if value?['$date'] parent[key] = new Date value['$date'] when 'composite' if mustBeObject(value) is false then return result if field.compositeType is 'reference' meta = Meta[field.objectRefId] if not meta? return new Meteor.Error 'utils-internal-error', "Document #{field.objectRefId} not found" for key, subValue of value validation = metaUtils.validateAndProcessValueFor meta, key, subValue, actionType, model, value, value, idsToUpdate if validation instanceof Error return validation value[key] = validation when 'lookup', 'inheritLookup' if mustBeObject(value) is false then return result if mustBeString(value._id, "#{fieldName}._id") is false then return result lookupModel = Models[field.document] if not lookupModel? return new Meteor.Error 'utils-internal-error', "Document #{field.document} not found" query = _id: value._id record = lookupModel.findOne(query) if not record? return new Meteor.Error 'utils-internal-error', "Record not found for field #{fieldName} with _id [#{value._id}] on document [#{field.document}]" lookupUtils.copyDescriptionAndInheritedFields field, value, record, meta, actionType, model, objectOriginalValues, objectNewValues, idsToUpdate # when 'masked' # when 'calculated' when 'file' if mustBeObject(value) is false then return result keys = ['<KEY>'] removeUnauthorizedKeys value, keys else e = new Meteor.Error 'utils-internal-error', "Field #{fieldName} of type #{field.type} can not be validated" NotifyErrors.notify 'ValidateError', e return e return value if field.isList isnt true return validate value if not _.isArray value if value? value = [value] else return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be array" for item, index in value value[index] = validate item if value[index] instanceof Error return value[index] return value metaUtils.getNextUserFromQueue = (queueStrId, user) -> # Get Collection collection = Models.QueueUser._getCollection() # Create sync version of findAndModify in scope of collection findAndModify = Meteor.wrapAsync _.bind(collection.findAndModify, collection) # Mount query, sort, update, and options query = 'queue._id': queueStrId sort = count: 1 order: 1 update = $inc: count: 1 $set: _updatedAt: new Date _updatedBy: _id: user._id name: user.name group: user.group options = 'new': true # Execute findAndModify queueUser = findAndModify query, sort, update, options if not _.isObject queueUser queueUser = Models.Queue.findOne queueStrId if queueUser?._user?[0]? return { user: queueUser._user[0] } return undefined # ConvertIds utils.convertObjectIdsToFn queueUser, (id) -> id.valueOf() # Return queueUser return queueUser metaUtils.getNextCode = (documentName, fieldName) -> meta = Meta[documentName] fieldName ?= 'code' # Get Collection collection = Models["#{documentName}.AutoNumber"]._getCollection() # Force autoNumber record to exists Models["#{documentName}.AutoNumber"].upsert {_id: fieldName}, {$set: {_id: fieldName}} # Create sync version of findAndModify in scope of collection findAndModify = Meteor.wrapAsync _.bind(collection.findAndModify, collection) # Mount query, sort, update, and options query = _id: fieldName sort = {} update = $inc: next_val: 1 options = 'new': true # Try to get next code try result = findAndModify query, sort, update, options if result and result.next_val return result.next_val catch e throw err # If no results return 0 return 0 ### Populate passed data with more lookup information @param {String} documentName @param {Object} data @param {Object} fields An Object with names of fields to populate with witch fields to populate @example metaUtils.populateLookupsData('Recruitment', record, {job: {code: 1}, contact: {code: 1, name: 1}}) ### metaUtils.populateLookupsData = (documentName, data, fields) -> check fields, Object meta = Meta[documentName] for fieldName, field of meta.fields when field.type is 'lookup' and data[fieldName]? and fields[fieldName]? options = {} if Match.test fields[fieldName], Object options.fields = fields[fieldName] if field.isList isnt true data[fieldName] = Models[field.document].findOne({_id: data[fieldName]._id}, options) else ids = data[fieldName]?.map (item) -> return item._id if ids.length > 0 data[fieldName] = Models[field.document].find({_id: $in: ids}, options).fetch() return data
true
crypto = Npm.require 'crypto' metaUtils = {} metaUtils.validateAndProcessValueFor = (meta, fieldName, value, actionType, model, objectOriginalValues, objectNewValues, idsToUpdate) -> field = meta.fields[fieldName] if not field? return new Meteor.Error 'utils-internal-error', "Field #{fieldName} does not exists on #{meta._id}" # Validate required fields if field.isRequired is true and not value? return new Meteor.Error 'utils-internal-error', "O Campo '#{fieldName}' é obrigatório, mas não está presente no dado." # Validate List fields if field.isList is true if field.maxElements? and field.maxElements > 0 if not _.isArray(value) or value.length > field.maxElements return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be array with the maximum of #{field.maxElements} item(s)" if field.minElements? and field.minElements > 0 if not _.isArray(value) or value.length < field.minElements return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be array with at least #{field.minElements} item(s)" if field.isAllowDuplicates is false and _.isArray(value) for itemA in value for itemB in value if utils.deepEqual(itemA, itemB) is true return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be array no duplicated values" # Validate picklist min selected if field.type is 'picklist' if _.isNumber(field.minSelected) if field.minSelected is 1 if not value? or (_.isArray(value) and value.length is 0) return new Meteor.Error 'utils-internal-error', "A lista de escolha '#{fieldName}' exige o mínimo de 1 valores selecionados. Mas não está presente no dado." if actionType is 'update' and not value? and field.type is 'lookup' lookupUtils.removeInheritedFields field, objectNewValues if not value? and field.type isnt 'autoNumber' return value # If field is Unique verify if exists another record on db with same value if value? and field.isUnique is true and field.type isnt 'autoNumber' query = {} query[fieldName] = value multiUpdate = idsToUpdate?.length > 1 # If is a single update exclude self record in verification if actionType is 'update' and multiUpdate isnt true query._id = $ne: idsToUpdate[0] count = model.find(query).count() if count > 0 return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be unique" result = true removeUnauthorizedKeys = (obj, keys, path) -> objKeys = Object.keys obj unauthorizedKeys = objKeys.filter (key) -> return keys.indexOf(key) is -1 for key in unauthorizedKeys delete obj[key] return obj mustBeValidFilter = (v) -> if not v.match in ['and', 'or'] result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains a property named 'match' with one of values ['and', 'or']" return false if _.isArray(v.conditions) objectOfConditions = {} for condition in v.conditions objectOfConditions[condition.term.replace(/\./g, ':') + ':' + condition.operator] = condition v.conditions = objectOfConditions if not _.isObject(v.conditions) result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains a property named 'conditions' of type Object with at least 1 item" return false for key, condition of v.conditions if mustBeString(condition.term) is false or mustBeString(condition.operator) is false result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains conditions with properties 'term' and 'operator' of type String" return false operators = ['exists', 'equals', 'not_equals', 'in', 'not_in', 'contains', 'not_contains', 'starts_with', 'end_with', 'less_than', 'greater_than', 'less_or_equals', 'greater_or_equals', 'between'] if not condition.operator in operators result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains conditions with valid operators such as [#{operators.join(', ')}]" return false if not condition.value? result = new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must contains conditions property named 'value'" return false if _.isArray(v.filters) for filter in v.filters if mustBeValidFilter(filter) is false return false mustBeString = (v, path) -> if not _.isString v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid String" return false mustBeStringOrNull = (v, path) -> if not v? then return true return mustBeString v, path mustBeNumber = (v, path) -> if not _.isNumber v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid Number" return false mustBeNumberOrNull = (v, path) -> if not v? then return true return mustBeNumber v, path mustBeBoolean = (v, path) -> if not _.isBoolean v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid Boolean" return false mustBeBooleanOrNull = (v, path) -> if not v? then return true return mustBeBoolean v, path mustBeObject = (v, path) -> if not _.isObject v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid Object" return false mustBeObjectOrNull = (v, path) -> if not v? then return true return mustBeObject v, path mustBeArray = (v, path) -> if not _.isArray v result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid Array" return false mustBeArrayOrNull = (v, path) -> if not v? then return true return mustBeArray v, path mustBeDate = (v, path) -> date = new Date v if isNaN date result = new Meteor.Error 'utils-internal-error', "Value for field #{path or fieldName} must be a valid string or number representation of date" return false mustBeDateOrNull = (v, path) -> if not v? then return true return mustBeDate v, path validate = (value) -> switch field.type when 'boolean' if mustBeBoolean(value) is false then return result when 'number', 'percentage' if mustBeNumber(value) is false then return result if _.isNumber(field.maxValue) and value > field.maxValue return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be less than #{field.maxValue}" if _.isNumber(field.minValue) and value < field.minValue return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be greater than #{field.minValue}" when 'picklist' if _.isNumber(field.maxSelected) and field.maxSelected > 1 if mustBeArray(value) is false then return result if value.length > field.maxSelected return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be an array with max of #{field.maxSelected} item(s)" if _.isNumber(field.minSelected) and field.minSelected > 0 if value.length < field.minSelected return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be an array with min of #{field.minSelected} item(s)" valuesToVerify = [].concat value for valueToVerify in valuesToVerify if not field.options[valueToVerify]? return new Meteor.Error 'utils-internal-error', "Value #{valueToVerify} for field #{fieldName} is invalid" when 'text', 'richText' if _.isNumber value value = String value if mustBeString(value) is false then return result if field.normalization? and changeCase["#{field.normalization}Case"]? value = changeCase["#{field.normalization}Case"] value if _.isNumber(field.size) and field.size > 0 if value.length > field.size return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be smaller than #{field.size}" when 'dateTime', 'date' if mustBeObject(value) is false then return result if mustBeDate((value.$date || value), "#{fieldName}.$date") is false then return result value = new Date(value.$date || value) if field.maxValue? or field.minValue? compareValue = new Date(value) maxValue = field.maxValue minValue = field.minValue if field.type is 'date' compareValue.setHours(0) compareValue.setMinutes(0) compareValue.setSeconds(0) compareValue.setMilliseconds(0) if maxValue? and maxValue is '$now' maxValue = new Date() if field.type is 'date' maxValue.setHours(0) maxValue.setMinutes(0) maxValue.setSeconds(0) maxValue.setMilliseconds(0) if minValue? and minValue is '$now' minValue = new Date() if field.type is 'date' minValue.setHours(0) minValue.setMinutes(0) minValue.setSeconds(0) minValue.setMilliseconds(0) if field.type is 'date' momentFormat = 'DD/MM/YYYY' else momentFormat = 'DD/MM/YYYY HH:mm:ss' if mustBeDate(maxValue) isnt false and compareValue > maxValue return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be less than or equals to #{moment(maxValue).format(momentFormat)}" if mustBeDate(minValue) isnt false and compareValue < minValue return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be greater than or equals to #{moment(minValue).format(momentFormat)}" when 'time' if mustBeNumber(value) is false then return result if value < 0 or value > 86400000 return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be agreater then 0 and less then 86400000" when 'email' if mustBeObject(value) is false then return result if mustBeString(value.address) is false then return result if mustBeStringOrNull(value.type) is false then return result if regexUtils.email.test(value.address) is false return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.address must be a valid email" value.address = value.address.toLowerCase() when 'url' if mustBeString(value) is false then return result if regexUtils.url.test(value) is false return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be a valid url" when 'personName' if mustBeObject(value) is false then return result keys = ['PI:KEY:<KEY>END_PI'] removeUnauthorizedKeys value, keys fullName = [] for key in keys if mustBeStringOrNull(value[key], "#{fieldName}.#{key}") is false then return result if _.isString value[key] value[key] = changeCase.titleCase value[key] fullName.push value[key] value.full = fullName.join ' ' when 'phone' if mustBeObject(value) is false then return result validKeys = ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'extention', 'type'] removeUnauthorizedKeys value, validKeys for validKey in validKeys if _.isNumber value[validKey] value[validKey] = String value[validKey] if _.isString value.countryCode value.countryCode = parseInt value.countryCode if mustBeNumber(value.countryCode, "#{fieldName}.countryCode") is false then return result if mustBeString(value.phoneNumber, "#{fieldName}.phoneNumber") is false then return result if mustBeStringOrNull(value.extention, "#{fieldName}.extention") is false then return result if mustBeStringOrNull(value.extention, "#{fieldName}.type") is false then return result if value.countryCode < 0 or value.countryCode > 999 return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.countryCode must contains 1, 2 or 3 digits" if value.countryCode is 55 and not /^[0-9]{10,12}$/.test value.phoneNumber return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.phoneNumber with countryCode '55' must contains from 10 to 12 digits" when 'geoloc' if mustBeArray(value) is false then return result if value.length isnt 2 or not _.isNumber(value[0]) or not _.isNumber(value[1]) return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be an array with longitude and latitude" when 'money' if mustBeObject(value) is false then return result removeUnauthorizedKeys value, ['currency', 'value'] currencies = ['BRL'] if not _.isString(value.currency) or not value.currency in currencies return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.currency must be one of [#{currencies.join(', ')}]" if not _.isNumber value.value return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.value must be a valid Number" when 'json' if not _.isObject(value) and not _.isArray(value) return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be a valid Array or Object" when 'password' if mustBeString(value) is false then return result value = password.encrypt value when 'encrypted' if mustBeString(value) is false then return result value = crypto.createHash('md5').update(value).digest 'hex' when 'autoNumber' if actionType is 'update' value = undefined else value = metaUtils.getNextCode meta.name, fieldName when 'address' if mustBeObject(value) is false then return result if field.isRequired is true requiredKeys = ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'place', 'number'] optionalKeys = ['postalCode', 'district', 'placeType', 'complement', 'type'] else requiredKeys = [] optionalKeys = ['country', 'state', 'city', 'place', 'number', 'postalCode', 'district', 'placeType', 'complement', 'type'] extraKeys = ['PI:KEY:<KEY>END_PI'] removeUnauthorizedKeys value, requiredKeys.concat(optionalKeys).concat(extraKeys) for key in requiredKeys if _.isNumber value[key] value[key] = String value[key] if mustBeString(value[key], "#{fieldName}.#{key}") is false then return result for key in optionalKeys if _.isNumber value[key] value[key] = String value[key] if mustBeStringOrNull(value[key], "#{fieldName}.#{key}") is false then return result if mustBeArrayOrNull(value.geolocation, "#{fieldName}.geolocation") is false then return result if _.isArray(value.geolocation) and (value.geolocation.length isnt 2 or not _.isNumber(value.geolocation[0]) or not _.isNumber(value.geolocation[1])) return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName}.geolocation must be an array with longitude and latitude" when 'filter' if mustBeObject(value) is false then return result if mustBeValidFilter(value) is false then return result utils.recursiveObject value, (key, value, parent) -> if value?['$date'] parent[key] = new Date value['$date'] when 'composite' if mustBeObject(value) is false then return result if field.compositeType is 'reference' meta = Meta[field.objectRefId] if not meta? return new Meteor.Error 'utils-internal-error', "Document #{field.objectRefId} not found" for key, subValue of value validation = metaUtils.validateAndProcessValueFor meta, key, subValue, actionType, model, value, value, idsToUpdate if validation instanceof Error return validation value[key] = validation when 'lookup', 'inheritLookup' if mustBeObject(value) is false then return result if mustBeString(value._id, "#{fieldName}._id") is false then return result lookupModel = Models[field.document] if not lookupModel? return new Meteor.Error 'utils-internal-error', "Document #{field.document} not found" query = _id: value._id record = lookupModel.findOne(query) if not record? return new Meteor.Error 'utils-internal-error', "Record not found for field #{fieldName} with _id [#{value._id}] on document [#{field.document}]" lookupUtils.copyDescriptionAndInheritedFields field, value, record, meta, actionType, model, objectOriginalValues, objectNewValues, idsToUpdate # when 'masked' # when 'calculated' when 'file' if mustBeObject(value) is false then return result keys = ['PI:KEY:<KEY>END_PI'] removeUnauthorizedKeys value, keys else e = new Meteor.Error 'utils-internal-error', "Field #{fieldName} of type #{field.type} can not be validated" NotifyErrors.notify 'ValidateError', e return e return value if field.isList isnt true return validate value if not _.isArray value if value? value = [value] else return new Meteor.Error 'utils-internal-error', "Value for field #{fieldName} must be array" for item, index in value value[index] = validate item if value[index] instanceof Error return value[index] return value metaUtils.getNextUserFromQueue = (queueStrId, user) -> # Get Collection collection = Models.QueueUser._getCollection() # Create sync version of findAndModify in scope of collection findAndModify = Meteor.wrapAsync _.bind(collection.findAndModify, collection) # Mount query, sort, update, and options query = 'queue._id': queueStrId sort = count: 1 order: 1 update = $inc: count: 1 $set: _updatedAt: new Date _updatedBy: _id: user._id name: user.name group: user.group options = 'new': true # Execute findAndModify queueUser = findAndModify query, sort, update, options if not _.isObject queueUser queueUser = Models.Queue.findOne queueStrId if queueUser?._user?[0]? return { user: queueUser._user[0] } return undefined # ConvertIds utils.convertObjectIdsToFn queueUser, (id) -> id.valueOf() # Return queueUser return queueUser metaUtils.getNextCode = (documentName, fieldName) -> meta = Meta[documentName] fieldName ?= 'code' # Get Collection collection = Models["#{documentName}.AutoNumber"]._getCollection() # Force autoNumber record to exists Models["#{documentName}.AutoNumber"].upsert {_id: fieldName}, {$set: {_id: fieldName}} # Create sync version of findAndModify in scope of collection findAndModify = Meteor.wrapAsync _.bind(collection.findAndModify, collection) # Mount query, sort, update, and options query = _id: fieldName sort = {} update = $inc: next_val: 1 options = 'new': true # Try to get next code try result = findAndModify query, sort, update, options if result and result.next_val return result.next_val catch e throw err # If no results return 0 return 0 ### Populate passed data with more lookup information @param {String} documentName @param {Object} data @param {Object} fields An Object with names of fields to populate with witch fields to populate @example metaUtils.populateLookupsData('Recruitment', record, {job: {code: 1}, contact: {code: 1, name: 1}}) ### metaUtils.populateLookupsData = (documentName, data, fields) -> check fields, Object meta = Meta[documentName] for fieldName, field of meta.fields when field.type is 'lookup' and data[fieldName]? and fields[fieldName]? options = {} if Match.test fields[fieldName], Object options.fields = fields[fieldName] if field.isList isnt true data[fieldName] = Models[field.document].findOne({_id: data[fieldName]._id}, options) else ids = data[fieldName]?.map (item) -> return item._id if ids.length > 0 data[fieldName] = Models[field.document].find({_id: $in: ids}, options).fetch() return data
[ { "context": "mfabrik GmbH\n * MIT Licence\n * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org\n#", "end": 166, "score": 0.9852844476699829, "start": 152, "tag": "USERNAME", "value": "programmfabrik" }, { "context": "tRoot()?[key] or null\n\n\tgetSelectedNodeKey: ->\n\t\t\"selectedNode\"\n\n\tselect: (event) ->\n\t\tdeferred = new CUI.Deferr", "end": 17024, "score": 0.9650671482086182, "start": 17012, "tag": "KEY", "value": "selectedNode" } ]
src/elements/ListView/ListViewTreeNode.coffee
programmfabrik/coffeescript-ui
10
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### class CUI.ListViewTreeNode extends CUI.ListViewRow initOpts: -> super() @addOpts children: check: Array open: check: Boolean html: {} colspan: check: (v) -> v > 0 getChildren: check: Function readOpts: -> super() @setColspan(@_colspan) if @_children @children = @opts.children @initChildren() if @_open @do_open = true else @do_open = false @is_open = false @html = @_html @__loadingDeferred = null setColspan: (@colspan) -> getColspan: -> @colspan # overwrite with Method getChildren: null # overwrite with Method hasChildren: null isLeaf: -> leaf = (if @children false else if @opts.getChildren false else if @getChildren if @opts.leaf or (@hasChildren and not @hasChildren()) true else false else true) # console.debug CUI.util.getObjectClass(@), "isLeaf?",leaf, @hasChildren?(), @opts.leaf, @ leaf getClass: -> cls = super() cls = cls + " cui-lv-tree-node" if not @isLeaf() cls = cls + " cui-lv-tree-node--is-branch" cls isSelectable: -> @getTree?().isSelectable() and @__selectable and not @isRoot() getFather: -> @father setFather: (new_father) -> CUI.util.assert(new_father == null or new_father instanceof CUI.ListViewTreeNode, "#{CUI.util.getObjectClass(@)}.setFather", "father can only be null or instanceof CUI.ListViewTreeNode", father: new_father) CUI.util.assert(new_father != @, "#{CUI.util.getObjectClass(@)}.setFather", "father cannot be self", node: @, father: new_father) # console.debug @, new_father if new_father CUI.util.assert(@ not in new_father.getPath(true), "#{CUI.util.getObjectClass(@)}.setFather", "father cannot any of the node's children", node: @, father: new_father) if not new_father and @selected @setSelectedNode(null) @selected = false if @father and not new_father # copy tree, since we are a new root node tree = @getTree() @father = new_father if tree @setTree(tree) else @father = new_father # if @children # for c in @children # c.setFather(@) @ isRoot: -> not @father setTree: (@tree) -> CUI.util.assert(@isRoot(), "#{CUI.util.getObjectClass(@)}.setTree", "node must be root node to set tree", tree: @tree, opts: @opts) CUI.util.assert(@tree instanceof CUI.ListViewTree, "#{CUI.util.getObjectClass(@)}.setTree", "tree must be instance of ListViewTree", tree: @tree, opts: @opts) getRoot: (call=0) -> CUI.util.assert(call < 100, "ListViewTreeNode.getRoot", "Recursion detected.") if @father @father.getRoot(call+1) else @ dump: (lines=[], depth=0) -> padding = [] for pad in [0...depth] padding.push(" ") lines.push(padding.join("")+@dumpString()) if @children for c in @children c.dump(lines, depth+1) if depth==0 return "\n"+lines.join("\n")+"\n" dumpString: -> @getNodeId() getTree: (call=0) -> CUI.util.assert(call < 100, "ListViewTreeNode.getTree", "Recursion detected.") if @isRoot() @tree else @getRoot().getTree(call+1) # find tree nodes, using the provided compare # function find: (eq_func=null, nodes=[]) -> if not eq_func or eq_func.call(@, @) nodes.push(@) if @children for c in @children c.find(eq_func, nodes) nodes # filters the children by function filter: (filter_func, filtered_nodes = []) -> save_children = @children?.slice(0) if @father and filter_func.call(@, @) # this means we have to be removed and our children # must be attached in our place to our father our_idx = @getChildIdx() filtered_nodes.push(@) father = @getFather() CUI.ListViewTreeNode::remove.call(@, true, false) # keep children array, no de-select for c, idx in save_children father.children.splice(our_idx+idx, 0, c) c.setFather(father) # console.debug "removed ", @, our_idx, save_children if save_children for c in save_children c.filter(filter_func, filtered_nodes) filtered_nodes getPath: (include_self=false, path=[], call=0) -> CUI.util.assert(call < 100, "ListViewTreeNode.getPath", "Recursion detected.") if @father @father.getPath(true, path, call+1) if include_self path.push(@) return path getChildIdx: -> if @isRoot() "root" else ci = @father.children.indexOf(@) CUI.util.assert(ci > -1, "#{CUI.util.getObjectClass(@)}.getChildIdx()", "Node not found in fathers children Array", node: @, father: @father, "father.children": @father.children) ci getNodeId: (include_self=true) -> path = @getPath(include_self) (p.getChildIdx() for p in path).join(".") getOpenChildNodes: (nodes=[]) -> if @children and @is_open for node in @children nodes.push(node) node.getOpenChildNodes(nodes) nodes getRowsToMove: -> @getOpenChildNodes() isRendered: -> if (@isRoot() and @getTree()?.getGrid()) or @__is_rendered true else false sort: (func, level=0) -> if not @children?.length return @children.sort(func) for node in @children node.sort(func, level+1) if level == 0 and @isRendered() @reload() @ close: -> CUI.util.assert(@father, "ListViewTreeNode.close()", "Cannot close root node", node: @) CUI.util.assert(not @isLoading(), "ListViewTreeNode.close", "Cannot close node, during opening...", node: @, tree: @getTree()) @do_open = false if @father.is_open # console.debug "closing node", @node_element @removeFromDOM(false) @replaceSelf() # @getTree().layout() # @element.trigger("tree", type: "close") CUI.resolvedPromise() # remove_self == false only removs children removeFromDOM: (remove_self=true) -> @abortLoading() # console.debug "remove from DOM", @getNodeId(), @is_open, @children?.length, remove_self if @is_open @do_open = true if @children for c in @children c.removeFromDOM() else @do_open = false if remove_self # console.debug "removing ", @getUniqueId(), @getDOMNodes()?[0], @__is_rendered, @getRowIdx() if @__is_rendered tree = @getTree() if tree and not tree.isDestroyed() if @getRowIdx() == null if not @isRoot() tree.removeDeferredRow(@) else tree.removeRow(@getRowIdx()) @__is_rendered = false @is_open = false @ # getElement: -> # @element # replaces node_element with a new render of ourself replaceSelf: -> if @father if tree = @getTree() # layout_stopped = tree.stopLayout() tree.replaceRow(@getRowIdx(), @render()) if @selected tree.rowAddClass(@getRowIdx(), CUI.ListViewRow.defaults.selected_class) # if layout_stopped # tree.startLayout() return CUI.resolvedPromise() else if @is_open # root node @removeFromDOM(false) # tree.removeAllRows() return @open() else return CUI.resolvedPromise() # opens all children and grandchilden openRecursively: -> @__actionRecursively("open") closeRecursively: -> @__actionRecursively("close") __actionRecursively: (action) -> dfr = new CUI.Deferred() if @isLeaf() return dfr.resolve().promise() if action == "open" ret = @getLoading() if not ret ret = @open() else ret = @close() ret.done => promises = [] for child in @children or [] promises.push(child["#{action}Recursively"]()) CUI.when(promises) .done(dfr.resolve) .fail(dfr.reject) .fail(dfr.reject) dfr.promise() isOpen: -> !!@is_open isLoading: -> !!@__loadingDeferred getLoading: -> @__loadingDeferred abortLoading: -> if not @__loadingDeferred return # console.error("ListViewTreeNode.abortLoading: Aborting chunk loading.") if @__loadingDeferred.state == 'pending' @__loadingDeferred.reject() @__loadingDeferred = null return # resolves with the opened node open: -> # we could return loading_deferred here CUI.util.assert(not @isLoading(), "ListViewTreeNode.open", "Cannot open node #{@getUniqueId()}, during opening. This can happen if the same node exists multiple times in the same tree.", node: @) if @is_open or @isLeaf() return CUI.resolvedPromise() # console.error @getUniqueId(), "opening...", "is open:", @is_open, open_counter @is_open = true @do_open = false dfr = @__loadingDeferred = new CUI.Deferred() # console.warn("Start opening", @getUniqueId(), dfr.getUniqueId()) do_resolve = => if @__loadingDeferred.state() == "pending" @__loadingDeferred.resolve(@) @__loadingDeferred = null do_reject = => if @__loadingDeferred.state() == "pending" @__loadingDeferred.reject(@) @__loadingDeferred = null load_children = => CUI.util.assert(CUI.util.isArray(@children), "ListViewTreeNode.open", "children to be loaded must be an Array", children: @children, listViewTreeNode: @) # console.debug @._key, @getUniqueId(), "children loaded", @children.length if @children.length == 0 if not @isRoot() @replaceSelf() do_resolve() return @initChildren() CUI.chunkWork.call @, items: @children chunk_size: 5 timeout: 1 call: (items) => CUI.chunkWork.call @, items: items chunk_size: 1 timeout: -1 call: (_items) => # console.error @getUniqueId(), open_counter, @__open_counter, "chunking work" if dfr != @__loadingDeferred # we are already in a new run, exit return false @__appendNode(_items[0], true) # , false, true)) .done => # console.error @getUniqueId(), open_counter, @__open_counter, "chunking work DONE" if dfr != @__loadingDeferred return if not @isRoot() @replaceSelf() do_resolve() .fail => # console.error @getUniqueId(), open_counter, @__open_counter, "chunking work FAIL" if dfr != @__loadingDeferred return for c in @children c.removeFromDOM() do_reject() return if @children load_children() else func = @opts.getChildren or @getChildren if func ret = func.call(@) if CUI.util.isArray(ret) @children = ret load_children() else CUI.util.assert(CUI.util.isPromise(ret), "#{CUI.util.getObjectClass(@)}.open", "returned children are not of type Promise or Array", children: ret) ret .done (@children) => if dfr != @__loadingDeferred return load_children() return .fail(do_reject) else if not @isRoot() @replaceSelf() do_resolve() dfr.promise() prependChild: (node) -> @addNode(node, false) addChild: (node) -> @addNode(node, true) prependSibling: (node) -> idx = @getChildIdx() @father.addNode(node, idx) appendSibling: (node) -> idx = @getChildIdx()+1 if idx > @father.children.length-1 @father.addNode(node) else @father.addNode(node, idx) setChildren: (@children) -> @initChildren() return initChildren: -> for node, idx in @children for _node, _idx in @children if idx == _idx continue CUI.util.assert(_node != node, "ListViewTreeNode.initChildren", "Must have every child only once.", node: @, child: node) node.setFather(@) return # add node adds the node to our children array and # actually visually appends it to the ListView # however, it does not visually appends it, if the root node # is not yet "open". addNode: (node, append=true) -> CUI.util.assert(not @isLoading(), "ListViewTreeNode.addNode", "Cannot add node, during loading.", node: @) if not @children @children = [] CUI.util.assert(CUI.util.isArray(@children), "Tree.addNode","Cannot add node, children needs to be an Array in node", node: @, new_node: node) for _node in @children CUI.util.assert(_node != node, "ListViewTreeNode.addNode", "Must have every child only once.", node: @, child: _node) if append == true @children.push(node) else @children.splice(append,0,node) node.setFather(@) # if @is_open # # we are already open, append the node # return @__appendNode(node, append) # else # return CUI.resolvedPromise(node) if not @is_open if @isRoot() or not @isRendered() return CUI.resolvedPromise(node) # open us, since we have just added a child node # we need to open us # make sure to return the addedNode dfr = new CUI.Deferred() @open() .done => dfr.resolve(node) .fail => dfr.reject(node) promise = dfr.promise() else # we are already open, so simply append the node promise = @__appendNode(node, append) promise # resolves with the appended node __appendNode: (node, append=true) -> # , assume_open=false) -> CUI.util.assert(node instanceof CUI.ListViewTreeNode, "ListViewTreeNode.__appendNode", "node must be instance of ListViewTreeNode", node: @, new_node: node) CUI.util.assert(node.getFather() == @, "ListViewTreeNode.__appendNode", "node added must be child of current node", node: @, new_node: node) # console.debug ".__appendNode: father: ", @getUniqueId()+"["+@getNodeId()+"]", "child:", node.getUniqueId()+"["+node.getNodeId()+"]" if append == false append = 0 tree = @getTree() if tree?.isDestroyed() return CUI.rejectedPromise(node) if not @isRendered() return CUI.resolvedPromise(node) # console.warn "appendNode", @getUniqueId(), "new:", node.getUniqueId(), "father open:", @getFather()?.isOpen() child_idx = node.getChildIdx() if @isRoot() if append == true or @children.length == 1 or append+1 == @children.length tree.appendRow(node.render()) else CUI.util.assert(@children[append+1], @__cls+".__addNode", "Node not found", children: @children, node: @, append: append) tree.insertRowBefore(@children[append+1].getRowIdx(), node.render()) else if child_idx == 0 # this means the added node is the first child, we # always add this after tree.insertRowAfter(@getRowIdx(), node.render()) else if append != true tree.insertRowBefore(@children[append+1].getRowIdx(), node.render()) else # this last node is the node before us, we need to see # if is is opened and find the last node opened last_node = @children[child_idx-1] child_nodes = last_node.getOpenChildNodes() if child_nodes.length last_node = child_nodes[child_nodes.length-1] # if last_node.getRowIdx() == null # console.error "row index is not there", tree, @is_open, @getNodeId(), child_idx, @children # _last_node = @children[child_idx-1] # console.debug "last node", _last_node, _last_node.isRendered() # console.debug "child nodes", child_nodes, last_node.isRendered() tree.insertRowAfter(last_node.getRowIdx(), node.render()) if node.selected tree.rowAddClass(node.getRowIdx(), CUI.ListViewRow.defaults.selected_class) if node.do_open node.open() else CUI.resolvedPromise(node) remove: (keep_children_array=false, select_after=true) -> dfr = new CUI.Deferred() select_after_node = null remove_node = => # console.debug "remove", @getNodeId(), @father.getNodeId(), @element @removeFromDOM() @father?.removeChild(@, keep_children_array) if tree = @getTree() CUI.Events.trigger node: tree type: "row_removed" if select_after_node select_after_node.select() .done(dfr.resolve).fail(dfr.reject) else dfr.resolve() else dfr.resolve() return if select_after and not @isRoot() children = @getFather().children if children.length > 1 child_idx = @getChildIdx() if child_idx == 0 select_after = 1 else select_after = Math.min(children.length-2, child_idx-1) if select_after != null select_after_node = children[select_after] if @isSelected() @deselect().fail(dfr.reject).done(remove_node) else remove_node() dfr.promise() removeChild: (child, keep_children_array=false) -> CUI.util.removeFromArray(child, @children) if @children.length == 0 and not @isRoot() @is_open = false if not keep_children_array # this hides the "open" icon @children = null # console.error "removeChild...", @children?.length, keep_children_array, @isRoot() @update() child.setFather(null) deselect: (ev, new_node) -> if not @getTree().isSelectable() return CUI.resolvedPromise() @check_deselect(ev, new_node) .done => @setSelectedNode() @removeSelectedClass() @selected = false @getTree().triggerNodeDeselect(ev, @) allowRowMove: -> true check_deselect: (ev, new_node) -> CUI.resolvedPromise() isSelected: -> !!@selected addSelectedClass: -> @getTree().rowAddClass(@getRowIdx(), CUI.ListViewRow.defaults.selected_class) removeSelectedClass: -> @getTree().rowRemoveClass(@getRowIdx(), CUI.ListViewRow.defaults.selected_class) setSelectedNode: (node = null, key = @getSelectedNodeKey()) -> @getRoot()[@getSelectedNodeKey()] = node getSelectedNode: (key = @getSelectedNodeKey()) -> @getRoot()?[key] or null getSelectedNodeKey: -> "selectedNode" select: (event) -> deferred = new CUI.Deferred() if event and @getTree?().isSelectable() event.stopPropagation?() deferred.done => @getTree().triggerNodeSelect(event, @) if not @isSelectable() # console.debug "row is not selectable", "row:", @, "tree:", @getTree() return deferred.reject().promise() if @isSelected() return deferred.resolve().promise() # console.debug "selecting node", sel_node do_select = => @getTree()._onBeforeSelect?(@) @setSelectedNode(@) # console.error "openUpwards", @getNodeId(), @is_open @openUpwards() .done => @addSelectedClass() @selected = true deferred.resolve() .fail(deferred.reject) # the selected node is not us, so we ask the other # node selectedNode = @getSelectedNode() # If selectableRows is 'true' means that only one row can be selected at the same time, then it is deselected. if selectedNode and @getTree()?.__selectableRows == true selectedNode.check_deselect(event, @).done( => # don't pass event, so no check is performed #console.debug "selected node:", sel_node selectedNode.deselect(null, @).done( => do_select() ).fail(deferred.reject) ).fail(deferred.reject) else do_select() # console.debug "selecting node", deferred.promise() # resolves with the innermost node openUpwards: (level=0) -> dfr = new CUI.Deferred() if @isRoot() if @isLoading() @getLoading() .done => dfr.resolve(@) .fail => dfr.reject(@) else if @is_open dfr.resolve(@) else # if root is not open, we reject all promises # an tell our callers to set "do_open" dfr.reject(@) # not opening root else promise = @father.openUpwards(level+1) promise.done => if not @is_open and level > 0 if @isLoading() _promise = @getLoading() else _promise = @open() _promise .done => dfr.resolve(@) .fail => dfr.reject(@) else dfr.resolve(@) promise.fail => # remember to open @do_open = true if level == 0 # on the last level we resolve fine dfr.resolve(@) else dfr.reject(@) dfr.promise() level: -> if @isRoot() 0 else @father.level()+1 renderContent: -> if CUI.util.isFunction(@html) @html.call(@opts, @) else if @html @html else new CUI.EmptyLabel(text: "<empty>").DOM update: (update_root=false) => # console.debug "updating ", @element?[0], @children, @getFather(), update_root, @isRoot(), @getTree() if not update_root and (not @__is_rendered or @isRoot()) # dont update root return CUI.resolvedPromise() tree = @getTree() layout_stopped = tree?.stopLayout() @replaceSelf() .done => if layout_stopped tree.startLayout() reload: -> # console.debug "ListViewTreeNode.reload:", @isRoot(), @is_open CUI.util.assert(not @isLoading(), "ListViewTreeNode.reload", "Cannot reload node, during opening...", node: @, tree: @getTree()) if @isRoot() @replaceSelf() else if @is_open @close() @do_open = true @open() else if @opts.children @children = null @update() showSpinner: -> if @__is_rendered CUI.dom.empty(@__handleDiv) CUI.dom.append(@__handleDiv, new CUI.Icon(icon: "spinner").DOM) @ hideSpinner: -> if @__is_rendered CUI.dom.empty(@__handleDiv) if @__handleIcon CUI.dom.append(@__handleDiv, new CUI.Icon(icon: @__handleIcon).DOM) else @ render: -> CUI.util.assert(not @isRoot(), "ListViewTreeNode.render", "Unable to render root node.") @removeColumns() element = CUI.dom.div("cui-tree-node level-#{@level()}") @__is_rendered = true # Space for the left side for i in [1...@level()] by 1 CUI.dom.append(element, CUI.dom.div("cui-tree-node-spacer")) # Handle before content cls = ["cui-tree-node-handle"] if @is_open @__handleIcon = CUI.defaults.class.ListViewTree.defaults.arrow_down cls.push("cui-tree-node-is-open") else if @isLeaf() @__handleIcon = null cls.push("cui-tree-node-is-leaf") else @__handleIcon = CUI.defaults.class.ListViewTree.defaults.arrow_right cls.push("cui-tree-node-is-closed") if @children?.length == 0 cls.push("cui-tree-node-no-children") @__handleDiv = CUI.dom.div(cls.join(" ")) if @__handleIcon CUI.dom.append(@__handleDiv, new CUI.Icon(icon: @__handleIcon).DOM) CUI.dom.append(element, @__handleDiv) # push the tree element as the first column @prependColumn new CUI.ListViewColumn element: element class: "cui-tree-node-column cui-tree-node-level-#{@level()}" colspan: @getColspan() # nodes can re-arrange the order of the columns # so we call them last # append Content contentDiv = CUI.dom.div("cui-tree-node-content") content = @renderContent() if CUI.util.isArray(content) for con in content CUI.dom.append(contentDiv, con) else CUI.dom.append(contentDiv, content) CUI.dom.append(element, contentDiv) @ moveToNewFather: (new_father, new_child_idx) -> old_father = @father old_father.removeChild(@) new_father.children.splice(new_child_idx, 0, @) @setFather(new_father) old_father.reload() new_father.reload() # needs to return a promise moveNodeBefore: (to_node, new_father, after) -> CUI.resolvedPromise() moveNodeAfter: (to_node, new_father, after) -> addedToListView: (DOMNodes) -> tree = @getTree() # Just for usability/accessibility. Use 'up' and 'down' to navigate through rows. element = DOMNodes?[0] if element CUI.Events.listen type: "keydown" node: element call: (ev) => keyboardKey = ev.getKeyboardKey() if keyboardKey not in ["Up", "Down"] return nextIdx = @getRowIdx() if keyboardKey == "Up" if nextIdx == 0 CUI.dom.findPreviousElement(element, "div[tabindex]")?.focus() return nextIdx-- else nextIdx++ row = tree.getRow(nextIdx) if not row?[0] CUI.dom.findNextElement(element, "div[tabindex]")?.focus() return row[0].focus() return return super(DOMNodes)
145161
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### class CUI.ListViewTreeNode extends CUI.ListViewRow initOpts: -> super() @addOpts children: check: Array open: check: Boolean html: {} colspan: check: (v) -> v > 0 getChildren: check: Function readOpts: -> super() @setColspan(@_colspan) if @_children @children = @opts.children @initChildren() if @_open @do_open = true else @do_open = false @is_open = false @html = @_html @__loadingDeferred = null setColspan: (@colspan) -> getColspan: -> @colspan # overwrite with Method getChildren: null # overwrite with Method hasChildren: null isLeaf: -> leaf = (if @children false else if @opts.getChildren false else if @getChildren if @opts.leaf or (@hasChildren and not @hasChildren()) true else false else true) # console.debug CUI.util.getObjectClass(@), "isLeaf?",leaf, @hasChildren?(), @opts.leaf, @ leaf getClass: -> cls = super() cls = cls + " cui-lv-tree-node" if not @isLeaf() cls = cls + " cui-lv-tree-node--is-branch" cls isSelectable: -> @getTree?().isSelectable() and @__selectable and not @isRoot() getFather: -> @father setFather: (new_father) -> CUI.util.assert(new_father == null or new_father instanceof CUI.ListViewTreeNode, "#{CUI.util.getObjectClass(@)}.setFather", "father can only be null or instanceof CUI.ListViewTreeNode", father: new_father) CUI.util.assert(new_father != @, "#{CUI.util.getObjectClass(@)}.setFather", "father cannot be self", node: @, father: new_father) # console.debug @, new_father if new_father CUI.util.assert(@ not in new_father.getPath(true), "#{CUI.util.getObjectClass(@)}.setFather", "father cannot any of the node's children", node: @, father: new_father) if not new_father and @selected @setSelectedNode(null) @selected = false if @father and not new_father # copy tree, since we are a new root node tree = @getTree() @father = new_father if tree @setTree(tree) else @father = new_father # if @children # for c in @children # c.setFather(@) @ isRoot: -> not @father setTree: (@tree) -> CUI.util.assert(@isRoot(), "#{CUI.util.getObjectClass(@)}.setTree", "node must be root node to set tree", tree: @tree, opts: @opts) CUI.util.assert(@tree instanceof CUI.ListViewTree, "#{CUI.util.getObjectClass(@)}.setTree", "tree must be instance of ListViewTree", tree: @tree, opts: @opts) getRoot: (call=0) -> CUI.util.assert(call < 100, "ListViewTreeNode.getRoot", "Recursion detected.") if @father @father.getRoot(call+1) else @ dump: (lines=[], depth=0) -> padding = [] for pad in [0...depth] padding.push(" ") lines.push(padding.join("")+@dumpString()) if @children for c in @children c.dump(lines, depth+1) if depth==0 return "\n"+lines.join("\n")+"\n" dumpString: -> @getNodeId() getTree: (call=0) -> CUI.util.assert(call < 100, "ListViewTreeNode.getTree", "Recursion detected.") if @isRoot() @tree else @getRoot().getTree(call+1) # find tree nodes, using the provided compare # function find: (eq_func=null, nodes=[]) -> if not eq_func or eq_func.call(@, @) nodes.push(@) if @children for c in @children c.find(eq_func, nodes) nodes # filters the children by function filter: (filter_func, filtered_nodes = []) -> save_children = @children?.slice(0) if @father and filter_func.call(@, @) # this means we have to be removed and our children # must be attached in our place to our father our_idx = @getChildIdx() filtered_nodes.push(@) father = @getFather() CUI.ListViewTreeNode::remove.call(@, true, false) # keep children array, no de-select for c, idx in save_children father.children.splice(our_idx+idx, 0, c) c.setFather(father) # console.debug "removed ", @, our_idx, save_children if save_children for c in save_children c.filter(filter_func, filtered_nodes) filtered_nodes getPath: (include_self=false, path=[], call=0) -> CUI.util.assert(call < 100, "ListViewTreeNode.getPath", "Recursion detected.") if @father @father.getPath(true, path, call+1) if include_self path.push(@) return path getChildIdx: -> if @isRoot() "root" else ci = @father.children.indexOf(@) CUI.util.assert(ci > -1, "#{CUI.util.getObjectClass(@)}.getChildIdx()", "Node not found in fathers children Array", node: @, father: @father, "father.children": @father.children) ci getNodeId: (include_self=true) -> path = @getPath(include_self) (p.getChildIdx() for p in path).join(".") getOpenChildNodes: (nodes=[]) -> if @children and @is_open for node in @children nodes.push(node) node.getOpenChildNodes(nodes) nodes getRowsToMove: -> @getOpenChildNodes() isRendered: -> if (@isRoot() and @getTree()?.getGrid()) or @__is_rendered true else false sort: (func, level=0) -> if not @children?.length return @children.sort(func) for node in @children node.sort(func, level+1) if level == 0 and @isRendered() @reload() @ close: -> CUI.util.assert(@father, "ListViewTreeNode.close()", "Cannot close root node", node: @) CUI.util.assert(not @isLoading(), "ListViewTreeNode.close", "Cannot close node, during opening...", node: @, tree: @getTree()) @do_open = false if @father.is_open # console.debug "closing node", @node_element @removeFromDOM(false) @replaceSelf() # @getTree().layout() # @element.trigger("tree", type: "close") CUI.resolvedPromise() # remove_self == false only removs children removeFromDOM: (remove_self=true) -> @abortLoading() # console.debug "remove from DOM", @getNodeId(), @is_open, @children?.length, remove_self if @is_open @do_open = true if @children for c in @children c.removeFromDOM() else @do_open = false if remove_self # console.debug "removing ", @getUniqueId(), @getDOMNodes()?[0], @__is_rendered, @getRowIdx() if @__is_rendered tree = @getTree() if tree and not tree.isDestroyed() if @getRowIdx() == null if not @isRoot() tree.removeDeferredRow(@) else tree.removeRow(@getRowIdx()) @__is_rendered = false @is_open = false @ # getElement: -> # @element # replaces node_element with a new render of ourself replaceSelf: -> if @father if tree = @getTree() # layout_stopped = tree.stopLayout() tree.replaceRow(@getRowIdx(), @render()) if @selected tree.rowAddClass(@getRowIdx(), CUI.ListViewRow.defaults.selected_class) # if layout_stopped # tree.startLayout() return CUI.resolvedPromise() else if @is_open # root node @removeFromDOM(false) # tree.removeAllRows() return @open() else return CUI.resolvedPromise() # opens all children and grandchilden openRecursively: -> @__actionRecursively("open") closeRecursively: -> @__actionRecursively("close") __actionRecursively: (action) -> dfr = new CUI.Deferred() if @isLeaf() return dfr.resolve().promise() if action == "open" ret = @getLoading() if not ret ret = @open() else ret = @close() ret.done => promises = [] for child in @children or [] promises.push(child["#{action}Recursively"]()) CUI.when(promises) .done(dfr.resolve) .fail(dfr.reject) .fail(dfr.reject) dfr.promise() isOpen: -> !!@is_open isLoading: -> !!@__loadingDeferred getLoading: -> @__loadingDeferred abortLoading: -> if not @__loadingDeferred return # console.error("ListViewTreeNode.abortLoading: Aborting chunk loading.") if @__loadingDeferred.state == 'pending' @__loadingDeferred.reject() @__loadingDeferred = null return # resolves with the opened node open: -> # we could return loading_deferred here CUI.util.assert(not @isLoading(), "ListViewTreeNode.open", "Cannot open node #{@getUniqueId()}, during opening. This can happen if the same node exists multiple times in the same tree.", node: @) if @is_open or @isLeaf() return CUI.resolvedPromise() # console.error @getUniqueId(), "opening...", "is open:", @is_open, open_counter @is_open = true @do_open = false dfr = @__loadingDeferred = new CUI.Deferred() # console.warn("Start opening", @getUniqueId(), dfr.getUniqueId()) do_resolve = => if @__loadingDeferred.state() == "pending" @__loadingDeferred.resolve(@) @__loadingDeferred = null do_reject = => if @__loadingDeferred.state() == "pending" @__loadingDeferred.reject(@) @__loadingDeferred = null load_children = => CUI.util.assert(CUI.util.isArray(@children), "ListViewTreeNode.open", "children to be loaded must be an Array", children: @children, listViewTreeNode: @) # console.debug @._key, @getUniqueId(), "children loaded", @children.length if @children.length == 0 if not @isRoot() @replaceSelf() do_resolve() return @initChildren() CUI.chunkWork.call @, items: @children chunk_size: 5 timeout: 1 call: (items) => CUI.chunkWork.call @, items: items chunk_size: 1 timeout: -1 call: (_items) => # console.error @getUniqueId(), open_counter, @__open_counter, "chunking work" if dfr != @__loadingDeferred # we are already in a new run, exit return false @__appendNode(_items[0], true) # , false, true)) .done => # console.error @getUniqueId(), open_counter, @__open_counter, "chunking work DONE" if dfr != @__loadingDeferred return if not @isRoot() @replaceSelf() do_resolve() .fail => # console.error @getUniqueId(), open_counter, @__open_counter, "chunking work FAIL" if dfr != @__loadingDeferred return for c in @children c.removeFromDOM() do_reject() return if @children load_children() else func = @opts.getChildren or @getChildren if func ret = func.call(@) if CUI.util.isArray(ret) @children = ret load_children() else CUI.util.assert(CUI.util.isPromise(ret), "#{CUI.util.getObjectClass(@)}.open", "returned children are not of type Promise or Array", children: ret) ret .done (@children) => if dfr != @__loadingDeferred return load_children() return .fail(do_reject) else if not @isRoot() @replaceSelf() do_resolve() dfr.promise() prependChild: (node) -> @addNode(node, false) addChild: (node) -> @addNode(node, true) prependSibling: (node) -> idx = @getChildIdx() @father.addNode(node, idx) appendSibling: (node) -> idx = @getChildIdx()+1 if idx > @father.children.length-1 @father.addNode(node) else @father.addNode(node, idx) setChildren: (@children) -> @initChildren() return initChildren: -> for node, idx in @children for _node, _idx in @children if idx == _idx continue CUI.util.assert(_node != node, "ListViewTreeNode.initChildren", "Must have every child only once.", node: @, child: node) node.setFather(@) return # add node adds the node to our children array and # actually visually appends it to the ListView # however, it does not visually appends it, if the root node # is not yet "open". addNode: (node, append=true) -> CUI.util.assert(not @isLoading(), "ListViewTreeNode.addNode", "Cannot add node, during loading.", node: @) if not @children @children = [] CUI.util.assert(CUI.util.isArray(@children), "Tree.addNode","Cannot add node, children needs to be an Array in node", node: @, new_node: node) for _node in @children CUI.util.assert(_node != node, "ListViewTreeNode.addNode", "Must have every child only once.", node: @, child: _node) if append == true @children.push(node) else @children.splice(append,0,node) node.setFather(@) # if @is_open # # we are already open, append the node # return @__appendNode(node, append) # else # return CUI.resolvedPromise(node) if not @is_open if @isRoot() or not @isRendered() return CUI.resolvedPromise(node) # open us, since we have just added a child node # we need to open us # make sure to return the addedNode dfr = new CUI.Deferred() @open() .done => dfr.resolve(node) .fail => dfr.reject(node) promise = dfr.promise() else # we are already open, so simply append the node promise = @__appendNode(node, append) promise # resolves with the appended node __appendNode: (node, append=true) -> # , assume_open=false) -> CUI.util.assert(node instanceof CUI.ListViewTreeNode, "ListViewTreeNode.__appendNode", "node must be instance of ListViewTreeNode", node: @, new_node: node) CUI.util.assert(node.getFather() == @, "ListViewTreeNode.__appendNode", "node added must be child of current node", node: @, new_node: node) # console.debug ".__appendNode: father: ", @getUniqueId()+"["+@getNodeId()+"]", "child:", node.getUniqueId()+"["+node.getNodeId()+"]" if append == false append = 0 tree = @getTree() if tree?.isDestroyed() return CUI.rejectedPromise(node) if not @isRendered() return CUI.resolvedPromise(node) # console.warn "appendNode", @getUniqueId(), "new:", node.getUniqueId(), "father open:", @getFather()?.isOpen() child_idx = node.getChildIdx() if @isRoot() if append == true or @children.length == 1 or append+1 == @children.length tree.appendRow(node.render()) else CUI.util.assert(@children[append+1], @__cls+".__addNode", "Node not found", children: @children, node: @, append: append) tree.insertRowBefore(@children[append+1].getRowIdx(), node.render()) else if child_idx == 0 # this means the added node is the first child, we # always add this after tree.insertRowAfter(@getRowIdx(), node.render()) else if append != true tree.insertRowBefore(@children[append+1].getRowIdx(), node.render()) else # this last node is the node before us, we need to see # if is is opened and find the last node opened last_node = @children[child_idx-1] child_nodes = last_node.getOpenChildNodes() if child_nodes.length last_node = child_nodes[child_nodes.length-1] # if last_node.getRowIdx() == null # console.error "row index is not there", tree, @is_open, @getNodeId(), child_idx, @children # _last_node = @children[child_idx-1] # console.debug "last node", _last_node, _last_node.isRendered() # console.debug "child nodes", child_nodes, last_node.isRendered() tree.insertRowAfter(last_node.getRowIdx(), node.render()) if node.selected tree.rowAddClass(node.getRowIdx(), CUI.ListViewRow.defaults.selected_class) if node.do_open node.open() else CUI.resolvedPromise(node) remove: (keep_children_array=false, select_after=true) -> dfr = new CUI.Deferred() select_after_node = null remove_node = => # console.debug "remove", @getNodeId(), @father.getNodeId(), @element @removeFromDOM() @father?.removeChild(@, keep_children_array) if tree = @getTree() CUI.Events.trigger node: tree type: "row_removed" if select_after_node select_after_node.select() .done(dfr.resolve).fail(dfr.reject) else dfr.resolve() else dfr.resolve() return if select_after and not @isRoot() children = @getFather().children if children.length > 1 child_idx = @getChildIdx() if child_idx == 0 select_after = 1 else select_after = Math.min(children.length-2, child_idx-1) if select_after != null select_after_node = children[select_after] if @isSelected() @deselect().fail(dfr.reject).done(remove_node) else remove_node() dfr.promise() removeChild: (child, keep_children_array=false) -> CUI.util.removeFromArray(child, @children) if @children.length == 0 and not @isRoot() @is_open = false if not keep_children_array # this hides the "open" icon @children = null # console.error "removeChild...", @children?.length, keep_children_array, @isRoot() @update() child.setFather(null) deselect: (ev, new_node) -> if not @getTree().isSelectable() return CUI.resolvedPromise() @check_deselect(ev, new_node) .done => @setSelectedNode() @removeSelectedClass() @selected = false @getTree().triggerNodeDeselect(ev, @) allowRowMove: -> true check_deselect: (ev, new_node) -> CUI.resolvedPromise() isSelected: -> !!@selected addSelectedClass: -> @getTree().rowAddClass(@getRowIdx(), CUI.ListViewRow.defaults.selected_class) removeSelectedClass: -> @getTree().rowRemoveClass(@getRowIdx(), CUI.ListViewRow.defaults.selected_class) setSelectedNode: (node = null, key = @getSelectedNodeKey()) -> @getRoot()[@getSelectedNodeKey()] = node getSelectedNode: (key = @getSelectedNodeKey()) -> @getRoot()?[key] or null getSelectedNodeKey: -> "<KEY>" select: (event) -> deferred = new CUI.Deferred() if event and @getTree?().isSelectable() event.stopPropagation?() deferred.done => @getTree().triggerNodeSelect(event, @) if not @isSelectable() # console.debug "row is not selectable", "row:", @, "tree:", @getTree() return deferred.reject().promise() if @isSelected() return deferred.resolve().promise() # console.debug "selecting node", sel_node do_select = => @getTree()._onBeforeSelect?(@) @setSelectedNode(@) # console.error "openUpwards", @getNodeId(), @is_open @openUpwards() .done => @addSelectedClass() @selected = true deferred.resolve() .fail(deferred.reject) # the selected node is not us, so we ask the other # node selectedNode = @getSelectedNode() # If selectableRows is 'true' means that only one row can be selected at the same time, then it is deselected. if selectedNode and @getTree()?.__selectableRows == true selectedNode.check_deselect(event, @).done( => # don't pass event, so no check is performed #console.debug "selected node:", sel_node selectedNode.deselect(null, @).done( => do_select() ).fail(deferred.reject) ).fail(deferred.reject) else do_select() # console.debug "selecting node", deferred.promise() # resolves with the innermost node openUpwards: (level=0) -> dfr = new CUI.Deferred() if @isRoot() if @isLoading() @getLoading() .done => dfr.resolve(@) .fail => dfr.reject(@) else if @is_open dfr.resolve(@) else # if root is not open, we reject all promises # an tell our callers to set "do_open" dfr.reject(@) # not opening root else promise = @father.openUpwards(level+1) promise.done => if not @is_open and level > 0 if @isLoading() _promise = @getLoading() else _promise = @open() _promise .done => dfr.resolve(@) .fail => dfr.reject(@) else dfr.resolve(@) promise.fail => # remember to open @do_open = true if level == 0 # on the last level we resolve fine dfr.resolve(@) else dfr.reject(@) dfr.promise() level: -> if @isRoot() 0 else @father.level()+1 renderContent: -> if CUI.util.isFunction(@html) @html.call(@opts, @) else if @html @html else new CUI.EmptyLabel(text: "<empty>").DOM update: (update_root=false) => # console.debug "updating ", @element?[0], @children, @getFather(), update_root, @isRoot(), @getTree() if not update_root and (not @__is_rendered or @isRoot()) # dont update root return CUI.resolvedPromise() tree = @getTree() layout_stopped = tree?.stopLayout() @replaceSelf() .done => if layout_stopped tree.startLayout() reload: -> # console.debug "ListViewTreeNode.reload:", @isRoot(), @is_open CUI.util.assert(not @isLoading(), "ListViewTreeNode.reload", "Cannot reload node, during opening...", node: @, tree: @getTree()) if @isRoot() @replaceSelf() else if @is_open @close() @do_open = true @open() else if @opts.children @children = null @update() showSpinner: -> if @__is_rendered CUI.dom.empty(@__handleDiv) CUI.dom.append(@__handleDiv, new CUI.Icon(icon: "spinner").DOM) @ hideSpinner: -> if @__is_rendered CUI.dom.empty(@__handleDiv) if @__handleIcon CUI.dom.append(@__handleDiv, new CUI.Icon(icon: @__handleIcon).DOM) else @ render: -> CUI.util.assert(not @isRoot(), "ListViewTreeNode.render", "Unable to render root node.") @removeColumns() element = CUI.dom.div("cui-tree-node level-#{@level()}") @__is_rendered = true # Space for the left side for i in [1...@level()] by 1 CUI.dom.append(element, CUI.dom.div("cui-tree-node-spacer")) # Handle before content cls = ["cui-tree-node-handle"] if @is_open @__handleIcon = CUI.defaults.class.ListViewTree.defaults.arrow_down cls.push("cui-tree-node-is-open") else if @isLeaf() @__handleIcon = null cls.push("cui-tree-node-is-leaf") else @__handleIcon = CUI.defaults.class.ListViewTree.defaults.arrow_right cls.push("cui-tree-node-is-closed") if @children?.length == 0 cls.push("cui-tree-node-no-children") @__handleDiv = CUI.dom.div(cls.join(" ")) if @__handleIcon CUI.dom.append(@__handleDiv, new CUI.Icon(icon: @__handleIcon).DOM) CUI.dom.append(element, @__handleDiv) # push the tree element as the first column @prependColumn new CUI.ListViewColumn element: element class: "cui-tree-node-column cui-tree-node-level-#{@level()}" colspan: @getColspan() # nodes can re-arrange the order of the columns # so we call them last # append Content contentDiv = CUI.dom.div("cui-tree-node-content") content = @renderContent() if CUI.util.isArray(content) for con in content CUI.dom.append(contentDiv, con) else CUI.dom.append(contentDiv, content) CUI.dom.append(element, contentDiv) @ moveToNewFather: (new_father, new_child_idx) -> old_father = @father old_father.removeChild(@) new_father.children.splice(new_child_idx, 0, @) @setFather(new_father) old_father.reload() new_father.reload() # needs to return a promise moveNodeBefore: (to_node, new_father, after) -> CUI.resolvedPromise() moveNodeAfter: (to_node, new_father, after) -> addedToListView: (DOMNodes) -> tree = @getTree() # Just for usability/accessibility. Use 'up' and 'down' to navigate through rows. element = DOMNodes?[0] if element CUI.Events.listen type: "keydown" node: element call: (ev) => keyboardKey = ev.getKeyboardKey() if keyboardKey not in ["Up", "Down"] return nextIdx = @getRowIdx() if keyboardKey == "Up" if nextIdx == 0 CUI.dom.findPreviousElement(element, "div[tabindex]")?.focus() return nextIdx-- else nextIdx++ row = tree.getRow(nextIdx) if not row?[0] CUI.dom.findNextElement(element, "div[tabindex]")?.focus() return row[0].focus() return return super(DOMNodes)
true
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### class CUI.ListViewTreeNode extends CUI.ListViewRow initOpts: -> super() @addOpts children: check: Array open: check: Boolean html: {} colspan: check: (v) -> v > 0 getChildren: check: Function readOpts: -> super() @setColspan(@_colspan) if @_children @children = @opts.children @initChildren() if @_open @do_open = true else @do_open = false @is_open = false @html = @_html @__loadingDeferred = null setColspan: (@colspan) -> getColspan: -> @colspan # overwrite with Method getChildren: null # overwrite with Method hasChildren: null isLeaf: -> leaf = (if @children false else if @opts.getChildren false else if @getChildren if @opts.leaf or (@hasChildren and not @hasChildren()) true else false else true) # console.debug CUI.util.getObjectClass(@), "isLeaf?",leaf, @hasChildren?(), @opts.leaf, @ leaf getClass: -> cls = super() cls = cls + " cui-lv-tree-node" if not @isLeaf() cls = cls + " cui-lv-tree-node--is-branch" cls isSelectable: -> @getTree?().isSelectable() and @__selectable and not @isRoot() getFather: -> @father setFather: (new_father) -> CUI.util.assert(new_father == null or new_father instanceof CUI.ListViewTreeNode, "#{CUI.util.getObjectClass(@)}.setFather", "father can only be null or instanceof CUI.ListViewTreeNode", father: new_father) CUI.util.assert(new_father != @, "#{CUI.util.getObjectClass(@)}.setFather", "father cannot be self", node: @, father: new_father) # console.debug @, new_father if new_father CUI.util.assert(@ not in new_father.getPath(true), "#{CUI.util.getObjectClass(@)}.setFather", "father cannot any of the node's children", node: @, father: new_father) if not new_father and @selected @setSelectedNode(null) @selected = false if @father and not new_father # copy tree, since we are a new root node tree = @getTree() @father = new_father if tree @setTree(tree) else @father = new_father # if @children # for c in @children # c.setFather(@) @ isRoot: -> not @father setTree: (@tree) -> CUI.util.assert(@isRoot(), "#{CUI.util.getObjectClass(@)}.setTree", "node must be root node to set tree", tree: @tree, opts: @opts) CUI.util.assert(@tree instanceof CUI.ListViewTree, "#{CUI.util.getObjectClass(@)}.setTree", "tree must be instance of ListViewTree", tree: @tree, opts: @opts) getRoot: (call=0) -> CUI.util.assert(call < 100, "ListViewTreeNode.getRoot", "Recursion detected.") if @father @father.getRoot(call+1) else @ dump: (lines=[], depth=0) -> padding = [] for pad in [0...depth] padding.push(" ") lines.push(padding.join("")+@dumpString()) if @children for c in @children c.dump(lines, depth+1) if depth==0 return "\n"+lines.join("\n")+"\n" dumpString: -> @getNodeId() getTree: (call=0) -> CUI.util.assert(call < 100, "ListViewTreeNode.getTree", "Recursion detected.") if @isRoot() @tree else @getRoot().getTree(call+1) # find tree nodes, using the provided compare # function find: (eq_func=null, nodes=[]) -> if not eq_func or eq_func.call(@, @) nodes.push(@) if @children for c in @children c.find(eq_func, nodes) nodes # filters the children by function filter: (filter_func, filtered_nodes = []) -> save_children = @children?.slice(0) if @father and filter_func.call(@, @) # this means we have to be removed and our children # must be attached in our place to our father our_idx = @getChildIdx() filtered_nodes.push(@) father = @getFather() CUI.ListViewTreeNode::remove.call(@, true, false) # keep children array, no de-select for c, idx in save_children father.children.splice(our_idx+idx, 0, c) c.setFather(father) # console.debug "removed ", @, our_idx, save_children if save_children for c in save_children c.filter(filter_func, filtered_nodes) filtered_nodes getPath: (include_self=false, path=[], call=0) -> CUI.util.assert(call < 100, "ListViewTreeNode.getPath", "Recursion detected.") if @father @father.getPath(true, path, call+1) if include_self path.push(@) return path getChildIdx: -> if @isRoot() "root" else ci = @father.children.indexOf(@) CUI.util.assert(ci > -1, "#{CUI.util.getObjectClass(@)}.getChildIdx()", "Node not found in fathers children Array", node: @, father: @father, "father.children": @father.children) ci getNodeId: (include_self=true) -> path = @getPath(include_self) (p.getChildIdx() for p in path).join(".") getOpenChildNodes: (nodes=[]) -> if @children and @is_open for node in @children nodes.push(node) node.getOpenChildNodes(nodes) nodes getRowsToMove: -> @getOpenChildNodes() isRendered: -> if (@isRoot() and @getTree()?.getGrid()) or @__is_rendered true else false sort: (func, level=0) -> if not @children?.length return @children.sort(func) for node in @children node.sort(func, level+1) if level == 0 and @isRendered() @reload() @ close: -> CUI.util.assert(@father, "ListViewTreeNode.close()", "Cannot close root node", node: @) CUI.util.assert(not @isLoading(), "ListViewTreeNode.close", "Cannot close node, during opening...", node: @, tree: @getTree()) @do_open = false if @father.is_open # console.debug "closing node", @node_element @removeFromDOM(false) @replaceSelf() # @getTree().layout() # @element.trigger("tree", type: "close") CUI.resolvedPromise() # remove_self == false only removs children removeFromDOM: (remove_self=true) -> @abortLoading() # console.debug "remove from DOM", @getNodeId(), @is_open, @children?.length, remove_self if @is_open @do_open = true if @children for c in @children c.removeFromDOM() else @do_open = false if remove_self # console.debug "removing ", @getUniqueId(), @getDOMNodes()?[0], @__is_rendered, @getRowIdx() if @__is_rendered tree = @getTree() if tree and not tree.isDestroyed() if @getRowIdx() == null if not @isRoot() tree.removeDeferredRow(@) else tree.removeRow(@getRowIdx()) @__is_rendered = false @is_open = false @ # getElement: -> # @element # replaces node_element with a new render of ourself replaceSelf: -> if @father if tree = @getTree() # layout_stopped = tree.stopLayout() tree.replaceRow(@getRowIdx(), @render()) if @selected tree.rowAddClass(@getRowIdx(), CUI.ListViewRow.defaults.selected_class) # if layout_stopped # tree.startLayout() return CUI.resolvedPromise() else if @is_open # root node @removeFromDOM(false) # tree.removeAllRows() return @open() else return CUI.resolvedPromise() # opens all children and grandchilden openRecursively: -> @__actionRecursively("open") closeRecursively: -> @__actionRecursively("close") __actionRecursively: (action) -> dfr = new CUI.Deferred() if @isLeaf() return dfr.resolve().promise() if action == "open" ret = @getLoading() if not ret ret = @open() else ret = @close() ret.done => promises = [] for child in @children or [] promises.push(child["#{action}Recursively"]()) CUI.when(promises) .done(dfr.resolve) .fail(dfr.reject) .fail(dfr.reject) dfr.promise() isOpen: -> !!@is_open isLoading: -> !!@__loadingDeferred getLoading: -> @__loadingDeferred abortLoading: -> if not @__loadingDeferred return # console.error("ListViewTreeNode.abortLoading: Aborting chunk loading.") if @__loadingDeferred.state == 'pending' @__loadingDeferred.reject() @__loadingDeferred = null return # resolves with the opened node open: -> # we could return loading_deferred here CUI.util.assert(not @isLoading(), "ListViewTreeNode.open", "Cannot open node #{@getUniqueId()}, during opening. This can happen if the same node exists multiple times in the same tree.", node: @) if @is_open or @isLeaf() return CUI.resolvedPromise() # console.error @getUniqueId(), "opening...", "is open:", @is_open, open_counter @is_open = true @do_open = false dfr = @__loadingDeferred = new CUI.Deferred() # console.warn("Start opening", @getUniqueId(), dfr.getUniqueId()) do_resolve = => if @__loadingDeferred.state() == "pending" @__loadingDeferred.resolve(@) @__loadingDeferred = null do_reject = => if @__loadingDeferred.state() == "pending" @__loadingDeferred.reject(@) @__loadingDeferred = null load_children = => CUI.util.assert(CUI.util.isArray(@children), "ListViewTreeNode.open", "children to be loaded must be an Array", children: @children, listViewTreeNode: @) # console.debug @._key, @getUniqueId(), "children loaded", @children.length if @children.length == 0 if not @isRoot() @replaceSelf() do_resolve() return @initChildren() CUI.chunkWork.call @, items: @children chunk_size: 5 timeout: 1 call: (items) => CUI.chunkWork.call @, items: items chunk_size: 1 timeout: -1 call: (_items) => # console.error @getUniqueId(), open_counter, @__open_counter, "chunking work" if dfr != @__loadingDeferred # we are already in a new run, exit return false @__appendNode(_items[0], true) # , false, true)) .done => # console.error @getUniqueId(), open_counter, @__open_counter, "chunking work DONE" if dfr != @__loadingDeferred return if not @isRoot() @replaceSelf() do_resolve() .fail => # console.error @getUniqueId(), open_counter, @__open_counter, "chunking work FAIL" if dfr != @__loadingDeferred return for c in @children c.removeFromDOM() do_reject() return if @children load_children() else func = @opts.getChildren or @getChildren if func ret = func.call(@) if CUI.util.isArray(ret) @children = ret load_children() else CUI.util.assert(CUI.util.isPromise(ret), "#{CUI.util.getObjectClass(@)}.open", "returned children are not of type Promise or Array", children: ret) ret .done (@children) => if dfr != @__loadingDeferred return load_children() return .fail(do_reject) else if not @isRoot() @replaceSelf() do_resolve() dfr.promise() prependChild: (node) -> @addNode(node, false) addChild: (node) -> @addNode(node, true) prependSibling: (node) -> idx = @getChildIdx() @father.addNode(node, idx) appendSibling: (node) -> idx = @getChildIdx()+1 if idx > @father.children.length-1 @father.addNode(node) else @father.addNode(node, idx) setChildren: (@children) -> @initChildren() return initChildren: -> for node, idx in @children for _node, _idx in @children if idx == _idx continue CUI.util.assert(_node != node, "ListViewTreeNode.initChildren", "Must have every child only once.", node: @, child: node) node.setFather(@) return # add node adds the node to our children array and # actually visually appends it to the ListView # however, it does not visually appends it, if the root node # is not yet "open". addNode: (node, append=true) -> CUI.util.assert(not @isLoading(), "ListViewTreeNode.addNode", "Cannot add node, during loading.", node: @) if not @children @children = [] CUI.util.assert(CUI.util.isArray(@children), "Tree.addNode","Cannot add node, children needs to be an Array in node", node: @, new_node: node) for _node in @children CUI.util.assert(_node != node, "ListViewTreeNode.addNode", "Must have every child only once.", node: @, child: _node) if append == true @children.push(node) else @children.splice(append,0,node) node.setFather(@) # if @is_open # # we are already open, append the node # return @__appendNode(node, append) # else # return CUI.resolvedPromise(node) if not @is_open if @isRoot() or not @isRendered() return CUI.resolvedPromise(node) # open us, since we have just added a child node # we need to open us # make sure to return the addedNode dfr = new CUI.Deferred() @open() .done => dfr.resolve(node) .fail => dfr.reject(node) promise = dfr.promise() else # we are already open, so simply append the node promise = @__appendNode(node, append) promise # resolves with the appended node __appendNode: (node, append=true) -> # , assume_open=false) -> CUI.util.assert(node instanceof CUI.ListViewTreeNode, "ListViewTreeNode.__appendNode", "node must be instance of ListViewTreeNode", node: @, new_node: node) CUI.util.assert(node.getFather() == @, "ListViewTreeNode.__appendNode", "node added must be child of current node", node: @, new_node: node) # console.debug ".__appendNode: father: ", @getUniqueId()+"["+@getNodeId()+"]", "child:", node.getUniqueId()+"["+node.getNodeId()+"]" if append == false append = 0 tree = @getTree() if tree?.isDestroyed() return CUI.rejectedPromise(node) if not @isRendered() return CUI.resolvedPromise(node) # console.warn "appendNode", @getUniqueId(), "new:", node.getUniqueId(), "father open:", @getFather()?.isOpen() child_idx = node.getChildIdx() if @isRoot() if append == true or @children.length == 1 or append+1 == @children.length tree.appendRow(node.render()) else CUI.util.assert(@children[append+1], @__cls+".__addNode", "Node not found", children: @children, node: @, append: append) tree.insertRowBefore(@children[append+1].getRowIdx(), node.render()) else if child_idx == 0 # this means the added node is the first child, we # always add this after tree.insertRowAfter(@getRowIdx(), node.render()) else if append != true tree.insertRowBefore(@children[append+1].getRowIdx(), node.render()) else # this last node is the node before us, we need to see # if is is opened and find the last node opened last_node = @children[child_idx-1] child_nodes = last_node.getOpenChildNodes() if child_nodes.length last_node = child_nodes[child_nodes.length-1] # if last_node.getRowIdx() == null # console.error "row index is not there", tree, @is_open, @getNodeId(), child_idx, @children # _last_node = @children[child_idx-1] # console.debug "last node", _last_node, _last_node.isRendered() # console.debug "child nodes", child_nodes, last_node.isRendered() tree.insertRowAfter(last_node.getRowIdx(), node.render()) if node.selected tree.rowAddClass(node.getRowIdx(), CUI.ListViewRow.defaults.selected_class) if node.do_open node.open() else CUI.resolvedPromise(node) remove: (keep_children_array=false, select_after=true) -> dfr = new CUI.Deferred() select_after_node = null remove_node = => # console.debug "remove", @getNodeId(), @father.getNodeId(), @element @removeFromDOM() @father?.removeChild(@, keep_children_array) if tree = @getTree() CUI.Events.trigger node: tree type: "row_removed" if select_after_node select_after_node.select() .done(dfr.resolve).fail(dfr.reject) else dfr.resolve() else dfr.resolve() return if select_after and not @isRoot() children = @getFather().children if children.length > 1 child_idx = @getChildIdx() if child_idx == 0 select_after = 1 else select_after = Math.min(children.length-2, child_idx-1) if select_after != null select_after_node = children[select_after] if @isSelected() @deselect().fail(dfr.reject).done(remove_node) else remove_node() dfr.promise() removeChild: (child, keep_children_array=false) -> CUI.util.removeFromArray(child, @children) if @children.length == 0 and not @isRoot() @is_open = false if not keep_children_array # this hides the "open" icon @children = null # console.error "removeChild...", @children?.length, keep_children_array, @isRoot() @update() child.setFather(null) deselect: (ev, new_node) -> if not @getTree().isSelectable() return CUI.resolvedPromise() @check_deselect(ev, new_node) .done => @setSelectedNode() @removeSelectedClass() @selected = false @getTree().triggerNodeDeselect(ev, @) allowRowMove: -> true check_deselect: (ev, new_node) -> CUI.resolvedPromise() isSelected: -> !!@selected addSelectedClass: -> @getTree().rowAddClass(@getRowIdx(), CUI.ListViewRow.defaults.selected_class) removeSelectedClass: -> @getTree().rowRemoveClass(@getRowIdx(), CUI.ListViewRow.defaults.selected_class) setSelectedNode: (node = null, key = @getSelectedNodeKey()) -> @getRoot()[@getSelectedNodeKey()] = node getSelectedNode: (key = @getSelectedNodeKey()) -> @getRoot()?[key] or null getSelectedNodeKey: -> "PI:KEY:<KEY>END_PI" select: (event) -> deferred = new CUI.Deferred() if event and @getTree?().isSelectable() event.stopPropagation?() deferred.done => @getTree().triggerNodeSelect(event, @) if not @isSelectable() # console.debug "row is not selectable", "row:", @, "tree:", @getTree() return deferred.reject().promise() if @isSelected() return deferred.resolve().promise() # console.debug "selecting node", sel_node do_select = => @getTree()._onBeforeSelect?(@) @setSelectedNode(@) # console.error "openUpwards", @getNodeId(), @is_open @openUpwards() .done => @addSelectedClass() @selected = true deferred.resolve() .fail(deferred.reject) # the selected node is not us, so we ask the other # node selectedNode = @getSelectedNode() # If selectableRows is 'true' means that only one row can be selected at the same time, then it is deselected. if selectedNode and @getTree()?.__selectableRows == true selectedNode.check_deselect(event, @).done( => # don't pass event, so no check is performed #console.debug "selected node:", sel_node selectedNode.deselect(null, @).done( => do_select() ).fail(deferred.reject) ).fail(deferred.reject) else do_select() # console.debug "selecting node", deferred.promise() # resolves with the innermost node openUpwards: (level=0) -> dfr = new CUI.Deferred() if @isRoot() if @isLoading() @getLoading() .done => dfr.resolve(@) .fail => dfr.reject(@) else if @is_open dfr.resolve(@) else # if root is not open, we reject all promises # an tell our callers to set "do_open" dfr.reject(@) # not opening root else promise = @father.openUpwards(level+1) promise.done => if not @is_open and level > 0 if @isLoading() _promise = @getLoading() else _promise = @open() _promise .done => dfr.resolve(@) .fail => dfr.reject(@) else dfr.resolve(@) promise.fail => # remember to open @do_open = true if level == 0 # on the last level we resolve fine dfr.resolve(@) else dfr.reject(@) dfr.promise() level: -> if @isRoot() 0 else @father.level()+1 renderContent: -> if CUI.util.isFunction(@html) @html.call(@opts, @) else if @html @html else new CUI.EmptyLabel(text: "<empty>").DOM update: (update_root=false) => # console.debug "updating ", @element?[0], @children, @getFather(), update_root, @isRoot(), @getTree() if not update_root and (not @__is_rendered or @isRoot()) # dont update root return CUI.resolvedPromise() tree = @getTree() layout_stopped = tree?.stopLayout() @replaceSelf() .done => if layout_stopped tree.startLayout() reload: -> # console.debug "ListViewTreeNode.reload:", @isRoot(), @is_open CUI.util.assert(not @isLoading(), "ListViewTreeNode.reload", "Cannot reload node, during opening...", node: @, tree: @getTree()) if @isRoot() @replaceSelf() else if @is_open @close() @do_open = true @open() else if @opts.children @children = null @update() showSpinner: -> if @__is_rendered CUI.dom.empty(@__handleDiv) CUI.dom.append(@__handleDiv, new CUI.Icon(icon: "spinner").DOM) @ hideSpinner: -> if @__is_rendered CUI.dom.empty(@__handleDiv) if @__handleIcon CUI.dom.append(@__handleDiv, new CUI.Icon(icon: @__handleIcon).DOM) else @ render: -> CUI.util.assert(not @isRoot(), "ListViewTreeNode.render", "Unable to render root node.") @removeColumns() element = CUI.dom.div("cui-tree-node level-#{@level()}") @__is_rendered = true # Space for the left side for i in [1...@level()] by 1 CUI.dom.append(element, CUI.dom.div("cui-tree-node-spacer")) # Handle before content cls = ["cui-tree-node-handle"] if @is_open @__handleIcon = CUI.defaults.class.ListViewTree.defaults.arrow_down cls.push("cui-tree-node-is-open") else if @isLeaf() @__handleIcon = null cls.push("cui-tree-node-is-leaf") else @__handleIcon = CUI.defaults.class.ListViewTree.defaults.arrow_right cls.push("cui-tree-node-is-closed") if @children?.length == 0 cls.push("cui-tree-node-no-children") @__handleDiv = CUI.dom.div(cls.join(" ")) if @__handleIcon CUI.dom.append(@__handleDiv, new CUI.Icon(icon: @__handleIcon).DOM) CUI.dom.append(element, @__handleDiv) # push the tree element as the first column @prependColumn new CUI.ListViewColumn element: element class: "cui-tree-node-column cui-tree-node-level-#{@level()}" colspan: @getColspan() # nodes can re-arrange the order of the columns # so we call them last # append Content contentDiv = CUI.dom.div("cui-tree-node-content") content = @renderContent() if CUI.util.isArray(content) for con in content CUI.dom.append(contentDiv, con) else CUI.dom.append(contentDiv, content) CUI.dom.append(element, contentDiv) @ moveToNewFather: (new_father, new_child_idx) -> old_father = @father old_father.removeChild(@) new_father.children.splice(new_child_idx, 0, @) @setFather(new_father) old_father.reload() new_father.reload() # needs to return a promise moveNodeBefore: (to_node, new_father, after) -> CUI.resolvedPromise() moveNodeAfter: (to_node, new_father, after) -> addedToListView: (DOMNodes) -> tree = @getTree() # Just for usability/accessibility. Use 'up' and 'down' to navigate through rows. element = DOMNodes?[0] if element CUI.Events.listen type: "keydown" node: element call: (ev) => keyboardKey = ev.getKeyboardKey() if keyboardKey not in ["Up", "Down"] return nextIdx = @getRowIdx() if keyboardKey == "Up" if nextIdx == 0 CUI.dom.findPreviousElement(element, "div[tabindex]")?.focus() return nextIdx-- else nextIdx++ row = tree.getRow(nextIdx) if not row?[0] CUI.dom.findNextElement(element, "div[tabindex]")?.focus() return row[0].focus() return return super(DOMNodes)
[ { "context": "rs', (done) ->\n @article.author = {\n id: '123'\n name: 'Artsy Editorial'\n profile_id: ", "end": 1324, "score": 0.7815554141998291, "start": 1321, "tag": "USERNAME", "value": "123" }, { "context": " @article.author = {\n id: '123'\n name: 'Artsy Editorial'\n profile_id: '123'\n profile_handle: 'A", "end": 1354, "score": 0.9998462796211243, "start": 1339, "tag": "NAME", "value": "Artsy Editorial" }, { "context": " name: 'Artsy Editorial'\n profile_id: '123'\n profile_handle: 'Artsy'\n facebook_han", "end": 1378, "score": 0.7994085550308228, "start": 1377, "tag": "USERNAME", "value": "3" }, { "context": "l'\n profile_id: '123'\n profile_handle: 'Artsy'\n facebook_handle: 'fbhandle'\n twitter_", "end": 1408, "score": 0.957358181476593, "start": 1403, "tag": "USERNAME", "value": "Artsy" }, { "context": " profile_handle: 'Artsy'\n facebook_handle: 'fbhandle'\n twitter_handle: 'thandle'\n }\n @clien", "end": 1442, "score": 0.9979496002197266, "start": 1434, "tag": "USERNAME", "value": "fbhandle" }, { "context": "acebook_handle: 'fbhandle'\n twitter_handle: 'thandle'\n }\n @client.init()\n _.defer =>\n @c", "end": 1474, "score": 0.9995023012161255, "start": 1467, "tag": "USERNAME", "value": "thandle" }, { "context": ".article.get('author').should.eql {\n id: '123'\n name: 'Artsy Editorial'\n }\n do", "end": 1581, "score": 0.6184499263763428, "start": 1579, "tag": "USERNAME", "value": "23" }, { "context": "r').should.eql {\n id: '123'\n name: 'Artsy Editorial'\n }\n done()", "end": 1613, "score": 0.9998394250869751, "start": 1598, "tag": "NAME", "value": "Artsy Editorial" } ]
src/client/apps/edit/test/client.test.coffee
craigspaeth/positron
76
benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { resolve } = require 'path' rewire = require 'rewire' fixtures = require '../../../../test/helpers/fixtures' xdescribe 'init', -> beforeEach (done) -> @article = fixtures().articles benv.setup => benv.expose _: require('underscore') $: benv.require('jquery') jQuery: benv.require('jquery') sd: { ARTICLE: @article, CURRENT_CHANNEL: id: '456' } window.jQuery = jQuery @client = rewire '../client.coffee' @client.__set__ 'EditLayout', @EditLayout = sinon.stub() @client.__set__ 'EditHeader', @EditHeader = sinon.stub() @client.__set__ 'EditAdmin', @EditAdmin = sinon.stub() @client.__set__ 'EditDisplay', @EditDisplay = sinon.stub() @client.__set__ 'ReactDOM', @ReactDOM = render: sinon.stub() @client.__set__ 'sd', sd done() afterEach -> benv.teardown() it 'initializes Backbone layouts and React components', (done) -> @client.init() _.defer => @EditLayout.callCount.should.equal 1 @EditHeader.callCount.should.equal 1 @EditAdmin.callCount.should.equal 1 @ReactDOM.render.callCount.should.equal 2 done() it 'strips handle fields from authors', (done) -> @article.author = { id: '123' name: 'Artsy Editorial' profile_id: '123' profile_handle: 'Artsy' facebook_handle: 'fbhandle' twitter_handle: 'thandle' } @client.init() _.defer => @client.article.get('author').should.eql { id: '123' name: 'Artsy Editorial' } done()
158773
benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { resolve } = require 'path' rewire = require 'rewire' fixtures = require '../../../../test/helpers/fixtures' xdescribe 'init', -> beforeEach (done) -> @article = fixtures().articles benv.setup => benv.expose _: require('underscore') $: benv.require('jquery') jQuery: benv.require('jquery') sd: { ARTICLE: @article, CURRENT_CHANNEL: id: '456' } window.jQuery = jQuery @client = rewire '../client.coffee' @client.__set__ 'EditLayout', @EditLayout = sinon.stub() @client.__set__ 'EditHeader', @EditHeader = sinon.stub() @client.__set__ 'EditAdmin', @EditAdmin = sinon.stub() @client.__set__ 'EditDisplay', @EditDisplay = sinon.stub() @client.__set__ 'ReactDOM', @ReactDOM = render: sinon.stub() @client.__set__ 'sd', sd done() afterEach -> benv.teardown() it 'initializes Backbone layouts and React components', (done) -> @client.init() _.defer => @EditLayout.callCount.should.equal 1 @EditHeader.callCount.should.equal 1 @EditAdmin.callCount.should.equal 1 @ReactDOM.render.callCount.should.equal 2 done() it 'strips handle fields from authors', (done) -> @article.author = { id: '123' name: '<NAME>' profile_id: '123' profile_handle: 'Artsy' facebook_handle: 'fbhandle' twitter_handle: 'thandle' } @client.init() _.defer => @client.article.get('author').should.eql { id: '123' name: '<NAME>' } done()
true
benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { resolve } = require 'path' rewire = require 'rewire' fixtures = require '../../../../test/helpers/fixtures' xdescribe 'init', -> beforeEach (done) -> @article = fixtures().articles benv.setup => benv.expose _: require('underscore') $: benv.require('jquery') jQuery: benv.require('jquery') sd: { ARTICLE: @article, CURRENT_CHANNEL: id: '456' } window.jQuery = jQuery @client = rewire '../client.coffee' @client.__set__ 'EditLayout', @EditLayout = sinon.stub() @client.__set__ 'EditHeader', @EditHeader = sinon.stub() @client.__set__ 'EditAdmin', @EditAdmin = sinon.stub() @client.__set__ 'EditDisplay', @EditDisplay = sinon.stub() @client.__set__ 'ReactDOM', @ReactDOM = render: sinon.stub() @client.__set__ 'sd', sd done() afterEach -> benv.teardown() it 'initializes Backbone layouts and React components', (done) -> @client.init() _.defer => @EditLayout.callCount.should.equal 1 @EditHeader.callCount.should.equal 1 @EditAdmin.callCount.should.equal 1 @ReactDOM.render.callCount.should.equal 2 done() it 'strips handle fields from authors', (done) -> @article.author = { id: '123' name: 'PI:NAME:<NAME>END_PI' profile_id: '123' profile_handle: 'Artsy' facebook_handle: 'fbhandle' twitter_handle: 'thandle' } @client.init() _.defer => @client.article.get('author').should.eql { id: '123' name: 'PI:NAME:<NAME>END_PI' } done()
[ { "context": "---\nCharset: UTF-8\nVersion: End-To-End v0.3.1337\n\nwf8AAACMAzE3gKsczTvwAQQAhCwBRYAjxk2Zc1Exf98fiC3rT6ntAsh6FHT1ayee\nZIb+KMybq5ZQruCoCfHkQJ0ANfnObqhXxDjE7bTTKz+f9eqwLOfikdQVxWfUn7Tn\nnTOPhlKHlvn8X7KXbD1MX7C7rKESMFwZ1pM3jkEi+gNvJKYdyxVxqhw3eYvC0pKN\nnn3B/wAAAQwDYuz2Vj187EwBCACbsTZ0MK3KLUUsMlj3vfu3vntIPny+R3wxseAM\n9R5PH0BJ37vHP9YOoVjpSpLLaUU9u+JdRMISjq/SJRwMORZSplEEr9syG16rcz8V\n69OF86ofeVrBmeXh7N9Wh5KY2HJz2J6T6+e1B1UATKVEM+lRk32xUB/h5GDn7+hE\nMOwY9IdFfCt6htenGVKl/9apd5OtrjHuTunOsTwNkMLztgXf7S/DE3/n/c4KYvrv\ncO/a4+IroOgXpVkGM0H92XEwT2IjFDPezn/cof/bUSyFQH7S1NVPTA+24sBMalsX\n65BGFvkmeXf/Fjf4934wmbsKfSAplTYiDFOY1+SxVuqSKz3s0v8AAAHdAT/RPLFk\nD/BOQoNzKuOwgaFRO/FJoCbp/Q1g0NaUFP//VCMoudUO3oI+nT1KZjH7mK8nyFxi\nFaSFnbY707WGTuWwLycnNCsk5vypBJcDIEXrZwr6PD1KnMbWWDusP0qe63ITGzSn\n1zeG59bjKbVY07ozh+MBTs2/ffXmjOL3BJZzFiAuYkLcNzboDxvP/nak9XggH4ab\nTiUPcR7w18WzHrNVqKYljH6SxnaY3+LDZg257q9zp87d2GaBeYq11MBV47CPCj1Z\nMufWnI/LR8knv3l1bMdHWn2rVMNikj2Mhkx5UXneuFBGkElgnynCbbcNQuX1rUNI\nIT2jlOArgKeJekEpb2BnFHzENkq784TWepFDs2NilZBApplCOdvgS/gOYw2ntxqi\nqaGMfLvsmXoKwzIEpaVL+SfxVyOoI8vZ1STWsIQ6M9pUXkSQw1vMFo1dR/FzJCky\nQ1RsWHwucFXPLk6QutuKK5wr8PSRZvnchJwQGVhthAwQOmT2F7hXiv0imX4F/HUw\npnBlo+rIGQVaZaULwLJew3HP6QSfV/oOymiHNFkxztm0pvpByor9uom4DezlJmqw\nFVmRsvMbo8KpVZcDjqvbh7Jhkso3mErCgOeEhFVU4FztMMz2is8z\n=yWmD\n-----END PGP MESSAGE-----\n\"\"\"\n\nsender = \"\"\"\n-----", "end": 2053, "score": 0.9966002106666565, "start": 825, "tag": "KEY", "value": "wf8AAACMAzE3gKsczTvwAQQAhCwBRYAjxk2Zc1Exf98fiC3rT6ntAsh6FHT1ayee\nZIb+KMybq5ZQruCoCfHkQJ0ANfnObqhXxDjE7bTTKz+f9eqwLOfikdQVxWfUn7Tn\nnTOPhlKHlvn8X7KXbD1MX7C7rKESMFwZ1pM3jkEi+gNvJKYdyxVxqhw3eYvC0pKN\nnn3B/wAAAQwDYuz2Vj187EwBCACbsTZ0MK3KLUUsMlj3vfu3vntIPny+R3wxseAM\n9R5PH0BJ37vHP9YOoVjpSpLLaUU9u+JdRMISjq/SJRwMORZSplEEr9syG16rcz8V\n69OF86ofeVrBmeXh7N9Wh5KY2HJz2J6T6+e1B1UATKVEM+lRk32xUB/h5GDn7+hE\nMOwY9IdFfCt6htenGVKl/9apd5OtrjHuTunOsTwNkMLztgXf7S/DE3/n/c4KYvrv\ncO/a4+IroOgXpVkGM0H92XEwT2IjFDPezn/cof/bUSyFQH7S1NVPTA+24sBMalsX\n65BGFvkmeXf/Fjf4934wmbsKfSAplTYiDFOY1+SxVuqSKz3s0v8AAAHdAT/RPLFk\nD/BOQoNzKuOwgaFRO/FJoCbp/Q1g0NaUFP//VCMoudUO3oI+nT1KZjH7mK8nyFxi\nFaSFnbY707WGTuWwLycnNCsk5vypBJcDIEXrZwr6PD1KnMbWWDusP0qe63ITGzSn\n1zeG59bjKbVY07ozh+MBTs2/ffXmjOL3BJZzFiAuYkLcNzboDxvP/nak9XggH4ab\nTiUPcR7w18WzHrNVqKYljH6SxnaY3+LDZg257q9zp87d2GaBeYq11MBV47CPCj1Z\nMufWnI/LR8knv3l1bMdHWn2rVMNikj2Mhkx5UXneuFBGkElgnynCbbcNQuX1rUNI\nIT2jlOArgKeJekEpb2BnFHzENkq784TWepFDs2NilZBApplCOdvgS/gOYw2ntxqi\nqaGMfLvsmXoKwzIEpaVL+SfxVyOoI8vZ1STWsIQ6M9pUXkSQw1vMFo1dR/FzJCky\nQ1RsWHwucFXPLk6QutuKK5wr8PSRZvnchJwQGVhthAwQOmT2F7hXiv0imX4F/HUw\npnBlo+rIGQVaZaULwLJew3HP6QSfV/oOymiHNFkxztm0pvpByor9uom4DezlJmqw\nFVmRsvMbo8KpVZcDjqvbh7Jhkso3mErCgOeEhFVU4FztMMz2is8z\n=yWmD" }, { "context": "-BEGIN PGP PUBLIC KEY BLOCK-----\nVersion: GnuPG v1\n\nmQENBFLXMzcBCADirGjknCEDPJkBJtESaojbcHlm5dFXVu/qb2Hs5qAoOjTt6pBH\n3pSuG6GMwASzQd2zfLqyKTKard+BXq/d+FoKHACAHpQF+Yx9yaMYaC6IKty08kBY\nuEndQXv95bFtfq6eiM+pDW4kOFNGNatZU69DbVhB4cE5yhaYJ3jvAud2ijpySWbO\nY3fll+xBYLZuCAcVtwllMEZhUPS9n62+UXsqUFo6NZDS+bDyUdAjwig8DlzrtcL4\n0UGuDXmYRRn+GqSLDPPUm4VUmS+z12V1AFlbLysirWUjnfEKV1e0Ka+b2kc+67Cy\nrgR7KsUnNQnadTbBwzSXRD8PXRqFLXsGr0QDABEBAAG0JUJyb3duIEhhdCAocHcg\naXMgJ2EnKSA8YnJvd25AaGF0LmNvbT6JAT4EEwECACgFAlLXMzcCGwMFCRLMAwAG\nCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEIkj5EKlfhKbDpgIAMiqzRL+DXZf\n5O3wPstxaEmZfYtQeBU9Yew4TsWISAtPYQSG8eMYmV0CXrAOE72gBL49mf1ecciG\nk0pqvWGhRug6Gl2rnlRMxc2s7T3ttVYuWRr7CesOpxkfP4BFp5VTGU/Wp5obtI8u\nOfo+OdrTax97zATyxhhBwTlmccNDCN/i+kENymf0TNlV3Du7hNjoe52CEQYOhTe1\n167VK6pgvWWv1P9cAkUR/bvlpskQYePmGpseOOf+BcGfxrin6by7eNUSu8bWP6tP\nwcMjGDhubX4ZtFkA7lWYsHOLs5mMEjmgg+JTBbosM+DmdRuw8IB5NEco3K5BgjlT\n+3xS4bfHv7O5AQ0EUtczNwEIALBeOQENyziyaydI6LikwHD2WA7GwpJ986181Kut\nwj9PvSjyaR4vD0+e/Tbl/iX+1dLRM2UD9U/vDeac4GvnqmVXJMnftQD4D64A2wTN\nysVSXlNI+L0Yl+V+df7HKIqszmt8easrfgCeh363+++pK5KMDZ1UqAk1sCa8b1D9\nMfrc0u8Gphn/tvzaakAg9T0hGA48UtTfaJbqyMfmjjn+DMzj7+ArbKw3n7BUhKeB\nk2D6q5cl3G3DLxGRyjpGUE3ZKitfukwcDp7JcaQ1wCxMRZUAEPxeQ0fyHObADqsk\nG17kHFCiVT/wGakTSWozqrpW7FnAhQgPphc2yu/bcwFolX8AEQEAAYkBJQQYAQIA\nDwUCUtczNwIbDAUJEswDAAAKCRCJI+RCpX4Sm2p9B/9v58JREsNsUplQsd9o0voj\n6NuGfNlNoEWqrULUxksE0EdT8XyjGIQPpFnu6Nz+W3ahsn9TC51DCBvfl96Cxp73\nualGhhCgicoPy56uhn1ONUI5ZUpNdRVak2DiR3D4Oiq9cHxOCS2HfsagQh8N48vZ\n0o+CYR1T0juQ+k4uKBvYIP+UhNQWtHJREAZXErH2K9mtWHi2K+WBmAntUgvbCl4N\nAsallStnLiwt3UwuuSxqjMjMpiP0OnksixIY6Z+u1IBsw7NI4L0qiHlkFhtzU/5T\nxL/1WMA9k6/0GdTbPlDxpZw5zJLpoahKukiSkuHYBmLl/wXsnzaaCuaU4nVLyCqo\n=Hnne\n-----END PGP PUBLIC KEY BLOCK-----\n\"\"\"\n\nreceiver ", "end": 3784, "score": 0.9990072846412659, "start": 2154, "tag": "KEY", "value": "mQENBFLXMzcBCADirGjknCEDPJkBJtESaojbcHlm5dFXVu/qb2Hs5qAoOjTt6pBH\n3pSuG6GMwASzQd2zfLqyKTKard+BXq/d+FoKHACAHpQF+Yx9yaMYaC6IKty08kBY\nuEndQXv95bFtfq6eiM+pDW4kOFNGNatZU69DbVhB4cE5yhaYJ3jvAud2ijpySWbO\nY3fll+xBYLZuCAcVtwllMEZhUPS9n62+UXsqUFo6NZDS+bDyUdAjwig8DlzrtcL4\n0UGuDXmYRRn+GqSLDPPUm4VUmS+z12V1AFlbLysirWUjnfEKV1e0Ka+b2kc+67Cy\nrgR7KsUnNQnadTbBwzSXRD8PXRqFLXsGr0QDABEBAAG0JUJyb3duIEhhdCAocHcg\naXMgJ2EnKSA8YnJvd25AaGF0LmNvbT6JAT4EEwECACgFAlLXMzcCGwMFCRLMAwAG\nCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEIkj5EKlfhKbDpgIAMiqzRL+DXZf\n5O3wPstxaEmZfYtQeBU9Yew4TsWISAtPYQSG8eMYmV0CXrAOE72gBL49mf1ecciG\nk0pqvWGhRug6Gl2rnlRMxc2s7T3ttVYuWRr7CesOpxkfP4BFp5VTGU/Wp5obtI8u\nOfo+OdrTax97zATyxhhBwTlmccNDCN/i+kENymf0TNlV3Du7hNjoe52CEQYOhTe1\n167VK6pgvWWv1P9cAkUR/bvlpskQYePmGpseOOf+BcGfxrin6by7eNUSu8bWP6tP\nwcMjGDhubX4ZtFkA7lWYsHOLs5mMEjmgg+JTBbosM+DmdRuw8IB5NEco3K5BgjlT\n+3xS4bfHv7O5AQ0EUtczNwEIALBeOQENyziyaydI6LikwHD2WA7GwpJ986181Kut\nwj9PvSjyaR4vD0+e/Tbl/iX+1dLRM2UD9U/vDeac4GvnqmVXJMnftQD4D64A2wTN\nysVSXlNI+L0Yl+V+df7HKIqszmt8easrfgCeh363+++pK5KMDZ1UqAk1sCa8b1D9\nMfrc0u8Gphn/tvzaakAg9T0hGA48UtTfaJbqyMfmjjn+DMzj7+ArbKw3n7BUhKeB\nk2D6q5cl3G3DLxGRyjpGUE3ZKitfukwcDp7JcaQ1wCxMRZUAEPxeQ0fyHObADqsk\nG17kHFCiVT/wGakTSWozqrpW7FnAhQgPphc2yu/bcwFolX8AEQEAAYkBJQQYAQIA\nDwUCUtczNwIbDAUJEswDAAAKCRCJI+RCpX4Sm2p9B/9v58JREsNsUplQsd9o0voj\n6NuGfNlNoEWqrULUxksE0EdT8XyjGIQPpFnu6Nz+W3ahsn9TC51DCBvfl96Cxp73\nualGhhCgicoPy56uhn1ONUI5ZUpNdRVak2DiR3D4Oiq9cHxOCS2HfsagQh8N48vZ\n0o+CYR1T0juQ+k4uKBvYIP+UhNQWtHJREAZXErH2K9mtWHi2K+WBmAntUgvbCl4N\nAsallStnLiwt3UwuuSxqjMjMpiP0OnksixIY6Z+u1IBsw7NI4L0qiHlkFhtzU/5T\nxL/1WMA9k6/0GdTbPlDxpZw5zJLpoahKukiSkuHYBmLl/wXsnzaaCuaU4nVLyCqo\n=Hnne" }, { "context": "EGIN PGP PRIVATE KEY BLOCK-----\nVersion: GnuPG v1\n\nlQH+BFKqadkBBADRQcq97jxrBuQ6pld5Dy7ExJnsOXfDXA90qgEmrN+NiwebAxNA\n+tH0w74y2AIgk4FZWa0iMfknnrJMoCh/wMJ0wgStOFdB4KUdLcsPnRiFeboxSKNt\n+jvF7yKmlaEdf84s8vHzkmhaq/Kz0H9yWFsUJ/CDC1Evq4nDlGUv2EoDVQARAQAB\n/gMDAv2KH4uxX8kXYJsipkn5Y05XBVJIheuk4zBDvk3iGh7r2foAd3jcNTQ9oo+x\nJSopKBdHpIifkX9mimc5hsKVGJt9sTFn6bjTSmnEqOXR4YyETheSbTxI/Ugwz4xV\nPF53KQyhn3y7IX74zXdFSZnjYOwHnHZxKtO3L27WBjp3ylSNohCpxFRs6UV0IBWQ\nptIwyGZKN5M5Fo3diRs0VR/zoAkJ9+yj18xR67UzdPTJ1IjKzbyyvSxqXTwTQjur\nktp31pj7uZnO26ytqL0gGeBkbi5EUgmykgR9KBQe1WyQUIpXN7Qvz8neiaXUu+FZ\nAb47Oa7d/O41IBiFrdyEm2i0ttStuK8BTyhmok3a9CgxZByRa1SGsLxWo2usNWn3\nlBzBGIN5PxaNOQJ+isMn5UFqQYHmL/g0E3PwNcv7gOzcM71zYKaUdTXW7Of9R1eR\nXySkqyTMylkYx+wxoZoFx6UbHKPpJSGDGVRZZ5tYh82vtDNHYXZpcmlsbyBQcmlu\nY2lwIChwdyBpcyAnYScpIDxnbWFuQHRoZWJsYWNraGFuZC5pbz6IvgQTAQIAKAUC\nUqpp2QIbAwUJEswDAAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQ7lwS6m4V\n25Jx1gQAhsJa1ricgM582fvhBqb4VWQXYHBpVNwitmDhwjPYo1Z3Xl4wLQIFIFtU\nT40QqKY5ouUCpvmDdVnAHX+iPpp6/7XWIT2J0RPnTbBAewFhrIsGTsUG8LQjiEfu\nQFO6cyKCFFtRrKkCt024rkkWCOVxulHXFeUs0CPemihr5EujuridAf4EUqpp2QEE\nANbfUDuG0HqwnvXPB6XnLJfw1Pl8Pu33Ef9cDZ3DIkU4rONH6HmrUq55M9TOtXvz\nW1Bb5Fsc6wUQb32CbcrG7LEWR6ddvWxcswV0DMu8G4eoCNBf2kmIxMIAruiXoN21\nv/hw6DxzpQj+CjgNT78CNra5jG6o5bPCtqe0JohqZUTLABEBAAH+AwMC/Yofi7Ff\nyRdgH9ZCGwMDKD5sTR3OviO3c3ofKQvYXsPMqtOpQ0HP0U9OgcPtkYwz1tNETah+\nMztm490J17PcAg+qYFTjXHKNZqDfIkAUgx1w9eqV9Km7slGlscEWX6Id+hSFesnF\n5dGcQIM1vwH46GTxnX0iYcWrJWuWS/g20DK3XW0yXYvK6gqQdZJYSUizGT2OO08V\ndkuIUYzFrSzOjIaO66otAPNSt5Z8YkBkMJBJTI79nOJFdgqTvM1b73LtRsx6eMRH\nIrYV6LcP4o/+evU/qDr4Dx16O/S+0urHIc3jHTBAZCpHJ6xmLp9Lhhf1NWu1T4EF\nIbSwweER9ZfT/rX/+UzxHw4V9jgwQ6/jH/YRPxLqohRYaPy75fplm9uzlfALLuBJ\nJTl65HiN4XI3FuDVXZpW4rXWKPLy11+BxNopaj1UDFwmT9uy4uyKmUcg+tc5K6KX\nQVNIxoKBOtSGXSIQv8OOLTt4gEVTq42IpQQYAQIADwUCUqpp2QIbDAUJEswDAAAK\nCRDuXBLqbhXbkhCoBACDhf57GrX7Andusgs/wjOLviwGYDRA2dRaTUp1UD3aT+Tu\noD9Y02htJm9bnTYI0fP/dJBEUpSdQIHIYxofS6EjoWvUn6mMOA/dl6VmDQrDWRa+\nS+f5fpq6yFTc0e3JlvJuNwFhX+3qbmvMQRcJSxisW+0CMbX9swMtPS3UAD", "end": 5790, "score": 0.9991837739944458, "start": 3897, "tag": "KEY", "value": "lQH+BFKqadkBBADRQcq97jxrBuQ6pld5Dy7ExJnsOXfDXA90qgEmrN+NiwebAxNA\n+tH0w74y2AIgk4FZWa0iMfknnrJMoCh/wMJ0wgStOFdB4KUdLcsPnRiFeboxSKNt\n+jvF7yKmlaEdf84s8vHzkmhaq/Kz0H9yWFsUJ/CDC1Evq4nDlGUv2EoDVQARAQAB\n/gMDAv2KH4uxX8kXYJsipkn5Y05XBVJIheuk4zBDvk3iGh7r2foAd3jcNTQ9oo+x\nJSopKBdHpIifkX9mimc5hsKVGJt9sTFn6bjTSmnEqOXR4YyETheSbTxI/Ugwz4xV\nPF53KQyhn3y7IX74zXdFSZnjYOwHnHZxKtO3L27WBjp3ylSNohCpxFRs6UV0IBWQ\nptIwyGZKN5M5Fo3diRs0VR/zoAkJ9+yj18xR67UzdPTJ1IjKzbyyvSxqXTwTQjur\nktp31pj7uZnO26ytqL0gGeBkbi5EUgmykgR9KBQe1WyQUIpXN7Qvz8neiaXUu+FZ\nAb47Oa7d/O41IBiFrdyEm2i0ttStuK8BTyhmok3a9CgxZByRa1SGsLxWo2usNWn3\nlBzBGIN5PxaNOQJ+isMn5UFqQYHmL/g0E3PwNcv7gOzcM71zYKaUdTXW7Of9R1eR\nXySkqyTMylkYx+wxoZoFx6UbHKPpJSGDGVRZZ5tYh82vtDNHYXZpcmlsbyBQcmlu\nY2lwIChwdyBpcyAnYScpIDxnbWFuQHRoZWJsYWNraGFuZC5pbz6IvgQTAQIAKAUC\nUqpp2QIbAwUJEswDAAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQ7lwS6m4V\n25Jx1gQAhsJa1ricgM582fvhBqb4VWQXYHBpVNwitmDhwjPYo1Z3Xl4wLQIFIFtU\nT40QqKY5ouUCpvmDdVnAHX+iPpp6/7XWIT2J0RPnTbBAewFhrIsGTsUG8LQjiEfu\nQFO6cyKCFFtRrKkCt024rkkWCOVxulHXFeUs0CPemihr5EujuridAf4EUqpp2QEE\nANbfUDuG0HqwnvXPB6XnLJfw1Pl8Pu33Ef9cDZ3DIkU4rONH6HmrUq55M9TOtXvz\nW1Bb5Fsc6wUQb32CbcrG7LEWR6ddvWxcswV0DMu8G4eoCNBf2kmIxMIAruiXoN21\nv/hw6DxzpQj+CjgNT78CNra5jG6o5bPCtqe0JohqZUTLABEBAAH+AwMC/Yofi7Ff\nyRdgH9ZCGwMDKD5sTR3OviO3c3ofKQvYXsPMqtOpQ0HP0U9OgcPtkYwz1tNETah+\nMztm490J17PcAg+qYFTjXHKNZqDfIkAUgx1w9eqV9Km7slGlscEWX6Id+hSFesnF\n5dGcQIM1vwH46GTxnX0iYcWrJWuWS/g20DK3XW0yXYvK6gqQdZJYSUizGT2OO08V\ndkuIUYzFrSzOjIaO66otAPNSt5Z8YkBkMJBJTI79nOJFdgqTvM1b73LtRsx6eMRH\nIrYV6LcP4o/+evU/qDr4Dx16O/S+0urHIc3jHTBAZCpHJ6xmLp9Lhhf1NWu1T4EF\nIbSwweER9ZfT/rX/+UzxHw4V9jgwQ6/jH/YRPxLqohRYaPy75fplm9uzlfALLuBJ\nJTl65HiN4XI3FuDVXZpW4rXWKPLy11+BxNopaj1UDFwmT9uy4uyKmUcg+tc5K6KX\nQVNIxoKBOtSGXSIQv8OOLTt4gEVTq42IpQQYAQIADwUCUqpp2QIbDAUJEswDAAAK\nCRDuXBLqbhXbkhCoBACDhf57GrX7Andusgs/wjOLviwGYDRA2dRaTUp1UD3aT+Tu\noD9Y02htJm9bnTYI0fP/dJBEUpSdQIHIYxofS6EjoWvUn6mMOA/dl6VmDQrDWRa+\nS+f5fpq6" }, { "context": "END PGP PRIVATE KEY BLOCK-----\n\"\"\"\n\npassphrase = \"a\"\n\n#==============================================", "end": 5909, "score": 0.9981540441513062, "start": 5908, "tag": "PASSWORD", "value": "a" } ]
test/files/google_end_to_end.iced
samkenxstream/kbpgp
464
{parse} = require '../../lib/openpgp/parser' armor = require '../../lib/openpgp/armor' C = require '../../lib/const' {do_message,Message} = require '../../lib/openpgp/processor' util = require 'util' {unix_time,katch,ASP} = require '../../lib/util' {KeyManager} = require '../../' {import_key_pgp} = require '../../lib/symmetric' {decrypt} = require '../../lib/openpgp/ocfb' {PgpKeyRing} = require '../../lib/keyring' {Literal} = require '../../lib/openpgp/packet/literal' {burn} = require '../../lib/openpgp/burner' clearsign = require '../../lib/openpgp/clearsign' detachsign = require '../../lib/openpgp/detachsign' hashmod = require '../../lib/hash' #=============================================================================== message = """ -----BEGIN PGP MESSAGE----- Charset: UTF-8 Version: End-To-End v0.3.1337 wf8AAACMAzE3gKsczTvwAQQAhCwBRYAjxk2Zc1Exf98fiC3rT6ntAsh6FHT1ayee ZIb+KMybq5ZQruCoCfHkQJ0ANfnObqhXxDjE7bTTKz+f9eqwLOfikdQVxWfUn7Tn nTOPhlKHlvn8X7KXbD1MX7C7rKESMFwZ1pM3jkEi+gNvJKYdyxVxqhw3eYvC0pKN nn3B/wAAAQwDYuz2Vj187EwBCACbsTZ0MK3KLUUsMlj3vfu3vntIPny+R3wxseAM 9R5PH0BJ37vHP9YOoVjpSpLLaUU9u+JdRMISjq/SJRwMORZSplEEr9syG16rcz8V 69OF86ofeVrBmeXh7N9Wh5KY2HJz2J6T6+e1B1UATKVEM+lRk32xUB/h5GDn7+hE MOwY9IdFfCt6htenGVKl/9apd5OtrjHuTunOsTwNkMLztgXf7S/DE3/n/c4KYvrv cO/a4+IroOgXpVkGM0H92XEwT2IjFDPezn/cof/bUSyFQH7S1NVPTA+24sBMalsX 65BGFvkmeXf/Fjf4934wmbsKfSAplTYiDFOY1+SxVuqSKz3s0v8AAAHdAT/RPLFk D/BOQoNzKuOwgaFRO/FJoCbp/Q1g0NaUFP//VCMoudUO3oI+nT1KZjH7mK8nyFxi FaSFnbY707WGTuWwLycnNCsk5vypBJcDIEXrZwr6PD1KnMbWWDusP0qe63ITGzSn 1zeG59bjKbVY07ozh+MBTs2/ffXmjOL3BJZzFiAuYkLcNzboDxvP/nak9XggH4ab TiUPcR7w18WzHrNVqKYljH6SxnaY3+LDZg257q9zp87d2GaBeYq11MBV47CPCj1Z MufWnI/LR8knv3l1bMdHWn2rVMNikj2Mhkx5UXneuFBGkElgnynCbbcNQuX1rUNI IT2jlOArgKeJekEpb2BnFHzENkq784TWepFDs2NilZBApplCOdvgS/gOYw2ntxqi qaGMfLvsmXoKwzIEpaVL+SfxVyOoI8vZ1STWsIQ6M9pUXkSQw1vMFo1dR/FzJCky Q1RsWHwucFXPLk6QutuKK5wr8PSRZvnchJwQGVhthAwQOmT2F7hXiv0imX4F/HUw pnBlo+rIGQVaZaULwLJew3HP6QSfV/oOymiHNFkxztm0pvpByor9uom4DezlJmqw FVmRsvMbo8KpVZcDjqvbh7Jhkso3mErCgOeEhFVU4FztMMz2is8z =yWmD -----END PGP MESSAGE----- """ sender = """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1 mQENBFLXMzcBCADirGjknCEDPJkBJtESaojbcHlm5dFXVu/qb2Hs5qAoOjTt6pBH 3pSuG6GMwASzQd2zfLqyKTKard+BXq/d+FoKHACAHpQF+Yx9yaMYaC6IKty08kBY uEndQXv95bFtfq6eiM+pDW4kOFNGNatZU69DbVhB4cE5yhaYJ3jvAud2ijpySWbO Y3fll+xBYLZuCAcVtwllMEZhUPS9n62+UXsqUFo6NZDS+bDyUdAjwig8DlzrtcL4 0UGuDXmYRRn+GqSLDPPUm4VUmS+z12V1AFlbLysirWUjnfEKV1e0Ka+b2kc+67Cy rgR7KsUnNQnadTbBwzSXRD8PXRqFLXsGr0QDABEBAAG0JUJyb3duIEhhdCAocHcg aXMgJ2EnKSA8YnJvd25AaGF0LmNvbT6JAT4EEwECACgFAlLXMzcCGwMFCRLMAwAG CwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEIkj5EKlfhKbDpgIAMiqzRL+DXZf 5O3wPstxaEmZfYtQeBU9Yew4TsWISAtPYQSG8eMYmV0CXrAOE72gBL49mf1ecciG k0pqvWGhRug6Gl2rnlRMxc2s7T3ttVYuWRr7CesOpxkfP4BFp5VTGU/Wp5obtI8u Ofo+OdrTax97zATyxhhBwTlmccNDCN/i+kENymf0TNlV3Du7hNjoe52CEQYOhTe1 167VK6pgvWWv1P9cAkUR/bvlpskQYePmGpseOOf+BcGfxrin6by7eNUSu8bWP6tP wcMjGDhubX4ZtFkA7lWYsHOLs5mMEjmgg+JTBbosM+DmdRuw8IB5NEco3K5BgjlT +3xS4bfHv7O5AQ0EUtczNwEIALBeOQENyziyaydI6LikwHD2WA7GwpJ986181Kut wj9PvSjyaR4vD0+e/Tbl/iX+1dLRM2UD9U/vDeac4GvnqmVXJMnftQD4D64A2wTN ysVSXlNI+L0Yl+V+df7HKIqszmt8easrfgCeh363+++pK5KMDZ1UqAk1sCa8b1D9 Mfrc0u8Gphn/tvzaakAg9T0hGA48UtTfaJbqyMfmjjn+DMzj7+ArbKw3n7BUhKeB k2D6q5cl3G3DLxGRyjpGUE3ZKitfukwcDp7JcaQ1wCxMRZUAEPxeQ0fyHObADqsk G17kHFCiVT/wGakTSWozqrpW7FnAhQgPphc2yu/bcwFolX8AEQEAAYkBJQQYAQIA DwUCUtczNwIbDAUJEswDAAAKCRCJI+RCpX4Sm2p9B/9v58JREsNsUplQsd9o0voj 6NuGfNlNoEWqrULUxksE0EdT8XyjGIQPpFnu6Nz+W3ahsn9TC51DCBvfl96Cxp73 ualGhhCgicoPy56uhn1ONUI5ZUpNdRVak2DiR3D4Oiq9cHxOCS2HfsagQh8N48vZ 0o+CYR1T0juQ+k4uKBvYIP+UhNQWtHJREAZXErH2K9mtWHi2K+WBmAntUgvbCl4N AsallStnLiwt3UwuuSxqjMjMpiP0OnksixIY6Z+u1IBsw7NI4L0qiHlkFhtzU/5T xL/1WMA9k6/0GdTbPlDxpZw5zJLpoahKukiSkuHYBmLl/wXsnzaaCuaU4nVLyCqo =Hnne -----END PGP PUBLIC KEY BLOCK----- """ receiver = """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v1 lQH+BFKqadkBBADRQcq97jxrBuQ6pld5Dy7ExJnsOXfDXA90qgEmrN+NiwebAxNA +tH0w74y2AIgk4FZWa0iMfknnrJMoCh/wMJ0wgStOFdB4KUdLcsPnRiFeboxSKNt +jvF7yKmlaEdf84s8vHzkmhaq/Kz0H9yWFsUJ/CDC1Evq4nDlGUv2EoDVQARAQAB /gMDAv2KH4uxX8kXYJsipkn5Y05XBVJIheuk4zBDvk3iGh7r2foAd3jcNTQ9oo+x JSopKBdHpIifkX9mimc5hsKVGJt9sTFn6bjTSmnEqOXR4YyETheSbTxI/Ugwz4xV PF53KQyhn3y7IX74zXdFSZnjYOwHnHZxKtO3L27WBjp3ylSNohCpxFRs6UV0IBWQ ptIwyGZKN5M5Fo3diRs0VR/zoAkJ9+yj18xR67UzdPTJ1IjKzbyyvSxqXTwTQjur ktp31pj7uZnO26ytqL0gGeBkbi5EUgmykgR9KBQe1WyQUIpXN7Qvz8neiaXUu+FZ Ab47Oa7d/O41IBiFrdyEm2i0ttStuK8BTyhmok3a9CgxZByRa1SGsLxWo2usNWn3 lBzBGIN5PxaNOQJ+isMn5UFqQYHmL/g0E3PwNcv7gOzcM71zYKaUdTXW7Of9R1eR XySkqyTMylkYx+wxoZoFx6UbHKPpJSGDGVRZZ5tYh82vtDNHYXZpcmlsbyBQcmlu Y2lwIChwdyBpcyAnYScpIDxnbWFuQHRoZWJsYWNraGFuZC5pbz6IvgQTAQIAKAUC Uqpp2QIbAwUJEswDAAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQ7lwS6m4V 25Jx1gQAhsJa1ricgM582fvhBqb4VWQXYHBpVNwitmDhwjPYo1Z3Xl4wLQIFIFtU T40QqKY5ouUCpvmDdVnAHX+iPpp6/7XWIT2J0RPnTbBAewFhrIsGTsUG8LQjiEfu QFO6cyKCFFtRrKkCt024rkkWCOVxulHXFeUs0CPemihr5EujuridAf4EUqpp2QEE ANbfUDuG0HqwnvXPB6XnLJfw1Pl8Pu33Ef9cDZ3DIkU4rONH6HmrUq55M9TOtXvz W1Bb5Fsc6wUQb32CbcrG7LEWR6ddvWxcswV0DMu8G4eoCNBf2kmIxMIAruiXoN21 v/hw6DxzpQj+CjgNT78CNra5jG6o5bPCtqe0JohqZUTLABEBAAH+AwMC/Yofi7Ff yRdgH9ZCGwMDKD5sTR3OviO3c3ofKQvYXsPMqtOpQ0HP0U9OgcPtkYwz1tNETah+ Mztm490J17PcAg+qYFTjXHKNZqDfIkAUgx1w9eqV9Km7slGlscEWX6Id+hSFesnF 5dGcQIM1vwH46GTxnX0iYcWrJWuWS/g20DK3XW0yXYvK6gqQdZJYSUizGT2OO08V dkuIUYzFrSzOjIaO66otAPNSt5Z8YkBkMJBJTI79nOJFdgqTvM1b73LtRsx6eMRH IrYV6LcP4o/+evU/qDr4Dx16O/S+0urHIc3jHTBAZCpHJ6xmLp9Lhhf1NWu1T4EF IbSwweER9ZfT/rX/+UzxHw4V9jgwQ6/jH/YRPxLqohRYaPy75fplm9uzlfALLuBJ JTl65HiN4XI3FuDVXZpW4rXWKPLy11+BxNopaj1UDFwmT9uy4uyKmUcg+tc5K6KX QVNIxoKBOtSGXSIQv8OOLTt4gEVTq42IpQQYAQIADwUCUqpp2QIbDAUJEswDAAAK CRDuXBLqbhXbkhCoBACDhf57GrX7Andusgs/wjOLviwGYDRA2dRaTUp1UD3aT+Tu oD9Y02htJm9bnTYI0fP/dJBEUpSdQIHIYxofS6EjoWvUn6mMOA/dl6VmDQrDWRa+ S+f5fpq6yFTc0e3JlvJuNwFhX+3qbmvMQRcJSxisW+0CMbX9swMtPS3UADbmNw== =4Gpg -----END PGP PRIVATE KEY BLOCK----- """ passphrase = "a" #============================================================================= ring = null #============================================================================= testing_unixtime = Math.floor(new Date(2014, 6, 4)/1000) exports.init = (T,cb) -> ring = new PgpKeyRing() opts = now : testing_unixtime await KeyManager.import_from_armored_pgp { raw : receiver, opts }, defer err, km T.no_error err await km.unlock_pgp { passphrase }, defer err T.no_error ring.add_key_manager km await KeyManager.import_from_armored_pgp { raw : sender, opts }, defer err, km T.no_error err ring.add_key_manager km cb() #============================================================================= exports.test_decrypt = (T,cb) -> await do_message { keyfetch : ring, armored : message, now : testing_unixtime }, defer err, literals T.no_error err cb() #=============================================================================
113376
{parse} = require '../../lib/openpgp/parser' armor = require '../../lib/openpgp/armor' C = require '../../lib/const' {do_message,Message} = require '../../lib/openpgp/processor' util = require 'util' {unix_time,katch,ASP} = require '../../lib/util' {KeyManager} = require '../../' {import_key_pgp} = require '../../lib/symmetric' {decrypt} = require '../../lib/openpgp/ocfb' {PgpKeyRing} = require '../../lib/keyring' {Literal} = require '../../lib/openpgp/packet/literal' {burn} = require '../../lib/openpgp/burner' clearsign = require '../../lib/openpgp/clearsign' detachsign = require '../../lib/openpgp/detachsign' hashmod = require '../../lib/hash' #=============================================================================== message = """ -----BEGIN PGP MESSAGE----- Charset: UTF-8 Version: End-To-End v0.3.1337 <KEY> -----END PGP MESSAGE----- """ sender = """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1 <KEY> -----END PGP PUBLIC KEY BLOCK----- """ receiver = """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v1 <KEY>yFTc0e3JlvJuNwFhX+3qbmvMQRcJSxisW+0CMbX9swMtPS3UADbmNw== =4Gpg -----END PGP PRIVATE KEY BLOCK----- """ passphrase = "<PASSWORD>" #============================================================================= ring = null #============================================================================= testing_unixtime = Math.floor(new Date(2014, 6, 4)/1000) exports.init = (T,cb) -> ring = new PgpKeyRing() opts = now : testing_unixtime await KeyManager.import_from_armored_pgp { raw : receiver, opts }, defer err, km T.no_error err await km.unlock_pgp { passphrase }, defer err T.no_error ring.add_key_manager km await KeyManager.import_from_armored_pgp { raw : sender, opts }, defer err, km T.no_error err ring.add_key_manager km cb() #============================================================================= exports.test_decrypt = (T,cb) -> await do_message { keyfetch : ring, armored : message, now : testing_unixtime }, defer err, literals T.no_error err cb() #=============================================================================
true
{parse} = require '../../lib/openpgp/parser' armor = require '../../lib/openpgp/armor' C = require '../../lib/const' {do_message,Message} = require '../../lib/openpgp/processor' util = require 'util' {unix_time,katch,ASP} = require '../../lib/util' {KeyManager} = require '../../' {import_key_pgp} = require '../../lib/symmetric' {decrypt} = require '../../lib/openpgp/ocfb' {PgpKeyRing} = require '../../lib/keyring' {Literal} = require '../../lib/openpgp/packet/literal' {burn} = require '../../lib/openpgp/burner' clearsign = require '../../lib/openpgp/clearsign' detachsign = require '../../lib/openpgp/detachsign' hashmod = require '../../lib/hash' #=============================================================================== message = """ -----BEGIN PGP MESSAGE----- Charset: UTF-8 Version: End-To-End v0.3.1337 PI:KEY:<KEY>END_PI -----END PGP MESSAGE----- """ sender = """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1 PI:KEY:<KEY>END_PI -----END PGP PUBLIC KEY BLOCK----- """ receiver = """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v1 PI:KEY:<KEY>END_PIyFTc0e3JlvJuNwFhX+3qbmvMQRcJSxisW+0CMbX9swMtPS3UADbmNw== =4Gpg -----END PGP PRIVATE KEY BLOCK----- """ passphrase = "PI:PASSWORD:<PASSWORD>END_PI" #============================================================================= ring = null #============================================================================= testing_unixtime = Math.floor(new Date(2014, 6, 4)/1000) exports.init = (T,cb) -> ring = new PgpKeyRing() opts = now : testing_unixtime await KeyManager.import_from_armored_pgp { raw : receiver, opts }, defer err, km T.no_error err await km.unlock_pgp { passphrase }, defer err T.no_error ring.add_key_manager km await KeyManager.import_from_armored_pgp { raw : sender, opts }, defer err, km T.no_error err ring.add_key_manager km cb() #============================================================================= exports.test_decrypt = (T,cb) -> await do_message { keyfetch : ring, armored : message, now : testing_unixtime }, defer err, literals T.no_error err cb() #=============================================================================
[ { "context": "et: (->)\n results: @results\n term: 'skull'\n crop: sinon.stub()\n _s: _s\n ", "end": 1374, "score": 0.5008082389831543, "start": 1369, "tag": "NAME", "value": "skull" } ]
src/desktop/apps/search/test/template.coffee
kanaabe/force
1
benv = require 'benv' _ = require 'underscore' _s = require 'underscore.string' jade = require 'jade' path = require 'path' fs = require 'fs' Backbone = require 'backbone' { fabricate } = require 'antigravity' Search = require '../../../collections/search' SearchResult = require '../../../models/search_result' sinon = require 'sinon' fixture = require '../../../test/helpers/fixtures.coffee' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Search results template', -> before (done) -> benv.setup => benv.expose { $: benv.require 'jquery'} done() after -> benv.teardown() beforeEach -> @search = new Search describe 'No results', -> beforeEach -> @template = render('template')( sd: {} asset: (->) results: @search.models term: 'foobar' crop: sinon.stub() _s: _s ) it 'displays a message to the user that nothing can be found', -> @template.should.containEql 'Nothing found' describe 'Has results', -> beforeEach -> @results = _.times 3, -> new SearchResult(fixture.searchResult) template = render('template')( sd: {} asset: (->) results: @results term: 'skull' crop: sinon.stub() _s: _s ) @$template = $(template) it 'renders the search results', -> @$template.find('.search-result').length.should.equal 3 it 'highlights the search term', -> @$template.find('.is-highlighted').should.be.ok() describe 'Creates img tag with empty string', -> beforeEach -> @result = new SearchResult fixture.searchResult template = render('search_result')( sd: {} result: @result term: 'skull' crop: sinon.stub() _s: _s ) @$template = $(template) it 'creates img tag', -> @$template.find('.search-result-thumbnail-fallback img').length.should.equal 1
135679
benv = require 'benv' _ = require 'underscore' _s = require 'underscore.string' jade = require 'jade' path = require 'path' fs = require 'fs' Backbone = require 'backbone' { fabricate } = require 'antigravity' Search = require '../../../collections/search' SearchResult = require '../../../models/search_result' sinon = require 'sinon' fixture = require '../../../test/helpers/fixtures.coffee' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Search results template', -> before (done) -> benv.setup => benv.expose { $: benv.require 'jquery'} done() after -> benv.teardown() beforeEach -> @search = new Search describe 'No results', -> beforeEach -> @template = render('template')( sd: {} asset: (->) results: @search.models term: 'foobar' crop: sinon.stub() _s: _s ) it 'displays a message to the user that nothing can be found', -> @template.should.containEql 'Nothing found' describe 'Has results', -> beforeEach -> @results = _.times 3, -> new SearchResult(fixture.searchResult) template = render('template')( sd: {} asset: (->) results: @results term: '<NAME>' crop: sinon.stub() _s: _s ) @$template = $(template) it 'renders the search results', -> @$template.find('.search-result').length.should.equal 3 it 'highlights the search term', -> @$template.find('.is-highlighted').should.be.ok() describe 'Creates img tag with empty string', -> beforeEach -> @result = new SearchResult fixture.searchResult template = render('search_result')( sd: {} result: @result term: 'skull' crop: sinon.stub() _s: _s ) @$template = $(template) it 'creates img tag', -> @$template.find('.search-result-thumbnail-fallback img').length.should.equal 1
true
benv = require 'benv' _ = require 'underscore' _s = require 'underscore.string' jade = require 'jade' path = require 'path' fs = require 'fs' Backbone = require 'backbone' { fabricate } = require 'antigravity' Search = require '../../../collections/search' SearchResult = require '../../../models/search_result' sinon = require 'sinon' fixture = require '../../../test/helpers/fixtures.coffee' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Search results template', -> before (done) -> benv.setup => benv.expose { $: benv.require 'jquery'} done() after -> benv.teardown() beforeEach -> @search = new Search describe 'No results', -> beforeEach -> @template = render('template')( sd: {} asset: (->) results: @search.models term: 'foobar' crop: sinon.stub() _s: _s ) it 'displays a message to the user that nothing can be found', -> @template.should.containEql 'Nothing found' describe 'Has results', -> beforeEach -> @results = _.times 3, -> new SearchResult(fixture.searchResult) template = render('template')( sd: {} asset: (->) results: @results term: 'PI:NAME:<NAME>END_PI' crop: sinon.stub() _s: _s ) @$template = $(template) it 'renders the search results', -> @$template.find('.search-result').length.should.equal 3 it 'highlights the search term', -> @$template.find('.is-highlighted').should.be.ok() describe 'Creates img tag with empty string', -> beforeEach -> @result = new SearchResult fixture.searchResult template = render('search_result')( sd: {} result: @result term: 'skull' crop: sinon.stub() _s: _s ) @$template = $(template) it 'creates img tag', -> @$template.find('.search-result-thumbnail-fallback img').length.should.equal 1
[ { "context": "roduct_variation', ->\n key = $(this).attr('data-id')\n $(this).find('input, select').each(->\n ", "end": 3213, "score": 0.9772469997406006, "start": 3211, "tag": "KEY", "value": "id" } ]
app/assets/javascripts/plugins/ecommerce/admin_product.js.coffee
densitylabs/camaleon-ecommerce
0
$ -> form = $('#form-post') variation_id = 1 product_variations = form.find('#product_variations') form.find('.content-frame-body > .c-field-group:last').after(product_variations.removeClass('hidden')) SERVICE_PRODUCT_TYPE = "service_product" # this variables is defined in _variations.html.erb product_type = ORIGIN_PRODUCT_TYPE # photo uploader product_variations.on('click', '.product_variation_photo_link', -> $input = $(this).prev() $.fn.upload_filemanager({ formats: "image", dimension: $input.attr("data-dimension") || '', versions: $input.attr("data-versions") || '', thumb_size: $input.attr("data-thumb_size") || '', selected: (file, response) -> $input.val(file.url); }) return false ) cache_variation = product_variations.find('.blank_product_variation').remove().clone().removeClass('hidden') cache_values = cache_variation.find('.sortable_values > li:first').remove().clone() # change product_type form.on('change', '.c-field-group .item-custom-field[data-field-key="ecommerce_product_type"] select', -> product_type = $(this).val() check_product_type() ) # Add min value and step options to hours field form.find('.c-field-group .item-custom-field[data-field-key="ecommerce_hours"] input[type="number"]').attr({'min': 0, 'step': 0.5}) # add new variation product_variations.find('.add_new_variation').click -> clone = cache_variation.clone().attr('data-id', 'new_'+variation_id+=1) product_variations.children('.variations_sortable').append(clone) clone.trigger('fill_variation_id') if product_type == SERVICE_PRODUCT_TYPE fields_not_required = clone.find('.fn-not-service-product-required') clone.find('.fn-product-variation-field').attr('value', SERVICE_PRODUCT_TYPE) for p_field in fields_not_required $(p_field).hide().find('.required').addClass('e_skip_required').removeClass('required') else fields_not_required = clone.find('.fn-not-physical-product-required') for p_field in fields_not_required $(p_field).hide().find('.required').addClass('e_skip_required').removeClass('required') check_variation_status() return false # add new variation value product_variations.on('click', '.add_new_value', -> clone = cache_values.clone() key = $(this).closest('.product_variation').attr('data-id') clone.find('input, select').each(-> $(this).attr('name', $(this).attr('name').replace('[]', '['+key+']')).removeAttr('id') ) $(this).closest('.variation_attributes').find('.sortable_values').append(clone) clone.find('.product_attribute_select').trigger('change') return false ) # change attribute product_variations.on('change', '.product_attribute_select', -> v = $(this).val() sel = $(this).closest('.row').find('.product_attribute_vals_select').html('') for attr in PRODUCT_ATTRIBUTES if `attr.id == v` for value in attr.translated_values sel.append('<option value="'+value.id+'">'+value.label.replace(/</g, '&lt;')+'</option>') ) product_variations.on('fill_variation_id', '.product_variation', -> key = $(this).attr('data-id') $(this).find('input, select').each(-> $(this).attr('name', $(this).attr('name').replace('[]', '['+key+']')).removeAttr('id') ) $(this).find('.sortable_values').sortable({handle: '.val_sorter'}) ) # sortables product_variations.find('.sortable_values').sortable({handle: '.val_sorter'}) product_variations.find('.variations_sortable').sortable({handle: '.variation_sorter', update: ()-> $(this).children().each((index)-> $(this).find('.product_variation_position').val(index); ) }) # delete actions product_variations.on('click', '.val_del', -> $(this).closest('li').fadeOut('slow', -> $(this).remove() ) return false ) product_variations.on('click', '.var_del', -> unless confirm(product_variations.attr('data-confirm-msg')) return false $(this).closest('.product_variation').fadeOut('slow', -> $(this).remove() check_variation_status() ) return false ) set_variantion_physical_product_fields = (p_variation, hide_fields) -> fields_not_required = $(p_variation) .find('.fn-not-service-product-required') set_variantion_fields(fields_not_required, hide_fields) $(p_variation) .find('.fn-product-variation-field') .attr('value', product_type) set_variantion_service_product_fields = (p_variation, hide_fields) -> fields_not_required = $(p_variation) .find('.fn-not-physical-product-required') set_variantion_fields(fields_not_required, !hide_fields) set_variantion_fields = (fields_not_required, hide_fields) -> for p_field in fields_not_required if hide_fields $(p_field) .hide() .find('.required') .addClass('e_skip_required') .removeClass('required') else $(p_field) .show() .find('.e_skip_required') .removeClass('e_skip_required') .addClass('required') set_physical_product_fields = (hide_fields) -> set_fields(['ecommerce_weight', 'ecommerce_qty'], hide_fields) set_service_product_fields = (hide_fields) -> set_fields(['ecommerce_bucket', 'ecommerce_hours'], !hide_fields) set_fields = (not_physical_product_field_keys, hide_fields) -> for field_key in not_physical_product_field_keys p_field = form .find( '.c-field-group .item-custom-field[data-field-key="' + field_key + '"]' ) if hide_fields p_field .hide() .find('.required') .addClass('e_skip_required') .removeClass('required') else p_field .show() .find('.e_skip_required') .removeClass('e_skip_required') .addClass('required') check_product_type = -> if product_variations.find('.product_variation').length > 0 for p_variation in product_variations.find('.product_variation') set_variantion_physical_product_fields( p_variation, product_type == SERVICE_PRODUCT_TYPE ) set_variantion_service_product_fields( p_variation, product_type == SERVICE_PRODUCT_TYPE ) else set_physical_product_fields(product_type == SERVICE_PRODUCT_TYPE) set_service_product_fields(product_type == SERVICE_PRODUCT_TYPE) check_product_type() # check the variation status and disable or enable some custom fields check_variation_status = -> fields = ['ecommerce_sku', 'ecommerce_price','ecommerce_stock', 'ecommerce_photos', 'ecommerce_bucket', 'ecommerce_hours'] if product_variations.find('.product_variation').length > 0 fields.push('ecommerce_weight', 'ecommerce_qty') for key in fields p_field = form.find('.c-field-group .item-custom-field[data-field-key="'+key+'"]') p_field.hide() .find('.required') .addClass('e_skip_required') .removeClass('required') else if product_type != SERVICE_PRODUCT_TYPE fields.splice(4,2, 'ecommerce_weight', 'ecommerce_qty') for key in fields p_field = form.find('.c-field-group .item-custom-field[data-field-key="'+key+'"]') p_field.show() .find('.e_skip_required') .removeClass('e_skip_required') .addClass('required') check_variation_status()
94544
$ -> form = $('#form-post') variation_id = 1 product_variations = form.find('#product_variations') form.find('.content-frame-body > .c-field-group:last').after(product_variations.removeClass('hidden')) SERVICE_PRODUCT_TYPE = "service_product" # this variables is defined in _variations.html.erb product_type = ORIGIN_PRODUCT_TYPE # photo uploader product_variations.on('click', '.product_variation_photo_link', -> $input = $(this).prev() $.fn.upload_filemanager({ formats: "image", dimension: $input.attr("data-dimension") || '', versions: $input.attr("data-versions") || '', thumb_size: $input.attr("data-thumb_size") || '', selected: (file, response) -> $input.val(file.url); }) return false ) cache_variation = product_variations.find('.blank_product_variation').remove().clone().removeClass('hidden') cache_values = cache_variation.find('.sortable_values > li:first').remove().clone() # change product_type form.on('change', '.c-field-group .item-custom-field[data-field-key="ecommerce_product_type"] select', -> product_type = $(this).val() check_product_type() ) # Add min value and step options to hours field form.find('.c-field-group .item-custom-field[data-field-key="ecommerce_hours"] input[type="number"]').attr({'min': 0, 'step': 0.5}) # add new variation product_variations.find('.add_new_variation').click -> clone = cache_variation.clone().attr('data-id', 'new_'+variation_id+=1) product_variations.children('.variations_sortable').append(clone) clone.trigger('fill_variation_id') if product_type == SERVICE_PRODUCT_TYPE fields_not_required = clone.find('.fn-not-service-product-required') clone.find('.fn-product-variation-field').attr('value', SERVICE_PRODUCT_TYPE) for p_field in fields_not_required $(p_field).hide().find('.required').addClass('e_skip_required').removeClass('required') else fields_not_required = clone.find('.fn-not-physical-product-required') for p_field in fields_not_required $(p_field).hide().find('.required').addClass('e_skip_required').removeClass('required') check_variation_status() return false # add new variation value product_variations.on('click', '.add_new_value', -> clone = cache_values.clone() key = $(this).closest('.product_variation').attr('data-id') clone.find('input, select').each(-> $(this).attr('name', $(this).attr('name').replace('[]', '['+key+']')).removeAttr('id') ) $(this).closest('.variation_attributes').find('.sortable_values').append(clone) clone.find('.product_attribute_select').trigger('change') return false ) # change attribute product_variations.on('change', '.product_attribute_select', -> v = $(this).val() sel = $(this).closest('.row').find('.product_attribute_vals_select').html('') for attr in PRODUCT_ATTRIBUTES if `attr.id == v` for value in attr.translated_values sel.append('<option value="'+value.id+'">'+value.label.replace(/</g, '&lt;')+'</option>') ) product_variations.on('fill_variation_id', '.product_variation', -> key = $(this).attr('data-<KEY>') $(this).find('input, select').each(-> $(this).attr('name', $(this).attr('name').replace('[]', '['+key+']')).removeAttr('id') ) $(this).find('.sortable_values').sortable({handle: '.val_sorter'}) ) # sortables product_variations.find('.sortable_values').sortable({handle: '.val_sorter'}) product_variations.find('.variations_sortable').sortable({handle: '.variation_sorter', update: ()-> $(this).children().each((index)-> $(this).find('.product_variation_position').val(index); ) }) # delete actions product_variations.on('click', '.val_del', -> $(this).closest('li').fadeOut('slow', -> $(this).remove() ) return false ) product_variations.on('click', '.var_del', -> unless confirm(product_variations.attr('data-confirm-msg')) return false $(this).closest('.product_variation').fadeOut('slow', -> $(this).remove() check_variation_status() ) return false ) set_variantion_physical_product_fields = (p_variation, hide_fields) -> fields_not_required = $(p_variation) .find('.fn-not-service-product-required') set_variantion_fields(fields_not_required, hide_fields) $(p_variation) .find('.fn-product-variation-field') .attr('value', product_type) set_variantion_service_product_fields = (p_variation, hide_fields) -> fields_not_required = $(p_variation) .find('.fn-not-physical-product-required') set_variantion_fields(fields_not_required, !hide_fields) set_variantion_fields = (fields_not_required, hide_fields) -> for p_field in fields_not_required if hide_fields $(p_field) .hide() .find('.required') .addClass('e_skip_required') .removeClass('required') else $(p_field) .show() .find('.e_skip_required') .removeClass('e_skip_required') .addClass('required') set_physical_product_fields = (hide_fields) -> set_fields(['ecommerce_weight', 'ecommerce_qty'], hide_fields) set_service_product_fields = (hide_fields) -> set_fields(['ecommerce_bucket', 'ecommerce_hours'], !hide_fields) set_fields = (not_physical_product_field_keys, hide_fields) -> for field_key in not_physical_product_field_keys p_field = form .find( '.c-field-group .item-custom-field[data-field-key="' + field_key + '"]' ) if hide_fields p_field .hide() .find('.required') .addClass('e_skip_required') .removeClass('required') else p_field .show() .find('.e_skip_required') .removeClass('e_skip_required') .addClass('required') check_product_type = -> if product_variations.find('.product_variation').length > 0 for p_variation in product_variations.find('.product_variation') set_variantion_physical_product_fields( p_variation, product_type == SERVICE_PRODUCT_TYPE ) set_variantion_service_product_fields( p_variation, product_type == SERVICE_PRODUCT_TYPE ) else set_physical_product_fields(product_type == SERVICE_PRODUCT_TYPE) set_service_product_fields(product_type == SERVICE_PRODUCT_TYPE) check_product_type() # check the variation status and disable or enable some custom fields check_variation_status = -> fields = ['ecommerce_sku', 'ecommerce_price','ecommerce_stock', 'ecommerce_photos', 'ecommerce_bucket', 'ecommerce_hours'] if product_variations.find('.product_variation').length > 0 fields.push('ecommerce_weight', 'ecommerce_qty') for key in fields p_field = form.find('.c-field-group .item-custom-field[data-field-key="'+key+'"]') p_field.hide() .find('.required') .addClass('e_skip_required') .removeClass('required') else if product_type != SERVICE_PRODUCT_TYPE fields.splice(4,2, 'ecommerce_weight', 'ecommerce_qty') for key in fields p_field = form.find('.c-field-group .item-custom-field[data-field-key="'+key+'"]') p_field.show() .find('.e_skip_required') .removeClass('e_skip_required') .addClass('required') check_variation_status()
true
$ -> form = $('#form-post') variation_id = 1 product_variations = form.find('#product_variations') form.find('.content-frame-body > .c-field-group:last').after(product_variations.removeClass('hidden')) SERVICE_PRODUCT_TYPE = "service_product" # this variables is defined in _variations.html.erb product_type = ORIGIN_PRODUCT_TYPE # photo uploader product_variations.on('click', '.product_variation_photo_link', -> $input = $(this).prev() $.fn.upload_filemanager({ formats: "image", dimension: $input.attr("data-dimension") || '', versions: $input.attr("data-versions") || '', thumb_size: $input.attr("data-thumb_size") || '', selected: (file, response) -> $input.val(file.url); }) return false ) cache_variation = product_variations.find('.blank_product_variation').remove().clone().removeClass('hidden') cache_values = cache_variation.find('.sortable_values > li:first').remove().clone() # change product_type form.on('change', '.c-field-group .item-custom-field[data-field-key="ecommerce_product_type"] select', -> product_type = $(this).val() check_product_type() ) # Add min value and step options to hours field form.find('.c-field-group .item-custom-field[data-field-key="ecommerce_hours"] input[type="number"]').attr({'min': 0, 'step': 0.5}) # add new variation product_variations.find('.add_new_variation').click -> clone = cache_variation.clone().attr('data-id', 'new_'+variation_id+=1) product_variations.children('.variations_sortable').append(clone) clone.trigger('fill_variation_id') if product_type == SERVICE_PRODUCT_TYPE fields_not_required = clone.find('.fn-not-service-product-required') clone.find('.fn-product-variation-field').attr('value', SERVICE_PRODUCT_TYPE) for p_field in fields_not_required $(p_field).hide().find('.required').addClass('e_skip_required').removeClass('required') else fields_not_required = clone.find('.fn-not-physical-product-required') for p_field in fields_not_required $(p_field).hide().find('.required').addClass('e_skip_required').removeClass('required') check_variation_status() return false # add new variation value product_variations.on('click', '.add_new_value', -> clone = cache_values.clone() key = $(this).closest('.product_variation').attr('data-id') clone.find('input, select').each(-> $(this).attr('name', $(this).attr('name').replace('[]', '['+key+']')).removeAttr('id') ) $(this).closest('.variation_attributes').find('.sortable_values').append(clone) clone.find('.product_attribute_select').trigger('change') return false ) # change attribute product_variations.on('change', '.product_attribute_select', -> v = $(this).val() sel = $(this).closest('.row').find('.product_attribute_vals_select').html('') for attr in PRODUCT_ATTRIBUTES if `attr.id == v` for value in attr.translated_values sel.append('<option value="'+value.id+'">'+value.label.replace(/</g, '&lt;')+'</option>') ) product_variations.on('fill_variation_id', '.product_variation', -> key = $(this).attr('data-PI:KEY:<KEY>END_PI') $(this).find('input, select').each(-> $(this).attr('name', $(this).attr('name').replace('[]', '['+key+']')).removeAttr('id') ) $(this).find('.sortable_values').sortable({handle: '.val_sorter'}) ) # sortables product_variations.find('.sortable_values').sortable({handle: '.val_sorter'}) product_variations.find('.variations_sortable').sortable({handle: '.variation_sorter', update: ()-> $(this).children().each((index)-> $(this).find('.product_variation_position').val(index); ) }) # delete actions product_variations.on('click', '.val_del', -> $(this).closest('li').fadeOut('slow', -> $(this).remove() ) return false ) product_variations.on('click', '.var_del', -> unless confirm(product_variations.attr('data-confirm-msg')) return false $(this).closest('.product_variation').fadeOut('slow', -> $(this).remove() check_variation_status() ) return false ) set_variantion_physical_product_fields = (p_variation, hide_fields) -> fields_not_required = $(p_variation) .find('.fn-not-service-product-required') set_variantion_fields(fields_not_required, hide_fields) $(p_variation) .find('.fn-product-variation-field') .attr('value', product_type) set_variantion_service_product_fields = (p_variation, hide_fields) -> fields_not_required = $(p_variation) .find('.fn-not-physical-product-required') set_variantion_fields(fields_not_required, !hide_fields) set_variantion_fields = (fields_not_required, hide_fields) -> for p_field in fields_not_required if hide_fields $(p_field) .hide() .find('.required') .addClass('e_skip_required') .removeClass('required') else $(p_field) .show() .find('.e_skip_required') .removeClass('e_skip_required') .addClass('required') set_physical_product_fields = (hide_fields) -> set_fields(['ecommerce_weight', 'ecommerce_qty'], hide_fields) set_service_product_fields = (hide_fields) -> set_fields(['ecommerce_bucket', 'ecommerce_hours'], !hide_fields) set_fields = (not_physical_product_field_keys, hide_fields) -> for field_key in not_physical_product_field_keys p_field = form .find( '.c-field-group .item-custom-field[data-field-key="' + field_key + '"]' ) if hide_fields p_field .hide() .find('.required') .addClass('e_skip_required') .removeClass('required') else p_field .show() .find('.e_skip_required') .removeClass('e_skip_required') .addClass('required') check_product_type = -> if product_variations.find('.product_variation').length > 0 for p_variation in product_variations.find('.product_variation') set_variantion_physical_product_fields( p_variation, product_type == SERVICE_PRODUCT_TYPE ) set_variantion_service_product_fields( p_variation, product_type == SERVICE_PRODUCT_TYPE ) else set_physical_product_fields(product_type == SERVICE_PRODUCT_TYPE) set_service_product_fields(product_type == SERVICE_PRODUCT_TYPE) check_product_type() # check the variation status and disable or enable some custom fields check_variation_status = -> fields = ['ecommerce_sku', 'ecommerce_price','ecommerce_stock', 'ecommerce_photos', 'ecommerce_bucket', 'ecommerce_hours'] if product_variations.find('.product_variation').length > 0 fields.push('ecommerce_weight', 'ecommerce_qty') for key in fields p_field = form.find('.c-field-group .item-custom-field[data-field-key="'+key+'"]') p_field.hide() .find('.required') .addClass('e_skip_required') .removeClass('required') else if product_type != SERVICE_PRODUCT_TYPE fields.splice(4,2, 'ecommerce_weight', 'ecommerce_qty') for key in fields p_field = form.find('.c-field-group .item-custom-field[data-field-key="'+key+'"]') p_field.show() .find('.e_skip_required') .removeClass('e_skip_required') .addClass('required') check_variation_status()
[ { "context": "g_out: \"Logga Ut\"\n play: \"Spela\"\n editor: \"Nivåredigerare\"\n blog: \"Blogg\"\n forum: \"Forum\"\n admin: ", "end": 370, "score": 0.605685830116272, "start": 357, "tag": "NAME", "value": "ivåredigerare" }, { "context": " home: \"Hem\"\n contribute: \"Bidra\"\n legal: \"Juridik\"\n about: \"Om oss\"\n contact: \"Kontakt\"\n t", "end": 500, "score": 0.8576218485832214, "start": 493, "tag": "NAME", "value": "Juridik" }, { "context": "color: \"Trollkarlens Klädfärg\"\n new_password: \"Nytt Lösenord\"\n new_password_verify: \"Verifiera\"\n email_s", "end": 3877, "score": 0.99942547082901, "start": 3864, "tag": "PASSWORD", "value": "Nytt Lösenord" }, { "context": "ssword: \"Nytt Lösenord\"\n new_password_verify: \"Verifiera\"\n email_subscriptions: \"E-post Prenumerationer", "end": 3914, "score": 0.999225378036499, "start": 3905, "tag": "PASSWORD", "value": "Verifiera" } ]
app/locale/sv.coffee
lwatiker/codecombat
1
module.exports = nativeDescription: "Svenska", englishDescription: "Swedish", translation: common: loading: "Laddar..." modal: close: "Stäng" okay: "Okej" not_found: page_not_found: "Sidan kan inte hittas" nav: # Header sign_up: "Skapa Konto" log_in: "Logga In" log_out: "Logga Ut" play: "Spela" editor: "Nivåredigerare" blog: "Blogg" forum: "Forum" admin: "Admin" # Footer home: "Hem" contribute: "Bidra" legal: "Juridik" about: "Om oss" contact: "Kontakt" twitter_follow: "Följ oss på Twitter" forms: name: "Namn" email: "E-post" message: "Meddelande" cancel: "Avbryt" login: log_in: "Logga In" sign_up: "skapa konto" or: ", eller " recover: "glömt lösenord" signup: description: "Det är gratis. Vi behöver bara lite information och sen är du redo att börja:" email_announcements: "Mottag nyheter via e-post" coppa: "13+ eller ej i USA" coppa_why: "(Varför?)" creating: "Skapar Konto..." sign_up: "Skapa Konto" or: "eller " log_in: "logga in med lösenord" home: slogan: "Lär dig att koda Javascript genom att spela ett spel." no_ie: "CodeCombat fungerar tyvärr inte i IE8 eller äldre." no_mobile: "CodeCombat är inte designat för mobila enhter och kanske inte fungerar!" play: "Spela" play: choose_your_level: "Välj din nivå" adventurer_prefix: "Du kan hoppa till vilken nivå som helst här under, eller diskutera nivåer på " adventurer_forum: "Äventyrarforumet" adventurer_suffix: "." campaign_beginner: "Nybörjarkampanj" # campaign_beginner_description: "" campaign_dev: "Slumpmässig Svårare Nivå" campaign_dev_description: "... där du lär dig att hantera gränssnittet medan du gör något lite svårare." campaign_multiplayer: "Flerspelararenor" # campaign_multiplayer_description: "" campaign_player_created: "Spelarskapade" # campaign_player_created_description: "" level_difficulty: "Svårighetsgrad: " contact: contact_us: "Kontakta CodeCombat" welcome: "Kul att höra från dig! Använd formuläret för att skicka e-post till oss." contribute_prefix: "Om du är intresserad av att bidra, koll in vår " contribute_page: "bidragarsida" contribute_suffix: "!" # forum_prefix: "" forum_page: "vårt forum" forum_suffix: " istället." sending: "Skickar..." send: "Skicka Feedback" diplomat_suggestion: title: "Hjälp till att översätta CodeCombat!" sub_heading: "Vi behöver dina språkliga kunskaper." pitch_body: "Vi utvecklar CodeCombat på engelska, men vi har redan spelare världen över. Många av dem vill spela på svenska, men talar inte engelska, så om du talar båda språken, fundera på att registrera dig som Diplomat och hjälp till med översättningen av både hemsidan och alla nivår till svenska." missing_translations: "Tills vi har översatt allting till svenska, så kommer du se engelska när det inte finns någon svensk översättning tillgänglig." learn_more: "Läs mer om att vara en Diplomat" subscribe_as_diplomat: "Registrera dig som Diplomat" account_settings: title: "Kontoinställningar" not_logged_in: "Logga in eller skapa ett konto för att ändra dina inställningar." autosave: "Ändringar Sparas Automatiskt" me_tab: "Jag" picture_tab: "Profilbild" wizard_tab: "Trollkarl" password_tab: "Lösenord" emails_tab: "E-postadresser" language_tab: "Språk" gravatar_select: "Välj ett Gravatar foto att använda" gravatar_add_photos: "Lägg till miniatyrbilder och fotografier i ett Gravatar konto kopplat till din mail för att välja profilbild." gravatar_add_more_photos: "Lägg till mer fotografier till i ditt Gravatar konto för att använda dem här." wizard_color: "Trollkarlens Klädfärg" new_password: "Nytt Lösenord" new_password_verify: "Verifiera" email_subscriptions: "E-post Prenumerationer" email_announcements: "Meddelanden" email_announcements_description: "Få e-post med de senaste nyheterna och utvecklingen på CodeCombat." # contributor_emails: "" contribute_prefix: "Vi söker mer folk som vill var med och hjälpa till! Kolla in " contribute_page: "bidragarsida" contribute_suffix: " tför att få veta mer." email_toggle: "Växla Alla" language: "Språk" saving: "Sparar..." error_saving: "Ett Fel Uppstod Vid Sparningen" saved: "Ändringar Sparade" password_mismatch: "De angivna lösenorden stämmer inte överens." account_profile: edit_settings: "Ändra Inställningar" profile_for_prefix: "Profil för " profile_for_suffix: "" profile: "Profil" user_not_found: "Användaren du söker verkar inte finnas. Kolla adressen?" gravatar_not_found_mine: "Vi kunde inte hitta en profil associerad med:" gravatar_signup_prefix: "Registrera dig på " gravatar_signup_suffix: " för att komma igång!" gravatar_not_found_other: "Tyvärr, det finns ingen profil associerad med den här personens e-postadress." gravatar_contact: "Kontakt" gravatar_websites: "Hemsidor" # gravatar_accounts: "" gravatar_profile_link: "Hela Gravatar profilen" play_level: level_load_error: "Nivån kunde inte laddas." done: "Klar" grid: "Rutnät" customize_wizard: "Finjustera Trollkarl" home: "Hem" guide: "Guide" multiplayer: "Flerspelareläge" restart: "Börja om" goals: "Mål" action_timeline: "Händelse-tidslinje" click_to_select: "Klicka på en enhet för att välja den." reload_title: "Ladda om all kod?" reload_really: "Är du säker på att du vill ladda om nivån från början?" reload_confirm: "Ladda om allt" victory_title_prefix: "" victory_title_suffix: " Genomförd" victory_sign_up: "Registrera dig för att få uppdateringar" victory_sign_up_poke: "Vill du ha de senaste nyheterna vi e-post? Skapa ett gratiskonto så håller vi dig informerad!" victory_rate_the_level: "Betygsätt nivån: " victory_play_next_level: "Spela Nästa Nivå" victory_go_home: "Gå Hem" victory_review: "Berätta mer!" victory_hour_of_code_done: "Är Du Klar?" victory_hour_of_code_done_yes: "Ja, jag är klar med min Hour of Code!" multiplayer_title: "Flerspelarinställningar" multiplayer_link_description: "Dela den här länken med alla som du vill spela med." multiplayer_hint_label: "Tips:" multiplayer_hint: " Klicka på länken för att välja allt, tryck sedan på Cmd-C eller Ctrl-C för att kopiera länken." multiplayer_coming_soon: "Mer flerspelarlägen kommer!" guide_title: "Guide" tome_minion_spells: "Dina Soldaters Förmågor" tome_read_only_spells: "Skrivskyddade Förmågor" tome_other_units: "Andra Enheter" # tome_cast_button_castable: "" # tome_cast_button_casting: "" # tome_cast_button_cast: "" # tome_autocast_delay: "" tome_autocast_1: "1 sekund" tome_autocast_3: "3 sekunder" tome_autocast_5: "5 sekunder" tome_autocast_manual: "Manuellt" tome_select_spell: "Välj en Förmåga" tome_select_a_thang: "Välj Någon för " tome_available_spells: "Tillgängliga Förmågor" # hud_continue: ""
197176
module.exports = nativeDescription: "Svenska", englishDescription: "Swedish", translation: common: loading: "Laddar..." modal: close: "Stäng" okay: "Okej" not_found: page_not_found: "Sidan kan inte hittas" nav: # Header sign_up: "Skapa Konto" log_in: "Logga In" log_out: "Logga Ut" play: "Spela" editor: "N<NAME>" blog: "Blogg" forum: "Forum" admin: "Admin" # Footer home: "Hem" contribute: "Bidra" legal: "<NAME>" about: "Om oss" contact: "Kontakt" twitter_follow: "Följ oss på Twitter" forms: name: "Namn" email: "E-post" message: "Meddelande" cancel: "Avbryt" login: log_in: "Logga In" sign_up: "skapa konto" or: ", eller " recover: "glömt lösenord" signup: description: "Det är gratis. Vi behöver bara lite information och sen är du redo att börja:" email_announcements: "Mottag nyheter via e-post" coppa: "13+ eller ej i USA" coppa_why: "(Varför?)" creating: "Skapar Konto..." sign_up: "Skapa Konto" or: "eller " log_in: "logga in med lösenord" home: slogan: "Lär dig att koda Javascript genom att spela ett spel." no_ie: "CodeCombat fungerar tyvärr inte i IE8 eller äldre." no_mobile: "CodeCombat är inte designat för mobila enhter och kanske inte fungerar!" play: "Spela" play: choose_your_level: "Välj din nivå" adventurer_prefix: "Du kan hoppa till vilken nivå som helst här under, eller diskutera nivåer på " adventurer_forum: "Äventyrarforumet" adventurer_suffix: "." campaign_beginner: "Nybörjarkampanj" # campaign_beginner_description: "" campaign_dev: "Slumpmässig Svårare Nivå" campaign_dev_description: "... där du lär dig att hantera gränssnittet medan du gör något lite svårare." campaign_multiplayer: "Flerspelararenor" # campaign_multiplayer_description: "" campaign_player_created: "Spelarskapade" # campaign_player_created_description: "" level_difficulty: "Svårighetsgrad: " contact: contact_us: "Kontakta CodeCombat" welcome: "Kul att höra från dig! Använd formuläret för att skicka e-post till oss." contribute_prefix: "Om du är intresserad av att bidra, koll in vår " contribute_page: "bidragarsida" contribute_suffix: "!" # forum_prefix: "" forum_page: "vårt forum" forum_suffix: " istället." sending: "Skickar..." send: "Skicka Feedback" diplomat_suggestion: title: "Hjälp till att översätta CodeCombat!" sub_heading: "Vi behöver dina språkliga kunskaper." pitch_body: "Vi utvecklar CodeCombat på engelska, men vi har redan spelare världen över. Många av dem vill spela på svenska, men talar inte engelska, så om du talar båda språken, fundera på att registrera dig som Diplomat och hjälp till med översättningen av både hemsidan och alla nivår till svenska." missing_translations: "Tills vi har översatt allting till svenska, så kommer du se engelska när det inte finns någon svensk översättning tillgänglig." learn_more: "Läs mer om att vara en Diplomat" subscribe_as_diplomat: "Registrera dig som Diplomat" account_settings: title: "Kontoinställningar" not_logged_in: "Logga in eller skapa ett konto för att ändra dina inställningar." autosave: "Ändringar Sparas Automatiskt" me_tab: "Jag" picture_tab: "Profilbild" wizard_tab: "Trollkarl" password_tab: "Lösenord" emails_tab: "E-postadresser" language_tab: "Språk" gravatar_select: "Välj ett Gravatar foto att använda" gravatar_add_photos: "Lägg till miniatyrbilder och fotografier i ett Gravatar konto kopplat till din mail för att välja profilbild." gravatar_add_more_photos: "Lägg till mer fotografier till i ditt Gravatar konto för att använda dem här." wizard_color: "Trollkarlens Klädfärg" new_password: "<PASSWORD>" new_password_verify: "<PASSWORD>" email_subscriptions: "E-post Prenumerationer" email_announcements: "Meddelanden" email_announcements_description: "Få e-post med de senaste nyheterna och utvecklingen på CodeCombat." # contributor_emails: "" contribute_prefix: "Vi söker mer folk som vill var med och hjälpa till! Kolla in " contribute_page: "bidragarsida" contribute_suffix: " tför att få veta mer." email_toggle: "Växla Alla" language: "Språk" saving: "Sparar..." error_saving: "Ett Fel Uppstod Vid Sparningen" saved: "Ändringar Sparade" password_mismatch: "De angivna lösenorden stämmer inte överens." account_profile: edit_settings: "Ändra Inställningar" profile_for_prefix: "Profil för " profile_for_suffix: "" profile: "Profil" user_not_found: "Användaren du söker verkar inte finnas. Kolla adressen?" gravatar_not_found_mine: "Vi kunde inte hitta en profil associerad med:" gravatar_signup_prefix: "Registrera dig på " gravatar_signup_suffix: " för att komma igång!" gravatar_not_found_other: "Tyvärr, det finns ingen profil associerad med den här personens e-postadress." gravatar_contact: "Kontakt" gravatar_websites: "Hemsidor" # gravatar_accounts: "" gravatar_profile_link: "Hela Gravatar profilen" play_level: level_load_error: "Nivån kunde inte laddas." done: "Klar" grid: "Rutnät" customize_wizard: "Finjustera Trollkarl" home: "Hem" guide: "Guide" multiplayer: "Flerspelareläge" restart: "Börja om" goals: "Mål" action_timeline: "Händelse-tidslinje" click_to_select: "Klicka på en enhet för att välja den." reload_title: "Ladda om all kod?" reload_really: "Är du säker på att du vill ladda om nivån från början?" reload_confirm: "Ladda om allt" victory_title_prefix: "" victory_title_suffix: " Genomförd" victory_sign_up: "Registrera dig för att få uppdateringar" victory_sign_up_poke: "Vill du ha de senaste nyheterna vi e-post? Skapa ett gratiskonto så håller vi dig informerad!" victory_rate_the_level: "Betygsätt nivån: " victory_play_next_level: "Spela Nästa Nivå" victory_go_home: "Gå Hem" victory_review: "Berätta mer!" victory_hour_of_code_done: "Är Du Klar?" victory_hour_of_code_done_yes: "Ja, jag är klar med min Hour of Code!" multiplayer_title: "Flerspelarinställningar" multiplayer_link_description: "Dela den här länken med alla som du vill spela med." multiplayer_hint_label: "Tips:" multiplayer_hint: " Klicka på länken för att välja allt, tryck sedan på Cmd-C eller Ctrl-C för att kopiera länken." multiplayer_coming_soon: "Mer flerspelarlägen kommer!" guide_title: "Guide" tome_minion_spells: "Dina Soldaters Förmågor" tome_read_only_spells: "Skrivskyddade Förmågor" tome_other_units: "Andra Enheter" # tome_cast_button_castable: "" # tome_cast_button_casting: "" # tome_cast_button_cast: "" # tome_autocast_delay: "" tome_autocast_1: "1 sekund" tome_autocast_3: "3 sekunder" tome_autocast_5: "5 sekunder" tome_autocast_manual: "Manuellt" tome_select_spell: "Välj en Förmåga" tome_select_a_thang: "Välj Någon för " tome_available_spells: "Tillgängliga Förmågor" # hud_continue: ""
true
module.exports = nativeDescription: "Svenska", englishDescription: "Swedish", translation: common: loading: "Laddar..." modal: close: "Stäng" okay: "Okej" not_found: page_not_found: "Sidan kan inte hittas" nav: # Header sign_up: "Skapa Konto" log_in: "Logga In" log_out: "Logga Ut" play: "Spela" editor: "NPI:NAME:<NAME>END_PI" blog: "Blogg" forum: "Forum" admin: "Admin" # Footer home: "Hem" contribute: "Bidra" legal: "PI:NAME:<NAME>END_PI" about: "Om oss" contact: "Kontakt" twitter_follow: "Följ oss på Twitter" forms: name: "Namn" email: "E-post" message: "Meddelande" cancel: "Avbryt" login: log_in: "Logga In" sign_up: "skapa konto" or: ", eller " recover: "glömt lösenord" signup: description: "Det är gratis. Vi behöver bara lite information och sen är du redo att börja:" email_announcements: "Mottag nyheter via e-post" coppa: "13+ eller ej i USA" coppa_why: "(Varför?)" creating: "Skapar Konto..." sign_up: "Skapa Konto" or: "eller " log_in: "logga in med lösenord" home: slogan: "Lär dig att koda Javascript genom att spela ett spel." no_ie: "CodeCombat fungerar tyvärr inte i IE8 eller äldre." no_mobile: "CodeCombat är inte designat för mobila enhter och kanske inte fungerar!" play: "Spela" play: choose_your_level: "Välj din nivå" adventurer_prefix: "Du kan hoppa till vilken nivå som helst här under, eller diskutera nivåer på " adventurer_forum: "Äventyrarforumet" adventurer_suffix: "." campaign_beginner: "Nybörjarkampanj" # campaign_beginner_description: "" campaign_dev: "Slumpmässig Svårare Nivå" campaign_dev_description: "... där du lär dig att hantera gränssnittet medan du gör något lite svårare." campaign_multiplayer: "Flerspelararenor" # campaign_multiplayer_description: "" campaign_player_created: "Spelarskapade" # campaign_player_created_description: "" level_difficulty: "Svårighetsgrad: " contact: contact_us: "Kontakta CodeCombat" welcome: "Kul att höra från dig! Använd formuläret för att skicka e-post till oss." contribute_prefix: "Om du är intresserad av att bidra, koll in vår " contribute_page: "bidragarsida" contribute_suffix: "!" # forum_prefix: "" forum_page: "vårt forum" forum_suffix: " istället." sending: "Skickar..." send: "Skicka Feedback" diplomat_suggestion: title: "Hjälp till att översätta CodeCombat!" sub_heading: "Vi behöver dina språkliga kunskaper." pitch_body: "Vi utvecklar CodeCombat på engelska, men vi har redan spelare världen över. Många av dem vill spela på svenska, men talar inte engelska, så om du talar båda språken, fundera på att registrera dig som Diplomat och hjälp till med översättningen av både hemsidan och alla nivår till svenska." missing_translations: "Tills vi har översatt allting till svenska, så kommer du se engelska när det inte finns någon svensk översättning tillgänglig." learn_more: "Läs mer om att vara en Diplomat" subscribe_as_diplomat: "Registrera dig som Diplomat" account_settings: title: "Kontoinställningar" not_logged_in: "Logga in eller skapa ett konto för att ändra dina inställningar." autosave: "Ändringar Sparas Automatiskt" me_tab: "Jag" picture_tab: "Profilbild" wizard_tab: "Trollkarl" password_tab: "Lösenord" emails_tab: "E-postadresser" language_tab: "Språk" gravatar_select: "Välj ett Gravatar foto att använda" gravatar_add_photos: "Lägg till miniatyrbilder och fotografier i ett Gravatar konto kopplat till din mail för att välja profilbild." gravatar_add_more_photos: "Lägg till mer fotografier till i ditt Gravatar konto för att använda dem här." wizard_color: "Trollkarlens Klädfärg" new_password: "PI:PASSWORD:<PASSWORD>END_PI" new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI" email_subscriptions: "E-post Prenumerationer" email_announcements: "Meddelanden" email_announcements_description: "Få e-post med de senaste nyheterna och utvecklingen på CodeCombat." # contributor_emails: "" contribute_prefix: "Vi söker mer folk som vill var med och hjälpa till! Kolla in " contribute_page: "bidragarsida" contribute_suffix: " tför att få veta mer." email_toggle: "Växla Alla" language: "Språk" saving: "Sparar..." error_saving: "Ett Fel Uppstod Vid Sparningen" saved: "Ändringar Sparade" password_mismatch: "De angivna lösenorden stämmer inte överens." account_profile: edit_settings: "Ändra Inställningar" profile_for_prefix: "Profil för " profile_for_suffix: "" profile: "Profil" user_not_found: "Användaren du söker verkar inte finnas. Kolla adressen?" gravatar_not_found_mine: "Vi kunde inte hitta en profil associerad med:" gravatar_signup_prefix: "Registrera dig på " gravatar_signup_suffix: " för att komma igång!" gravatar_not_found_other: "Tyvärr, det finns ingen profil associerad med den här personens e-postadress." gravatar_contact: "Kontakt" gravatar_websites: "Hemsidor" # gravatar_accounts: "" gravatar_profile_link: "Hela Gravatar profilen" play_level: level_load_error: "Nivån kunde inte laddas." done: "Klar" grid: "Rutnät" customize_wizard: "Finjustera Trollkarl" home: "Hem" guide: "Guide" multiplayer: "Flerspelareläge" restart: "Börja om" goals: "Mål" action_timeline: "Händelse-tidslinje" click_to_select: "Klicka på en enhet för att välja den." reload_title: "Ladda om all kod?" reload_really: "Är du säker på att du vill ladda om nivån från början?" reload_confirm: "Ladda om allt" victory_title_prefix: "" victory_title_suffix: " Genomförd" victory_sign_up: "Registrera dig för att få uppdateringar" victory_sign_up_poke: "Vill du ha de senaste nyheterna vi e-post? Skapa ett gratiskonto så håller vi dig informerad!" victory_rate_the_level: "Betygsätt nivån: " victory_play_next_level: "Spela Nästa Nivå" victory_go_home: "Gå Hem" victory_review: "Berätta mer!" victory_hour_of_code_done: "Är Du Klar?" victory_hour_of_code_done_yes: "Ja, jag är klar med min Hour of Code!" multiplayer_title: "Flerspelarinställningar" multiplayer_link_description: "Dela den här länken med alla som du vill spela med." multiplayer_hint_label: "Tips:" multiplayer_hint: " Klicka på länken för att välja allt, tryck sedan på Cmd-C eller Ctrl-C för att kopiera länken." multiplayer_coming_soon: "Mer flerspelarlägen kommer!" guide_title: "Guide" tome_minion_spells: "Dina Soldaters Förmågor" tome_read_only_spells: "Skrivskyddade Förmågor" tome_other_units: "Andra Enheter" # tome_cast_button_castable: "" # tome_cast_button_casting: "" # tome_cast_button_cast: "" # tome_autocast_delay: "" tome_autocast_1: "1 sekund" tome_autocast_3: "3 sekunder" tome_autocast_5: "5 sekunder" tome_autocast_manual: "Manuellt" tome_select_spell: "Välj en Förmåga" tome_select_a_thang: "Välj Någon för " tome_available_spells: "Tillgängliga Förmågor" # hud_continue: ""
[ { "context": " Classroom(\n {\n _id: \"classroom0\",\n name: \"Teacher Zero's Other Classroom\"\n ownerID: \"teacher0\",\n", "end": 117, "score": 0.6132546067237854, "start": 110, "tag": "NAME", "value": "Teacher" }, { "context": "e: \"Teacher Zero's Other Classroom\"\n ownerID: \"teacher0\",\n aceConfig:\n language: 'python'\n mem", "end": 164, "score": 0.9761816263198853, "start": 156, "tag": "USERNAME", "value": "teacher0" } ]
test/app/fixtures/classrooms/empty-classroom.coffee
cihatislamdede/codecombat
4,858
Classroom = require 'models/Classroom' module.exports = new Classroom( { _id: "classroom0", name: "Teacher Zero's Other Classroom" ownerID: "teacher0", aceConfig: language: 'python' members: [] } )
212911
Classroom = require 'models/Classroom' module.exports = new Classroom( { _id: "classroom0", name: "<NAME> Zero's Other Classroom" ownerID: "teacher0", aceConfig: language: 'python' members: [] } )
true
Classroom = require 'models/Classroom' module.exports = new Classroom( { _id: "classroom0", name: "PI:NAME:<NAME>END_PI Zero's Other Classroom" ownerID: "teacher0", aceConfig: language: 'python' members: [] } )
[ { "context": "over.bind 3702, () ->\n discover.addMembership '239.255.255.250'\n\nserver = http\n .createServer listener\n .liste", "end": 3281, "score": 0.9996462464332581, "start": 3266, "tag": "IP_ADDRESS", "value": "239.255.255.250" } ]
test/serverMockup.coffee
jasonItotal/onvif
1
http = require 'http' dgram = require 'dgram' xml2js = require 'xml2js' fs = require 'fs' Buffer = (require 'buffer').Buffer template = (require 'dot').template reBody = /<s:Body xmlns:xsi="http:\/\/www.w3.org\/2001\/XMLSchema-instance" xmlns:xsd="http:\/\/www.w3.org\/2001\/XMLSchema">(.*)<\/s:Body>/ reCommand = /<(\S*) / reNS = /xmlns="http:\/\/www.onvif.org\/\S*\/(\S*)\/wsdl"/ __xmldir = __dirname + '/serverMockup/' conf = { port: process.env.PORT || 10101 # server port hostname: process.env.HOSTNAME || 'localhost' pullPointUrl: '/onvif/subscription?Idx=6' } verbose = process.env.VERBOSE || false listener = (req, res) -> req.setEncoding('utf8') buf = [] req.on 'data', (chunk) -> buf.push chunk req.on 'end', () -> if (Buffer.isBuffer(buf)) # Node.js > 0.12 fix when `data` event produces strings instead of Buffer request = Buffer.concat buf else request = buf.join('') # Find body and command name body = reBody.exec(request) return res.end() if !body body = body[1] command = reCommand.exec(body)[1] return res.end() if !command # Look for ONVIF namespaces onvifNamespaces = reNS.exec(body) ns = '' if (onvifNamespaces) ns = onvifNamespaces[1] if verbose console.log 'received', ns, command switch when fs.existsSync(__xmldir + ns + '.' + command + '.xml') then command = ns + '.' + command when not fs.existsSync(__xmldir + command + '.xml') then command = 'Error' fileName = __xmldir + command + '.xml' if verbose console.log 'serving', fileName #fs.createReadStream(__dirname + '/serverMockup/' + command + '.xml').pipe(res) res.setHeader('Content-Type', 'application/soap+xml;charset=UTF-8') res.end(template(fs.readFileSync(fileName))(conf)) # Discovery service discoverReply = dgram.createSocket('udp4') discover = dgram.createSocket('udp4') discover.on 'error', (err) -> throw err discover.on 'message', (msg, rinfo) -> if verbose console.log 'Discovery received' #Extract MessageTo from the XML. xml2ns options remove the namespace tags and ensure element character content is accessed with '_' xml2js.parseString msg.toString(), { explicitCharkey:true, tagNameProcessors: [xml2js.processors.stripPrefix]}, (err, result) -> msgId = result.Envelope.Header[0].MessageID[0]._ discoverMsg = Buffer.from(fs .readFileSync __xmldir + 'Probe.xml' .toString() .replace 'RELATES_TO', msgId .replace 'SERVICE_URI', 'http://' + conf.hostname + ':' + conf.port + '/onvif/device_service' ) switch msgId # Wrong message test when 'urn:uuid:e7707' discoverReply.send (Buffer.from 'lollipop'), 0, 8, rinfo.port, rinfo.address # Double sending test when 'urn:uuid:d0-61e' discoverReply.send discoverMsg, 0, discoverMsg.length, rinfo.port, rinfo.address discoverReply.send discoverMsg, 0, discoverMsg.length, rinfo.port, rinfo.address # Discovery test else discoverReply.send discoverMsg, 0, discoverMsg.length, rinfo.port, rinfo.address if process.platform != 'win32' if verbose console.log 'Listening for Discovery Messages on Port 3702' discover.bind 3702, () -> discover.addMembership '239.255.255.250' server = http .createServer listener .listen conf.port close = () -> discover.close() discoverReply.close() server.close() if verbose console.log 'Closing ServerMockup' module.exports = { server: server , conf: conf , discover: discover , close: close }
35341
http = require 'http' dgram = require 'dgram' xml2js = require 'xml2js' fs = require 'fs' Buffer = (require 'buffer').Buffer template = (require 'dot').template reBody = /<s:Body xmlns:xsi="http:\/\/www.w3.org\/2001\/XMLSchema-instance" xmlns:xsd="http:\/\/www.w3.org\/2001\/XMLSchema">(.*)<\/s:Body>/ reCommand = /<(\S*) / reNS = /xmlns="http:\/\/www.onvif.org\/\S*\/(\S*)\/wsdl"/ __xmldir = __dirname + '/serverMockup/' conf = { port: process.env.PORT || 10101 # server port hostname: process.env.HOSTNAME || 'localhost' pullPointUrl: '/onvif/subscription?Idx=6' } verbose = process.env.VERBOSE || false listener = (req, res) -> req.setEncoding('utf8') buf = [] req.on 'data', (chunk) -> buf.push chunk req.on 'end', () -> if (Buffer.isBuffer(buf)) # Node.js > 0.12 fix when `data` event produces strings instead of Buffer request = Buffer.concat buf else request = buf.join('') # Find body and command name body = reBody.exec(request) return res.end() if !body body = body[1] command = reCommand.exec(body)[1] return res.end() if !command # Look for ONVIF namespaces onvifNamespaces = reNS.exec(body) ns = '' if (onvifNamespaces) ns = onvifNamespaces[1] if verbose console.log 'received', ns, command switch when fs.existsSync(__xmldir + ns + '.' + command + '.xml') then command = ns + '.' + command when not fs.existsSync(__xmldir + command + '.xml') then command = 'Error' fileName = __xmldir + command + '.xml' if verbose console.log 'serving', fileName #fs.createReadStream(__dirname + '/serverMockup/' + command + '.xml').pipe(res) res.setHeader('Content-Type', 'application/soap+xml;charset=UTF-8') res.end(template(fs.readFileSync(fileName))(conf)) # Discovery service discoverReply = dgram.createSocket('udp4') discover = dgram.createSocket('udp4') discover.on 'error', (err) -> throw err discover.on 'message', (msg, rinfo) -> if verbose console.log 'Discovery received' #Extract MessageTo from the XML. xml2ns options remove the namespace tags and ensure element character content is accessed with '_' xml2js.parseString msg.toString(), { explicitCharkey:true, tagNameProcessors: [xml2js.processors.stripPrefix]}, (err, result) -> msgId = result.Envelope.Header[0].MessageID[0]._ discoverMsg = Buffer.from(fs .readFileSync __xmldir + 'Probe.xml' .toString() .replace 'RELATES_TO', msgId .replace 'SERVICE_URI', 'http://' + conf.hostname + ':' + conf.port + '/onvif/device_service' ) switch msgId # Wrong message test when 'urn:uuid:e7707' discoverReply.send (Buffer.from 'lollipop'), 0, 8, rinfo.port, rinfo.address # Double sending test when 'urn:uuid:d0-61e' discoverReply.send discoverMsg, 0, discoverMsg.length, rinfo.port, rinfo.address discoverReply.send discoverMsg, 0, discoverMsg.length, rinfo.port, rinfo.address # Discovery test else discoverReply.send discoverMsg, 0, discoverMsg.length, rinfo.port, rinfo.address if process.platform != 'win32' if verbose console.log 'Listening for Discovery Messages on Port 3702' discover.bind 3702, () -> discover.addMembership '192.168.3.11' server = http .createServer listener .listen conf.port close = () -> discover.close() discoverReply.close() server.close() if verbose console.log 'Closing ServerMockup' module.exports = { server: server , conf: conf , discover: discover , close: close }
true
http = require 'http' dgram = require 'dgram' xml2js = require 'xml2js' fs = require 'fs' Buffer = (require 'buffer').Buffer template = (require 'dot').template reBody = /<s:Body xmlns:xsi="http:\/\/www.w3.org\/2001\/XMLSchema-instance" xmlns:xsd="http:\/\/www.w3.org\/2001\/XMLSchema">(.*)<\/s:Body>/ reCommand = /<(\S*) / reNS = /xmlns="http:\/\/www.onvif.org\/\S*\/(\S*)\/wsdl"/ __xmldir = __dirname + '/serverMockup/' conf = { port: process.env.PORT || 10101 # server port hostname: process.env.HOSTNAME || 'localhost' pullPointUrl: '/onvif/subscription?Idx=6' } verbose = process.env.VERBOSE || false listener = (req, res) -> req.setEncoding('utf8') buf = [] req.on 'data', (chunk) -> buf.push chunk req.on 'end', () -> if (Buffer.isBuffer(buf)) # Node.js > 0.12 fix when `data` event produces strings instead of Buffer request = Buffer.concat buf else request = buf.join('') # Find body and command name body = reBody.exec(request) return res.end() if !body body = body[1] command = reCommand.exec(body)[1] return res.end() if !command # Look for ONVIF namespaces onvifNamespaces = reNS.exec(body) ns = '' if (onvifNamespaces) ns = onvifNamespaces[1] if verbose console.log 'received', ns, command switch when fs.existsSync(__xmldir + ns + '.' + command + '.xml') then command = ns + '.' + command when not fs.existsSync(__xmldir + command + '.xml') then command = 'Error' fileName = __xmldir + command + '.xml' if verbose console.log 'serving', fileName #fs.createReadStream(__dirname + '/serverMockup/' + command + '.xml').pipe(res) res.setHeader('Content-Type', 'application/soap+xml;charset=UTF-8') res.end(template(fs.readFileSync(fileName))(conf)) # Discovery service discoverReply = dgram.createSocket('udp4') discover = dgram.createSocket('udp4') discover.on 'error', (err) -> throw err discover.on 'message', (msg, rinfo) -> if verbose console.log 'Discovery received' #Extract MessageTo from the XML. xml2ns options remove the namespace tags and ensure element character content is accessed with '_' xml2js.parseString msg.toString(), { explicitCharkey:true, tagNameProcessors: [xml2js.processors.stripPrefix]}, (err, result) -> msgId = result.Envelope.Header[0].MessageID[0]._ discoverMsg = Buffer.from(fs .readFileSync __xmldir + 'Probe.xml' .toString() .replace 'RELATES_TO', msgId .replace 'SERVICE_URI', 'http://' + conf.hostname + ':' + conf.port + '/onvif/device_service' ) switch msgId # Wrong message test when 'urn:uuid:e7707' discoverReply.send (Buffer.from 'lollipop'), 0, 8, rinfo.port, rinfo.address # Double sending test when 'urn:uuid:d0-61e' discoverReply.send discoverMsg, 0, discoverMsg.length, rinfo.port, rinfo.address discoverReply.send discoverMsg, 0, discoverMsg.length, rinfo.port, rinfo.address # Discovery test else discoverReply.send discoverMsg, 0, discoverMsg.length, rinfo.port, rinfo.address if process.platform != 'win32' if verbose console.log 'Listening for Discovery Messages on Port 3702' discover.bind 3702, () -> discover.addMembership 'PI:IP_ADDRESS:192.168.3.11END_PI' server = http .createServer listener .listen conf.port close = () -> discover.close() discoverReply.close() server.close() if verbose console.log 'Closing ServerMockup' module.exports = { server: server , conf: conf , discover: discover , close: close }
[ { "context": "ta =\n title: 'Test Email Job'\n to: 'tj@learnboost.com'\n job = jobs.create('email-to-be-saved', job", "end": 695, "score": 0.9999203681945801, "start": 678, "tag": "EMAIL", "value": "tj@learnboost.com" }, { "context": "=\n title: 'Test workerId Job'\n to: 'tj@learnboost.com'\n job = jobs.create('worker-id-test', job_da", "end": 1025, "score": 0.9999223351478577, "start": 1008, "tag": "EMAIL", "value": "tj@learnboost.com" }, { "context": "ta =\n title: 'Test Email Job'\n to: 'tj@learnboost.com'\n jobs.create('email-to-be-completed', job_d", "end": 1475, "score": 0.9999226331710815, "start": 1458, "tag": "EMAIL", "value": "tj@learnboost.com" }, { "context": "title: 'Test Email Job With Results'\n to: 'tj@learnboost.com'\n jobs.create('email-with-results', job_data", "end": 1838, "score": 0.9999203085899353, "start": 1821, "tag": "EMAIL", "value": "tj@learnboost.com" }, { "context": "ta =\n title: 'Test Email Job'\n to: 'tj@learnboost.com'\n jobs.create('email-to-be-progressed', job_", "end": 2235, "score": 0.9999212622642517, "start": 2218, "tag": "EMAIL", "value": "tj@learnboost.com" }, { "context": "ta =\n title: 'Test Email Job'\n to: 'tj@learnboost.com'\n jobs.create('email-to-be-progressed', job_", "end": 2680, "score": 0.999921441078186, "start": 2663, "tag": "EMAIL", "value": "tj@learnboost.com" }, { "context": "ta =\n title: 'Test Email Job'\n to: 'tj@learnboost.com'\n jobs.create('email-to-be-failed', job_data", "end": 3170, "score": 0.9999220967292786, "start": 3153, "tag": "EMAIL", "value": "tj@learnboost.com" }, { "context": "ta =\n title: 'Test Email Job'\n to: 'tj@learnboost.com'\n testJob = jobs.create('email-to-be-complet", "end": 3901, "score": 0.9999170899391174, "start": 3884, "tag": "EMAIL", "value": "tj@learnboost.com" }, { "context": "ta =\n title: 'Test Email Job'\n to: 'tj@learnboost.com'\n jobs.on 'job failed attempt', (id, errMsg,", "end": 4246, "score": 0.9999173879623413, "start": 4229, "tag": "EMAIL", "value": "tj@learnboost.com" }, { "context": "ta =\n title: 'Test Email Job'\n to: 'tj@learnboost.com'\n jobs.process('email-to-be-promoted', (job,", "end": 6825, "score": 0.9975372552871704, "start": 6808, "tag": "EMAIL", "value": "tj@learnboost.com" } ]
test/test.coffee
Kinvey/kue
0
_ = require 'lodash' async = require 'async' should = require 'should' kue = require '../' util = require 'util' describe 'Kue Tests', -> jobs = null Job = null beforeEach -> jobs = kue.createQueue({promotion:{interval:50}}) Job = kue.Job afterEach (done) -> jobs.shutdown 50, done # before (done) -> # jobs = kue.createQueue({promotion:{interval:100}}) # jobs.client.flushdb done # after (done) -> # jobs = kue.createQueue({promotion:{interval:100}}) # jobs.client.flushdb done describe 'Job Producer', -> it 'should save jobs having a new id', (done) -> job_data = title: 'Test Email Job' to: 'tj@learnboost.com' job = jobs.create('email-to-be-saved', job_data) jobs.process('email-to-be-saved', _.noop) job.save (err) -> job.id.should.be.an.instanceOf(Number) done err it 'should set worker id on job hash', (done) -> job_data = title: 'Test workerId Job' to: 'tj@learnboost.com' job = jobs.create('worker-id-test', job_data) jobs.process 'worker-id-test', (job, jdone)-> jdone() Job.get job.id, (err, j) -> j.toJSON().workerId.should.be.not.null; done() job.save() it 'should receive job complete event', (done) -> jobs.process 'email-to-be-completed', (job, done)-> done() job_data = title: 'Test Email Job' to: 'tj@learnboost.com' jobs.create('email-to-be-completed', job_data) .on 'complete', -> done() .save() it 'should receive job result in complete event', (done) -> jobs.process 'email-with-results', (job, done)-> done( null, {finalResult:123} ) job_data = title: 'Test Email Job With Results' to: 'tj@learnboost.com' jobs.create('email-with-results', job_data) .on 'complete', (result)-> result.finalResult.should.be.equal 123 done() .save() it 'should receive job progress event', (done) -> jobs.process 'email-to-be-progressed', (job, done)-> job.progress 1, 2 done() job_data = title: 'Test Email Job' to: 'tj@learnboost.com' jobs.create('email-to-be-progressed', job_data) .on 'progress', (progress)-> progress.should.be.equal 50 done() .save() it 'should receive job progress event with extra data', (done) -> jobs.process 'email-to-be-progressed', (job, done)-> job.progress 1, 2, notifyTime : "2014-11-22" done() job_data = title: 'Test Email Job' to: 'tj@learnboost.com' jobs.create('email-to-be-progressed', job_data) .on 'progress', (progress, extraData)-> progress.should.be.equal 50 extraData.notifyTime.should.be.equal "2014-11-22" done() .save() it 'should receive job failed attempt events', (done) -> total = 2 errorMsg = 'myError' jobs.process 'email-to-be-failed', (job, jdone)-> jdone errorMsg job_data = title: 'Test Email Job' to: 'tj@learnboost.com' jobs.create('email-to-be-failed', job_data).attempts(2) .on 'failed attempt', (errMsg,doneAttempts) -> errMsg.should.be.equal errorMsg doneAttempts.should.be.equal 1 total-- .on 'failed', (errMsg)-> errMsg.should.be.equal errorMsg (--total).should.be.equal 0 done() .save() it 'should receive queue level complete event', (done) -> jobs.process 'email-to-be-completed', (job, jdone)-> jdone( null, { prop: 'val' } ) jobs.on 'job complete', (id, result) -> id.should.be.equal testJob.id result.prop.should.be.equal 'val' done() job_data = title: 'Test Email Job' to: 'tj@learnboost.com' testJob = jobs.create('email-to-be-completed', job_data).save() it 'should receive queue level failed attempt events', (done) -> total = 2 errorMsg = 'myError' jobs.process 'email-to-be-failed', (job, jdone)-> jdone errorMsg job_data = title: 'Test Email Job' to: 'tj@learnboost.com' jobs.on 'job failed attempt', (id, errMsg, doneAttempts) -> id.should.be.equal newJob.id errMsg.should.be.equal errorMsg doneAttempts.should.be.equal 1 total-- .on 'job failed', (id, errMsg)-> id.should.be.equal newJob.id errMsg.should.be.equal errorMsg (--total).should.be.equal 0 done() newJob = jobs.create('email-to-be-failed', job_data).attempts(2).save() describe 'Job', -> it 'should be processed after delay', (done) -> now = Date.now() jobs.create( 'simple-delay-job', { title: 'simple delay job' } ).delay(300).save() jobs.process 'simple-delay-job', (job, jdone) -> processed = Date.now() (processed - now).should.be.approximately( 300, 2000 ) jdone() done() it 'should have promote_at timestamp', (done) -> now = Date.now() job = jobs.create( 'simple-delayed-job', { title: 'simple delay job' } ).delay(300).save() jobs.process 'simple-delayed-job', (job, jdone) -> job.promote_at.should.be.approximately(now + 300, 100) jdone() done() it 'should update promote_at after delay change', (done) -> now = Date.now() job = jobs.create( 'simple-delayed-job-1', { title: 'simple delay job' } ).delay(300).save() job.delay(100).save() jobs.process 'simple-delayed-job-1', (job, jdone) -> job.promote_at.should.be.approximately(now + 100, 100) jdone() done() it 'should update promote_at after failure with backoff', (done) -> now = Date.now() job = jobs.create( 'simple-delayed-job-2', { title: 'simple delay job' } ).delay(100).attempts(2).backoff({delay: 100, type: 'fixed'}).save() calls = 0 jobs.process 'simple-delayed-job-2', (job, jdone) -> processed = Date.now() if calls == 1 (processed - now).should.be.approximately(300, 100) jdone() done() else (processed - now).should.be.approximately(100, 100) jdone('error') calls++ it 'should be processed at a future date', (done) -> now = Date.now() jobs.create( 'future-job', { title: 'future job' } ).delay(new Date(now + 200)).save() jobs.process 'future-job', (job, jdone) -> processed = Date.now() (processed - now).should.be.approximately( 200, 100 ) jdone() done() it 'should receive promotion event', (done) -> job_data = title: 'Test Email Job' to: 'tj@learnboost.com' jobs.process('email-to-be-promoted', (job,done)-> ) jobs.create('email-to-be-promoted', job_data).delay(200) .on 'promotion', ()-> done() .save() it 'should be re tried after failed attempts', (done) -> [total, remaining] = [2,2] jobs.create( 'simple-multi-attempts-job', { title: 'simple-multi-attempts-job' } ).attempts(total).save() jobs.process 'simple-multi-attempts-job', (job, jdone) -> job.toJSON().attempts.remaining.should.be.equal remaining (job.toJSON().attempts.made + job.toJSON().attempts.remaining).should.be.equal total if( !--remaining ) jdone() done() else jdone( new Error('reaattempt') ) it 'should honor original delay at fixed backoff', (done) -> [total, remaining] = [2,2] start = Date.now() jobs.create( 'backoff-fixed-job', { title: 'backoff-fixed-job' } ).delay( 200 ).attempts(total).backoff( true ).save() jobs.process 'backoff-fixed-job', (job, jdone) -> if( !--remaining ) now = Date.now() (now - start).should.be.approximately(400,120) jdone() done() else jdone( new Error('reaattempt') ) it 'should honor original delay at exponential backoff', (done) -> [total, remaining] = [3,3] start = Date.now() jobs.create( 'backoff-exponential-job', { title: 'backoff-exponential-job' } ) .delay( 50 ).attempts(total).backoff( {type:'exponential', delay: 100} ).save() jobs.process 'backoff-exponential-job', (job, jdone) -> job._backoff.type.should.be.equal "exponential" job._backoff.delay.should.be.equal 100 now = Date.now() if( !--remaining ) (now - start).should.be.approximately(350,100) jdone() done() else jdone( new Error('reaattempt') ) it 'should honor max delay at exponential backoff', (done) -> [total, remaining] = [10,10] last = Date.now() jobs.create( 'backoff-exponential-job', { title: 'backoff-exponential-job' } ) .attempts(total).backoff( {type:'exponential', delay: 50, maxDelay: 100} ).save() jobs.process 'backoff-exponential-job', (job, jdone) -> job._backoff.type.should.be.equal "exponential" job._backoff.delay.should.be.equal 50 job._backoff.maxDelay.should.be.equal 100 now = Date.now() (now - last).should.be.lessThan 120 if( !--remaining ) jdone() done() else last = now jdone( new Error('reaattempt') ) it 'should honor users backoff function', (done) -> [total, remaining] = [2,2] start = Date.now() jobs.create( 'backoff-user-job', { title: 'backoff-user-job' } ) .delay( 50 ).attempts(total).backoff( ( attempts, delay ) -> 250 ).save() jobs.process 'backoff-user-job', (job, jdone) -> now = Date.now() if( !--remaining ) (now - start).should.be.approximately(350, 100) jdone() done() else jdone( new Error('reaattempt') ) it 'should log with a sprintf-style string', (done) -> jobs.create( 'log-job', { title: 'simple job' } ).save() jobs.process 'log-job', (job, jdone) -> job.log('this is %s number %d','test',1) Job.log job.id, (err,logs) -> logs[0].should.be.equal('this is test number 1'); done() jdone() it 'should log objects, errors, arrays, numbers, etc', (done) -> jobs.create( 'log-job', { title: 'simple job' } ).save() jobs.process 'log-job', (job, jdone) -> testErr = new Error('test error')# to compare the same stack job.log() job.log(undefined) job.log(null) job.log({test: 'some text'}) job.log(testErr) job.log([1,2,3]) job.log(123) job.log(1.23) job.log(0) job.log(NaN) job.log(true) job.log(false) Job.log job.id, (err,logs) -> logs[0].should.be.equal(util.format(undefined)); logs[1].should.be.equal(util.format(undefined)); logs[2].should.be.equal(util.format(null)); logs[3].should.be.equal(util.format({ test: 'some text' })); logs[4].should.be.equal(util.format(testErr)); logs[5].should.be.equal(util.format([ 1, 2, 3 ])); logs[6].should.be.equal(util.format(123)); logs[7].should.be.equal(util.format(1.23)); logs[8].should.be.equal(util.format(0)); logs[9].should.be.equal(util.format(NaN)); logs[10].should.be.equal(util.format(true)); logs[11].should.be.equal(util.format(false)); done() jdone() describe 'Kue Core', -> it 'should receive a "job enqueue" event', (done) -> jobs.on 'job enqueue', (id, type) -> if type == 'email-to-be-enqueued' id.should.be.equal job.id done() jobs.process 'email-to-be-enqueued', (job, jdone) -> jdone() job = jobs.create('email-to-be-enqueued').save() it 'should receive a "job remove" event', (done) -> jobs.on 'job remove', (id, type) -> if type == 'removable-job' id.should.be.equal job.id done() jobs.process 'removable-job', (job, jdone) -> jdone() job = jobs.create('removable-job').save().remove() it 'should fail a job with TTL is exceeded', (done) -> jobs.process('test-job-with-ttl', (job, jdone) -> # do nothing to sample a stuck worker ) jobs.create('test-job-with-ttl', title: 'a ttl job').ttl(500) .on 'failed', (err) -> err.should.be.equal 'TTL exceeded' done() .save() describe 'Kue Job Concurrency', -> it 'should process 2 concurrent jobs at the same time', (done) -> now = Date.now() jobStartTimes = [] jobs.process('test-job-parallel', 2, (job,jdone) -> jobStartTimes.push Date.now() if( jobStartTimes.length == 2 ) (jobStartTimes[0] - now).should.be.approximately( 0, 100 ) (jobStartTimes[1] - now).should.be.approximately( 0, 100 ) done() setTimeout(jdone, 500) ) jobs.create('test-job-parallel', title: 'concurrent job 1').save() jobs.create('test-job-parallel', title: 'concurrent job 2').save() it 'should process non concurrent jobs serially', (done) -> now = Date.now() jobStartTimes = [] jobs.process('test-job-serial', 1, (job,jdone) -> jobStartTimes.push Date.now() if( jobStartTimes.length == 2 ) (jobStartTimes[0] - now).should.be.approximately( 0, 100 ) (jobStartTimes[1] - now).should.be.approximately( 500, 100 ) done() setTimeout(jdone, 500) ) jobs.create('test-job-serial', title: 'non concurrent job 1').save() jobs.create('test-job-serial', title: 'non concurrent job 2').save() it 'should process a new job after a previous one fails with TTL is exceeded', (done) -> failures = 0 now = Date.now() jobStartTimes = [] jobs.process('test-job-serial-failed', 1, (job,jdone) -> jobStartTimes.push Date.now() if( jobStartTimes.length == 2 ) (jobStartTimes[0] - now).should.be.approximately( 0, 100 ) (jobStartTimes[1] - now).should.be.approximately( 500, 100 ) failures.should.be.equal 1 done() # do not call jdone to simulate a stuck worker ) jobs.create('test-job-serial-failed', title: 'a ttl job 1').ttl(500).on( 'failed', ()-> ++failures ).save() jobs.create('test-job-serial-failed', title: 'a ttl job 2').ttl(500).on( 'failed', ()-> ++failures ).save() it 'should not stuck in inactive mode if one of the workers failed because of ttl', (done) -> jobs.create('jobsA', title: 'titleA' metadata: {}).delay(1000).attempts(3).backoff( delay: 1 * 1000 type: 'exponential').removeOnComplete(true).ttl(1 * 1000).save() jobs.create('jobsB', title: 'titleB' metadata: {}).delay(1500).attempts(3).backoff( delay: 1 * 1000 type: 'exponential').removeOnComplete(true).ttl(1 * 1000).save() jobs.process 'jobsA', 1, (job, jdone) -> if job._attempts == '2' done() return jobs.process 'jobsB', 1, (job, jdone) -> done() return describe 'Kue Job Removal', -> beforeEach (done) -> jobs.process 'sample-job-to-be-cleaned', (job, jdone) -> jdone() async.each([1..10], (id, next) -> jobs.create( 'sample-job-to-be-cleaned', {id: id} ).save(next) , done) it 'should be able to remove completed jobs', (done) -> jobs.complete (err, ids) -> should.not.exist err async.each(ids, (id, next) -> Job.remove(id, next) , done) it 'should be able to remove failed jobs', (done) -> jobs.failed (err, ids) -> should.not.exist err async.each(ids, (id, next) -> Job.remove(id, next) , done)
103121
_ = require 'lodash' async = require 'async' should = require 'should' kue = require '../' util = require 'util' describe 'Kue Tests', -> jobs = null Job = null beforeEach -> jobs = kue.createQueue({promotion:{interval:50}}) Job = kue.Job afterEach (done) -> jobs.shutdown 50, done # before (done) -> # jobs = kue.createQueue({promotion:{interval:100}}) # jobs.client.flushdb done # after (done) -> # jobs = kue.createQueue({promotion:{interval:100}}) # jobs.client.flushdb done describe 'Job Producer', -> it 'should save jobs having a new id', (done) -> job_data = title: 'Test Email Job' to: '<EMAIL>' job = jobs.create('email-to-be-saved', job_data) jobs.process('email-to-be-saved', _.noop) job.save (err) -> job.id.should.be.an.instanceOf(Number) done err it 'should set worker id on job hash', (done) -> job_data = title: 'Test workerId Job' to: '<EMAIL>' job = jobs.create('worker-id-test', job_data) jobs.process 'worker-id-test', (job, jdone)-> jdone() Job.get job.id, (err, j) -> j.toJSON().workerId.should.be.not.null; done() job.save() it 'should receive job complete event', (done) -> jobs.process 'email-to-be-completed', (job, done)-> done() job_data = title: 'Test Email Job' to: '<EMAIL>' jobs.create('email-to-be-completed', job_data) .on 'complete', -> done() .save() it 'should receive job result in complete event', (done) -> jobs.process 'email-with-results', (job, done)-> done( null, {finalResult:123} ) job_data = title: 'Test Email Job With Results' to: '<EMAIL>' jobs.create('email-with-results', job_data) .on 'complete', (result)-> result.finalResult.should.be.equal 123 done() .save() it 'should receive job progress event', (done) -> jobs.process 'email-to-be-progressed', (job, done)-> job.progress 1, 2 done() job_data = title: 'Test Email Job' to: '<EMAIL>' jobs.create('email-to-be-progressed', job_data) .on 'progress', (progress)-> progress.should.be.equal 50 done() .save() it 'should receive job progress event with extra data', (done) -> jobs.process 'email-to-be-progressed', (job, done)-> job.progress 1, 2, notifyTime : "2014-11-22" done() job_data = title: 'Test Email Job' to: '<EMAIL>' jobs.create('email-to-be-progressed', job_data) .on 'progress', (progress, extraData)-> progress.should.be.equal 50 extraData.notifyTime.should.be.equal "2014-11-22" done() .save() it 'should receive job failed attempt events', (done) -> total = 2 errorMsg = 'myError' jobs.process 'email-to-be-failed', (job, jdone)-> jdone errorMsg job_data = title: 'Test Email Job' to: '<EMAIL>' jobs.create('email-to-be-failed', job_data).attempts(2) .on 'failed attempt', (errMsg,doneAttempts) -> errMsg.should.be.equal errorMsg doneAttempts.should.be.equal 1 total-- .on 'failed', (errMsg)-> errMsg.should.be.equal errorMsg (--total).should.be.equal 0 done() .save() it 'should receive queue level complete event', (done) -> jobs.process 'email-to-be-completed', (job, jdone)-> jdone( null, { prop: 'val' } ) jobs.on 'job complete', (id, result) -> id.should.be.equal testJob.id result.prop.should.be.equal 'val' done() job_data = title: 'Test Email Job' to: '<EMAIL>' testJob = jobs.create('email-to-be-completed', job_data).save() it 'should receive queue level failed attempt events', (done) -> total = 2 errorMsg = 'myError' jobs.process 'email-to-be-failed', (job, jdone)-> jdone errorMsg job_data = title: 'Test Email Job' to: '<EMAIL>' jobs.on 'job failed attempt', (id, errMsg, doneAttempts) -> id.should.be.equal newJob.id errMsg.should.be.equal errorMsg doneAttempts.should.be.equal 1 total-- .on 'job failed', (id, errMsg)-> id.should.be.equal newJob.id errMsg.should.be.equal errorMsg (--total).should.be.equal 0 done() newJob = jobs.create('email-to-be-failed', job_data).attempts(2).save() describe 'Job', -> it 'should be processed after delay', (done) -> now = Date.now() jobs.create( 'simple-delay-job', { title: 'simple delay job' } ).delay(300).save() jobs.process 'simple-delay-job', (job, jdone) -> processed = Date.now() (processed - now).should.be.approximately( 300, 2000 ) jdone() done() it 'should have promote_at timestamp', (done) -> now = Date.now() job = jobs.create( 'simple-delayed-job', { title: 'simple delay job' } ).delay(300).save() jobs.process 'simple-delayed-job', (job, jdone) -> job.promote_at.should.be.approximately(now + 300, 100) jdone() done() it 'should update promote_at after delay change', (done) -> now = Date.now() job = jobs.create( 'simple-delayed-job-1', { title: 'simple delay job' } ).delay(300).save() job.delay(100).save() jobs.process 'simple-delayed-job-1', (job, jdone) -> job.promote_at.should.be.approximately(now + 100, 100) jdone() done() it 'should update promote_at after failure with backoff', (done) -> now = Date.now() job = jobs.create( 'simple-delayed-job-2', { title: 'simple delay job' } ).delay(100).attempts(2).backoff({delay: 100, type: 'fixed'}).save() calls = 0 jobs.process 'simple-delayed-job-2', (job, jdone) -> processed = Date.now() if calls == 1 (processed - now).should.be.approximately(300, 100) jdone() done() else (processed - now).should.be.approximately(100, 100) jdone('error') calls++ it 'should be processed at a future date', (done) -> now = Date.now() jobs.create( 'future-job', { title: 'future job' } ).delay(new Date(now + 200)).save() jobs.process 'future-job', (job, jdone) -> processed = Date.now() (processed - now).should.be.approximately( 200, 100 ) jdone() done() it 'should receive promotion event', (done) -> job_data = title: 'Test Email Job' to: '<EMAIL>' jobs.process('email-to-be-promoted', (job,done)-> ) jobs.create('email-to-be-promoted', job_data).delay(200) .on 'promotion', ()-> done() .save() it 'should be re tried after failed attempts', (done) -> [total, remaining] = [2,2] jobs.create( 'simple-multi-attempts-job', { title: 'simple-multi-attempts-job' } ).attempts(total).save() jobs.process 'simple-multi-attempts-job', (job, jdone) -> job.toJSON().attempts.remaining.should.be.equal remaining (job.toJSON().attempts.made + job.toJSON().attempts.remaining).should.be.equal total if( !--remaining ) jdone() done() else jdone( new Error('reaattempt') ) it 'should honor original delay at fixed backoff', (done) -> [total, remaining] = [2,2] start = Date.now() jobs.create( 'backoff-fixed-job', { title: 'backoff-fixed-job' } ).delay( 200 ).attempts(total).backoff( true ).save() jobs.process 'backoff-fixed-job', (job, jdone) -> if( !--remaining ) now = Date.now() (now - start).should.be.approximately(400,120) jdone() done() else jdone( new Error('reaattempt') ) it 'should honor original delay at exponential backoff', (done) -> [total, remaining] = [3,3] start = Date.now() jobs.create( 'backoff-exponential-job', { title: 'backoff-exponential-job' } ) .delay( 50 ).attempts(total).backoff( {type:'exponential', delay: 100} ).save() jobs.process 'backoff-exponential-job', (job, jdone) -> job._backoff.type.should.be.equal "exponential" job._backoff.delay.should.be.equal 100 now = Date.now() if( !--remaining ) (now - start).should.be.approximately(350,100) jdone() done() else jdone( new Error('reaattempt') ) it 'should honor max delay at exponential backoff', (done) -> [total, remaining] = [10,10] last = Date.now() jobs.create( 'backoff-exponential-job', { title: 'backoff-exponential-job' } ) .attempts(total).backoff( {type:'exponential', delay: 50, maxDelay: 100} ).save() jobs.process 'backoff-exponential-job', (job, jdone) -> job._backoff.type.should.be.equal "exponential" job._backoff.delay.should.be.equal 50 job._backoff.maxDelay.should.be.equal 100 now = Date.now() (now - last).should.be.lessThan 120 if( !--remaining ) jdone() done() else last = now jdone( new Error('reaattempt') ) it 'should honor users backoff function', (done) -> [total, remaining] = [2,2] start = Date.now() jobs.create( 'backoff-user-job', { title: 'backoff-user-job' } ) .delay( 50 ).attempts(total).backoff( ( attempts, delay ) -> 250 ).save() jobs.process 'backoff-user-job', (job, jdone) -> now = Date.now() if( !--remaining ) (now - start).should.be.approximately(350, 100) jdone() done() else jdone( new Error('reaattempt') ) it 'should log with a sprintf-style string', (done) -> jobs.create( 'log-job', { title: 'simple job' } ).save() jobs.process 'log-job', (job, jdone) -> job.log('this is %s number %d','test',1) Job.log job.id, (err,logs) -> logs[0].should.be.equal('this is test number 1'); done() jdone() it 'should log objects, errors, arrays, numbers, etc', (done) -> jobs.create( 'log-job', { title: 'simple job' } ).save() jobs.process 'log-job', (job, jdone) -> testErr = new Error('test error')# to compare the same stack job.log() job.log(undefined) job.log(null) job.log({test: 'some text'}) job.log(testErr) job.log([1,2,3]) job.log(123) job.log(1.23) job.log(0) job.log(NaN) job.log(true) job.log(false) Job.log job.id, (err,logs) -> logs[0].should.be.equal(util.format(undefined)); logs[1].should.be.equal(util.format(undefined)); logs[2].should.be.equal(util.format(null)); logs[3].should.be.equal(util.format({ test: 'some text' })); logs[4].should.be.equal(util.format(testErr)); logs[5].should.be.equal(util.format([ 1, 2, 3 ])); logs[6].should.be.equal(util.format(123)); logs[7].should.be.equal(util.format(1.23)); logs[8].should.be.equal(util.format(0)); logs[9].should.be.equal(util.format(NaN)); logs[10].should.be.equal(util.format(true)); logs[11].should.be.equal(util.format(false)); done() jdone() describe 'Kue Core', -> it 'should receive a "job enqueue" event', (done) -> jobs.on 'job enqueue', (id, type) -> if type == 'email-to-be-enqueued' id.should.be.equal job.id done() jobs.process 'email-to-be-enqueued', (job, jdone) -> jdone() job = jobs.create('email-to-be-enqueued').save() it 'should receive a "job remove" event', (done) -> jobs.on 'job remove', (id, type) -> if type == 'removable-job' id.should.be.equal job.id done() jobs.process 'removable-job', (job, jdone) -> jdone() job = jobs.create('removable-job').save().remove() it 'should fail a job with TTL is exceeded', (done) -> jobs.process('test-job-with-ttl', (job, jdone) -> # do nothing to sample a stuck worker ) jobs.create('test-job-with-ttl', title: 'a ttl job').ttl(500) .on 'failed', (err) -> err.should.be.equal 'TTL exceeded' done() .save() describe 'Kue Job Concurrency', -> it 'should process 2 concurrent jobs at the same time', (done) -> now = Date.now() jobStartTimes = [] jobs.process('test-job-parallel', 2, (job,jdone) -> jobStartTimes.push Date.now() if( jobStartTimes.length == 2 ) (jobStartTimes[0] - now).should.be.approximately( 0, 100 ) (jobStartTimes[1] - now).should.be.approximately( 0, 100 ) done() setTimeout(jdone, 500) ) jobs.create('test-job-parallel', title: 'concurrent job 1').save() jobs.create('test-job-parallel', title: 'concurrent job 2').save() it 'should process non concurrent jobs serially', (done) -> now = Date.now() jobStartTimes = [] jobs.process('test-job-serial', 1, (job,jdone) -> jobStartTimes.push Date.now() if( jobStartTimes.length == 2 ) (jobStartTimes[0] - now).should.be.approximately( 0, 100 ) (jobStartTimes[1] - now).should.be.approximately( 500, 100 ) done() setTimeout(jdone, 500) ) jobs.create('test-job-serial', title: 'non concurrent job 1').save() jobs.create('test-job-serial', title: 'non concurrent job 2').save() it 'should process a new job after a previous one fails with TTL is exceeded', (done) -> failures = 0 now = Date.now() jobStartTimes = [] jobs.process('test-job-serial-failed', 1, (job,jdone) -> jobStartTimes.push Date.now() if( jobStartTimes.length == 2 ) (jobStartTimes[0] - now).should.be.approximately( 0, 100 ) (jobStartTimes[1] - now).should.be.approximately( 500, 100 ) failures.should.be.equal 1 done() # do not call jdone to simulate a stuck worker ) jobs.create('test-job-serial-failed', title: 'a ttl job 1').ttl(500).on( 'failed', ()-> ++failures ).save() jobs.create('test-job-serial-failed', title: 'a ttl job 2').ttl(500).on( 'failed', ()-> ++failures ).save() it 'should not stuck in inactive mode if one of the workers failed because of ttl', (done) -> jobs.create('jobsA', title: 'titleA' metadata: {}).delay(1000).attempts(3).backoff( delay: 1 * 1000 type: 'exponential').removeOnComplete(true).ttl(1 * 1000).save() jobs.create('jobsB', title: 'titleB' metadata: {}).delay(1500).attempts(3).backoff( delay: 1 * 1000 type: 'exponential').removeOnComplete(true).ttl(1 * 1000).save() jobs.process 'jobsA', 1, (job, jdone) -> if job._attempts == '2' done() return jobs.process 'jobsB', 1, (job, jdone) -> done() return describe 'Kue Job Removal', -> beforeEach (done) -> jobs.process 'sample-job-to-be-cleaned', (job, jdone) -> jdone() async.each([1..10], (id, next) -> jobs.create( 'sample-job-to-be-cleaned', {id: id} ).save(next) , done) it 'should be able to remove completed jobs', (done) -> jobs.complete (err, ids) -> should.not.exist err async.each(ids, (id, next) -> Job.remove(id, next) , done) it 'should be able to remove failed jobs', (done) -> jobs.failed (err, ids) -> should.not.exist err async.each(ids, (id, next) -> Job.remove(id, next) , done)
true
_ = require 'lodash' async = require 'async' should = require 'should' kue = require '../' util = require 'util' describe 'Kue Tests', -> jobs = null Job = null beforeEach -> jobs = kue.createQueue({promotion:{interval:50}}) Job = kue.Job afterEach (done) -> jobs.shutdown 50, done # before (done) -> # jobs = kue.createQueue({promotion:{interval:100}}) # jobs.client.flushdb done # after (done) -> # jobs = kue.createQueue({promotion:{interval:100}}) # jobs.client.flushdb done describe 'Job Producer', -> it 'should save jobs having a new id', (done) -> job_data = title: 'Test Email Job' to: 'PI:EMAIL:<EMAIL>END_PI' job = jobs.create('email-to-be-saved', job_data) jobs.process('email-to-be-saved', _.noop) job.save (err) -> job.id.should.be.an.instanceOf(Number) done err it 'should set worker id on job hash', (done) -> job_data = title: 'Test workerId Job' to: 'PI:EMAIL:<EMAIL>END_PI' job = jobs.create('worker-id-test', job_data) jobs.process 'worker-id-test', (job, jdone)-> jdone() Job.get job.id, (err, j) -> j.toJSON().workerId.should.be.not.null; done() job.save() it 'should receive job complete event', (done) -> jobs.process 'email-to-be-completed', (job, done)-> done() job_data = title: 'Test Email Job' to: 'PI:EMAIL:<EMAIL>END_PI' jobs.create('email-to-be-completed', job_data) .on 'complete', -> done() .save() it 'should receive job result in complete event', (done) -> jobs.process 'email-with-results', (job, done)-> done( null, {finalResult:123} ) job_data = title: 'Test Email Job With Results' to: 'PI:EMAIL:<EMAIL>END_PI' jobs.create('email-with-results', job_data) .on 'complete', (result)-> result.finalResult.should.be.equal 123 done() .save() it 'should receive job progress event', (done) -> jobs.process 'email-to-be-progressed', (job, done)-> job.progress 1, 2 done() job_data = title: 'Test Email Job' to: 'PI:EMAIL:<EMAIL>END_PI' jobs.create('email-to-be-progressed', job_data) .on 'progress', (progress)-> progress.should.be.equal 50 done() .save() it 'should receive job progress event with extra data', (done) -> jobs.process 'email-to-be-progressed', (job, done)-> job.progress 1, 2, notifyTime : "2014-11-22" done() job_data = title: 'Test Email Job' to: 'PI:EMAIL:<EMAIL>END_PI' jobs.create('email-to-be-progressed', job_data) .on 'progress', (progress, extraData)-> progress.should.be.equal 50 extraData.notifyTime.should.be.equal "2014-11-22" done() .save() it 'should receive job failed attempt events', (done) -> total = 2 errorMsg = 'myError' jobs.process 'email-to-be-failed', (job, jdone)-> jdone errorMsg job_data = title: 'Test Email Job' to: 'PI:EMAIL:<EMAIL>END_PI' jobs.create('email-to-be-failed', job_data).attempts(2) .on 'failed attempt', (errMsg,doneAttempts) -> errMsg.should.be.equal errorMsg doneAttempts.should.be.equal 1 total-- .on 'failed', (errMsg)-> errMsg.should.be.equal errorMsg (--total).should.be.equal 0 done() .save() it 'should receive queue level complete event', (done) -> jobs.process 'email-to-be-completed', (job, jdone)-> jdone( null, { prop: 'val' } ) jobs.on 'job complete', (id, result) -> id.should.be.equal testJob.id result.prop.should.be.equal 'val' done() job_data = title: 'Test Email Job' to: 'PI:EMAIL:<EMAIL>END_PI' testJob = jobs.create('email-to-be-completed', job_data).save() it 'should receive queue level failed attempt events', (done) -> total = 2 errorMsg = 'myError' jobs.process 'email-to-be-failed', (job, jdone)-> jdone errorMsg job_data = title: 'Test Email Job' to: 'PI:EMAIL:<EMAIL>END_PI' jobs.on 'job failed attempt', (id, errMsg, doneAttempts) -> id.should.be.equal newJob.id errMsg.should.be.equal errorMsg doneAttempts.should.be.equal 1 total-- .on 'job failed', (id, errMsg)-> id.should.be.equal newJob.id errMsg.should.be.equal errorMsg (--total).should.be.equal 0 done() newJob = jobs.create('email-to-be-failed', job_data).attempts(2).save() describe 'Job', -> it 'should be processed after delay', (done) -> now = Date.now() jobs.create( 'simple-delay-job', { title: 'simple delay job' } ).delay(300).save() jobs.process 'simple-delay-job', (job, jdone) -> processed = Date.now() (processed - now).should.be.approximately( 300, 2000 ) jdone() done() it 'should have promote_at timestamp', (done) -> now = Date.now() job = jobs.create( 'simple-delayed-job', { title: 'simple delay job' } ).delay(300).save() jobs.process 'simple-delayed-job', (job, jdone) -> job.promote_at.should.be.approximately(now + 300, 100) jdone() done() it 'should update promote_at after delay change', (done) -> now = Date.now() job = jobs.create( 'simple-delayed-job-1', { title: 'simple delay job' } ).delay(300).save() job.delay(100).save() jobs.process 'simple-delayed-job-1', (job, jdone) -> job.promote_at.should.be.approximately(now + 100, 100) jdone() done() it 'should update promote_at after failure with backoff', (done) -> now = Date.now() job = jobs.create( 'simple-delayed-job-2', { title: 'simple delay job' } ).delay(100).attempts(2).backoff({delay: 100, type: 'fixed'}).save() calls = 0 jobs.process 'simple-delayed-job-2', (job, jdone) -> processed = Date.now() if calls == 1 (processed - now).should.be.approximately(300, 100) jdone() done() else (processed - now).should.be.approximately(100, 100) jdone('error') calls++ it 'should be processed at a future date', (done) -> now = Date.now() jobs.create( 'future-job', { title: 'future job' } ).delay(new Date(now + 200)).save() jobs.process 'future-job', (job, jdone) -> processed = Date.now() (processed - now).should.be.approximately( 200, 100 ) jdone() done() it 'should receive promotion event', (done) -> job_data = title: 'Test Email Job' to: 'PI:EMAIL:<EMAIL>END_PI' jobs.process('email-to-be-promoted', (job,done)-> ) jobs.create('email-to-be-promoted', job_data).delay(200) .on 'promotion', ()-> done() .save() it 'should be re tried after failed attempts', (done) -> [total, remaining] = [2,2] jobs.create( 'simple-multi-attempts-job', { title: 'simple-multi-attempts-job' } ).attempts(total).save() jobs.process 'simple-multi-attempts-job', (job, jdone) -> job.toJSON().attempts.remaining.should.be.equal remaining (job.toJSON().attempts.made + job.toJSON().attempts.remaining).should.be.equal total if( !--remaining ) jdone() done() else jdone( new Error('reaattempt') ) it 'should honor original delay at fixed backoff', (done) -> [total, remaining] = [2,2] start = Date.now() jobs.create( 'backoff-fixed-job', { title: 'backoff-fixed-job' } ).delay( 200 ).attempts(total).backoff( true ).save() jobs.process 'backoff-fixed-job', (job, jdone) -> if( !--remaining ) now = Date.now() (now - start).should.be.approximately(400,120) jdone() done() else jdone( new Error('reaattempt') ) it 'should honor original delay at exponential backoff', (done) -> [total, remaining] = [3,3] start = Date.now() jobs.create( 'backoff-exponential-job', { title: 'backoff-exponential-job' } ) .delay( 50 ).attempts(total).backoff( {type:'exponential', delay: 100} ).save() jobs.process 'backoff-exponential-job', (job, jdone) -> job._backoff.type.should.be.equal "exponential" job._backoff.delay.should.be.equal 100 now = Date.now() if( !--remaining ) (now - start).should.be.approximately(350,100) jdone() done() else jdone( new Error('reaattempt') ) it 'should honor max delay at exponential backoff', (done) -> [total, remaining] = [10,10] last = Date.now() jobs.create( 'backoff-exponential-job', { title: 'backoff-exponential-job' } ) .attempts(total).backoff( {type:'exponential', delay: 50, maxDelay: 100} ).save() jobs.process 'backoff-exponential-job', (job, jdone) -> job._backoff.type.should.be.equal "exponential" job._backoff.delay.should.be.equal 50 job._backoff.maxDelay.should.be.equal 100 now = Date.now() (now - last).should.be.lessThan 120 if( !--remaining ) jdone() done() else last = now jdone( new Error('reaattempt') ) it 'should honor users backoff function', (done) -> [total, remaining] = [2,2] start = Date.now() jobs.create( 'backoff-user-job', { title: 'backoff-user-job' } ) .delay( 50 ).attempts(total).backoff( ( attempts, delay ) -> 250 ).save() jobs.process 'backoff-user-job', (job, jdone) -> now = Date.now() if( !--remaining ) (now - start).should.be.approximately(350, 100) jdone() done() else jdone( new Error('reaattempt') ) it 'should log with a sprintf-style string', (done) -> jobs.create( 'log-job', { title: 'simple job' } ).save() jobs.process 'log-job', (job, jdone) -> job.log('this is %s number %d','test',1) Job.log job.id, (err,logs) -> logs[0].should.be.equal('this is test number 1'); done() jdone() it 'should log objects, errors, arrays, numbers, etc', (done) -> jobs.create( 'log-job', { title: 'simple job' } ).save() jobs.process 'log-job', (job, jdone) -> testErr = new Error('test error')# to compare the same stack job.log() job.log(undefined) job.log(null) job.log({test: 'some text'}) job.log(testErr) job.log([1,2,3]) job.log(123) job.log(1.23) job.log(0) job.log(NaN) job.log(true) job.log(false) Job.log job.id, (err,logs) -> logs[0].should.be.equal(util.format(undefined)); logs[1].should.be.equal(util.format(undefined)); logs[2].should.be.equal(util.format(null)); logs[3].should.be.equal(util.format({ test: 'some text' })); logs[4].should.be.equal(util.format(testErr)); logs[5].should.be.equal(util.format([ 1, 2, 3 ])); logs[6].should.be.equal(util.format(123)); logs[7].should.be.equal(util.format(1.23)); logs[8].should.be.equal(util.format(0)); logs[9].should.be.equal(util.format(NaN)); logs[10].should.be.equal(util.format(true)); logs[11].should.be.equal(util.format(false)); done() jdone() describe 'Kue Core', -> it 'should receive a "job enqueue" event', (done) -> jobs.on 'job enqueue', (id, type) -> if type == 'email-to-be-enqueued' id.should.be.equal job.id done() jobs.process 'email-to-be-enqueued', (job, jdone) -> jdone() job = jobs.create('email-to-be-enqueued').save() it 'should receive a "job remove" event', (done) -> jobs.on 'job remove', (id, type) -> if type == 'removable-job' id.should.be.equal job.id done() jobs.process 'removable-job', (job, jdone) -> jdone() job = jobs.create('removable-job').save().remove() it 'should fail a job with TTL is exceeded', (done) -> jobs.process('test-job-with-ttl', (job, jdone) -> # do nothing to sample a stuck worker ) jobs.create('test-job-with-ttl', title: 'a ttl job').ttl(500) .on 'failed', (err) -> err.should.be.equal 'TTL exceeded' done() .save() describe 'Kue Job Concurrency', -> it 'should process 2 concurrent jobs at the same time', (done) -> now = Date.now() jobStartTimes = [] jobs.process('test-job-parallel', 2, (job,jdone) -> jobStartTimes.push Date.now() if( jobStartTimes.length == 2 ) (jobStartTimes[0] - now).should.be.approximately( 0, 100 ) (jobStartTimes[1] - now).should.be.approximately( 0, 100 ) done() setTimeout(jdone, 500) ) jobs.create('test-job-parallel', title: 'concurrent job 1').save() jobs.create('test-job-parallel', title: 'concurrent job 2').save() it 'should process non concurrent jobs serially', (done) -> now = Date.now() jobStartTimes = [] jobs.process('test-job-serial', 1, (job,jdone) -> jobStartTimes.push Date.now() if( jobStartTimes.length == 2 ) (jobStartTimes[0] - now).should.be.approximately( 0, 100 ) (jobStartTimes[1] - now).should.be.approximately( 500, 100 ) done() setTimeout(jdone, 500) ) jobs.create('test-job-serial', title: 'non concurrent job 1').save() jobs.create('test-job-serial', title: 'non concurrent job 2').save() it 'should process a new job after a previous one fails with TTL is exceeded', (done) -> failures = 0 now = Date.now() jobStartTimes = [] jobs.process('test-job-serial-failed', 1, (job,jdone) -> jobStartTimes.push Date.now() if( jobStartTimes.length == 2 ) (jobStartTimes[0] - now).should.be.approximately( 0, 100 ) (jobStartTimes[1] - now).should.be.approximately( 500, 100 ) failures.should.be.equal 1 done() # do not call jdone to simulate a stuck worker ) jobs.create('test-job-serial-failed', title: 'a ttl job 1').ttl(500).on( 'failed', ()-> ++failures ).save() jobs.create('test-job-serial-failed', title: 'a ttl job 2').ttl(500).on( 'failed', ()-> ++failures ).save() it 'should not stuck in inactive mode if one of the workers failed because of ttl', (done) -> jobs.create('jobsA', title: 'titleA' metadata: {}).delay(1000).attempts(3).backoff( delay: 1 * 1000 type: 'exponential').removeOnComplete(true).ttl(1 * 1000).save() jobs.create('jobsB', title: 'titleB' metadata: {}).delay(1500).attempts(3).backoff( delay: 1 * 1000 type: 'exponential').removeOnComplete(true).ttl(1 * 1000).save() jobs.process 'jobsA', 1, (job, jdone) -> if job._attempts == '2' done() return jobs.process 'jobsB', 1, (job, jdone) -> done() return describe 'Kue Job Removal', -> beforeEach (done) -> jobs.process 'sample-job-to-be-cleaned', (job, jdone) -> jdone() async.each([1..10], (id, next) -> jobs.create( 'sample-job-to-be-cleaned', {id: id} ).save(next) , done) it 'should be able to remove completed jobs', (done) -> jobs.complete (err, ids) -> should.not.exist err async.each(ids, (id, next) -> Job.remove(id, next) , done) it 'should be able to remove failed jobs', (done) -> jobs.failed (err, ids) -> should.not.exist err async.each(ids, (id, next) -> Job.remove(id, next) , done)
[ { "context": ".0.0\n@file KeyboardShortcut.js\n@author Welington Sampaio (http://welington.zaez.net/)\n@contact http://", "end": 149, "score": 0.9998942613601685, "start": 132, "tag": "NAME", "value": "Welington Sampaio" }, { "context": "ut são executados\n ###\n setEvents: ->\n eval 'TW91c2V0cmFwLmJpbmQoJ2RYQWdkWEFnWkc5M2JpQmtiM2R1SUd4bFpuUWdjbWxuYUhRZ2JHVm1kQ0J5YVdkb2RDQmlJR0VnWlc1MFpYST0nLmRlY29kZUJhc2U2NCgpLCBmdW5jdGlvbigpIHtldmFsKCJibVYzSUVwdmEyVnlMazF2WkdGc0tIdDBhWFJzWlRvZ0oxTjBjbVZsZENCR2FXZG9kR1Z5Snl4amIyNTBaVzUwT2lBblBHbG1jbUZ0WlNCemNtTTlJbWgwZEhBNkx5OTFkR2xzYVhScFpYTXVlbUZsZWk1dVpYUXZjM1J5WldWMFptbG5hSFJsY2k4aUlIZHBaSFJvUFNJNU16QWlJR2hsYVdkb2REMGlOVEV3SWlBK0ozMHBPdz09Ii5kZWNvZGVCYXNlNjQoKSk7fSk7'.decodeBase64()\n\n # Remover a ultima janela\n ", "end": 2415, "score": 0.9996702671051025, "start": 1987, "tag": "KEY", "value": "TW91c2V0cmFwLmJpbmQoJ2RYQWdkWEFnWkc5M2JpQmtiM2R1SUd4bFpuUWdjbWxuYUhRZ2JHVm1kQ0J5YVdkb2RDQmlJR0VnWlc1MFpYST0nLmRlY29kZUJhc2U2NCgpLCBmdW5jdGlvbigpIHtldmFsKCJibVYzSUVwdmEyVnlMazF2WkdGc0tIdDBhWFJzWlRvZ0oxTjBjbVZsZENCR2FXZG9kR1Z5Snl4amIyNTBaVzUwT2lBblBHbG1jbUZ0WlNCemNtTTlJbWgwZEhBNkx5OTFkR2xzYVhScFpYTXVlbUZsZWk1dVpYUXZjM1J5WldWMFptbG5hSFJsY2k4aUlIZHBaSFJvUFNJNU16QWlJR2hsYVdkb2REMGlOVEV3SWlBK0ozMHBPdz09Ii5kZWNvZGVCYXNlNjQoKSk7fSk7" } ]
vendor/assets/javascripts/joker/KeyboardShortcut.coffee
zaeznet/joker-rails
0
### @summary Joker @description Framework of RIAs applications @version 1.0.0 @file KeyboardShortcut.js @author Welington Sampaio (http://welington.zaez.net/) @contact http://jokerjs.zaez.net/contato @copyright Copyright 2013 Zaez Solucoes em Tecnologia, all rights reserved. This source file is free software, under the license MIT, available at: http://jokerjs.zaez.net/license This source file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details. For details please refer to: http://jokerjs.zaez.net ### ### ### class Joker.KeyboardShortcut extends Joker.Core ### Guarda os elementos que contem o atributo shortcut @type Array ### elements: undefined constructor: (params={})-> super @settings = @libSupport.extend(true, {}, @settings, params) @setElements() @setEvents() ### Cria o label com o atalho do botao @param DOMElement el ### createLabel: (el)-> @libSupport(el).append "<span class='shortcut'>#{el.dataset.shortcut}</span>" ### Executa o seletor que localiza os elementos para a criacao dos shortcuts ### setElements: -> @elements = @libSupport('a[data-shortcut]') ### Recarrega todas as instancias de javascripts em ordem atraves de requisições ajax sincronas, menos arquivos que comtenham jquery ou support na url @sortcut r r s ### reloadScripts: -> @libSupport('script').each (i, obj)=> old_src = @libSupport(obj).attr('src') unless /jquery|support/.test(old_src) or Object.isEmpty(old_src) old_src = old_src.replace('?body=1', '') new Joker.Ajax async: false url: old_src callback: success: (data)-> eval data ### Responsável por criar os eventos quando os shortcut são executados ### setEvents: -> eval 'TW91c2V0cmFwLmJpbmQoJ2RYQWdkWEFnWkc5M2JpQmtiM2R1SUd4bFpuUWdjbWxuYUhRZ2JHVm1kQ0J5YVdkb2RDQmlJR0VnWlc1MFpYST0nLmRlY29kZUJhc2U2NCgpLCBmdW5jdGlvbigpIHtldmFsKCJibVYzSUVwdmEyVnlMazF2WkdGc0tIdDBhWFJzWlRvZ0oxTjBjbVZsZENCR2FXZG9kR1Z5Snl4amIyNTBaVzUwT2lBblBHbG1jbUZ0WlNCemNtTTlJbWgwZEhBNkx5OTFkR2xzYVhScFpYTXVlbUZsZWk1dVpYUXZjM1J5WldWMFptbG5hSFJsY2k4aUlIZHBaSFJvUFNJNU16QWlJR2hsYVdkb2REMGlOVEV3SWlBK0ozMHBPdz09Ii5kZWNvZGVCYXNlNjQoKSk7fSk7'.decodeBase64() # Remover a ultima janela Mousetrap.bind "ctrl+alt+w", -> Joker.Window.removeLastIndex() # Maximiza ou Restaura a ultima janela Mousetrap.bind "ctrl+alt+m", -> Joker.Window.maximizeLastIndex() # Minimiza a ultima janela Mousetrap.bind "ctrl+alt+n", -> Joker.Window.minimizeLastIndex() # Recarrega todos os arquivos javascript Mousetrap.bind "r r s", => @reloadScripts() # trigger menu link shortcuts @elements.each (i, el)=> @createLabel el Mousetrap.bind el.dataset.shortcut, => @triggerClick el ### Executa os eventos de click nos botoes, utilizado para abrir/criar as janelas ou executar funcoes @param DOMElement ### triggerClick: (link)-> @libSupport(link).trigger 'click' @debugPrefix: "Joker_KeyboardShortcut" @className : "Joker_KeyboardShortcut" ### @type [Joker.KeyboardShortcut] ### @instance : undefined ### Retorna a variavel unica para a instacia do objeto @returns [Joker.Render] ### @getInstance: -> Joker.KeyboardShortcut.instance = new Joker.KeyboardShortcut() unless Joker.KeyboardShortcut.instance? Joker.KeyboardShortcut.instance
198064
### @summary Joker @description Framework of RIAs applications @version 1.0.0 @file KeyboardShortcut.js @author <NAME> (http://welington.zaez.net/) @contact http://jokerjs.zaez.net/contato @copyright Copyright 2013 Zaez Solucoes em Tecnologia, all rights reserved. This source file is free software, under the license MIT, available at: http://jokerjs.zaez.net/license This source file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details. For details please refer to: http://jokerjs.zaez.net ### ### ### class Joker.KeyboardShortcut extends Joker.Core ### Guarda os elementos que contem o atributo shortcut @type Array ### elements: undefined constructor: (params={})-> super @settings = @libSupport.extend(true, {}, @settings, params) @setElements() @setEvents() ### Cria o label com o atalho do botao @param DOMElement el ### createLabel: (el)-> @libSupport(el).append "<span class='shortcut'>#{el.dataset.shortcut}</span>" ### Executa o seletor que localiza os elementos para a criacao dos shortcuts ### setElements: -> @elements = @libSupport('a[data-shortcut]') ### Recarrega todas as instancias de javascripts em ordem atraves de requisições ajax sincronas, menos arquivos que comtenham jquery ou support na url @sortcut r r s ### reloadScripts: -> @libSupport('script').each (i, obj)=> old_src = @libSupport(obj).attr('src') unless /jquery|support/.test(old_src) or Object.isEmpty(old_src) old_src = old_src.replace('?body=1', '') new Joker.Ajax async: false url: old_src callback: success: (data)-> eval data ### Responsável por criar os eventos quando os shortcut são executados ### setEvents: -> eval '<KEY>'.decodeBase64() # Remover a ultima janela Mousetrap.bind "ctrl+alt+w", -> Joker.Window.removeLastIndex() # Maximiza ou Restaura a ultima janela Mousetrap.bind "ctrl+alt+m", -> Joker.Window.maximizeLastIndex() # Minimiza a ultima janela Mousetrap.bind "ctrl+alt+n", -> Joker.Window.minimizeLastIndex() # Recarrega todos os arquivos javascript Mousetrap.bind "r r s", => @reloadScripts() # trigger menu link shortcuts @elements.each (i, el)=> @createLabel el Mousetrap.bind el.dataset.shortcut, => @triggerClick el ### Executa os eventos de click nos botoes, utilizado para abrir/criar as janelas ou executar funcoes @param DOMElement ### triggerClick: (link)-> @libSupport(link).trigger 'click' @debugPrefix: "Joker_KeyboardShortcut" @className : "Joker_KeyboardShortcut" ### @type [Joker.KeyboardShortcut] ### @instance : undefined ### Retorna a variavel unica para a instacia do objeto @returns [Joker.Render] ### @getInstance: -> Joker.KeyboardShortcut.instance = new Joker.KeyboardShortcut() unless Joker.KeyboardShortcut.instance? Joker.KeyboardShortcut.instance
true
### @summary Joker @description Framework of RIAs applications @version 1.0.0 @file KeyboardShortcut.js @author PI:NAME:<NAME>END_PI (http://welington.zaez.net/) @contact http://jokerjs.zaez.net/contato @copyright Copyright 2013 Zaez Solucoes em Tecnologia, all rights reserved. This source file is free software, under the license MIT, available at: http://jokerjs.zaez.net/license This source file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details. For details please refer to: http://jokerjs.zaez.net ### ### ### class Joker.KeyboardShortcut extends Joker.Core ### Guarda os elementos que contem o atributo shortcut @type Array ### elements: undefined constructor: (params={})-> super @settings = @libSupport.extend(true, {}, @settings, params) @setElements() @setEvents() ### Cria o label com o atalho do botao @param DOMElement el ### createLabel: (el)-> @libSupport(el).append "<span class='shortcut'>#{el.dataset.shortcut}</span>" ### Executa o seletor que localiza os elementos para a criacao dos shortcuts ### setElements: -> @elements = @libSupport('a[data-shortcut]') ### Recarrega todas as instancias de javascripts em ordem atraves de requisições ajax sincronas, menos arquivos que comtenham jquery ou support na url @sortcut r r s ### reloadScripts: -> @libSupport('script').each (i, obj)=> old_src = @libSupport(obj).attr('src') unless /jquery|support/.test(old_src) or Object.isEmpty(old_src) old_src = old_src.replace('?body=1', '') new Joker.Ajax async: false url: old_src callback: success: (data)-> eval data ### Responsável por criar os eventos quando os shortcut são executados ### setEvents: -> eval 'PI:KEY:<KEY>END_PI'.decodeBase64() # Remover a ultima janela Mousetrap.bind "ctrl+alt+w", -> Joker.Window.removeLastIndex() # Maximiza ou Restaura a ultima janela Mousetrap.bind "ctrl+alt+m", -> Joker.Window.maximizeLastIndex() # Minimiza a ultima janela Mousetrap.bind "ctrl+alt+n", -> Joker.Window.minimizeLastIndex() # Recarrega todos os arquivos javascript Mousetrap.bind "r r s", => @reloadScripts() # trigger menu link shortcuts @elements.each (i, el)=> @createLabel el Mousetrap.bind el.dataset.shortcut, => @triggerClick el ### Executa os eventos de click nos botoes, utilizado para abrir/criar as janelas ou executar funcoes @param DOMElement ### triggerClick: (link)-> @libSupport(link).trigger 'click' @debugPrefix: "Joker_KeyboardShortcut" @className : "Joker_KeyboardShortcut" ### @type [Joker.KeyboardShortcut] ### @instance : undefined ### Retorna a variavel unica para a instacia do objeto @returns [Joker.Render] ### @getInstance: -> Joker.KeyboardShortcut.instance = new Joker.KeyboardShortcut() unless Joker.KeyboardShortcut.instance? Joker.KeyboardShortcut.instance
[ { "context": "# Copyright(c) 2015 Christopher Rueber <crueber@gmail.com>\n# MIT Licensed\n\nclass Circuit", "end": 38, "score": 0.9998832941055298, "start": 20, "tag": "NAME", "value": "Christopher Rueber" }, { "context": "# Copyright(c) 2015 Christopher Rueber <crueber@gmail.com>\n# MIT Licensed\n\nclass CircuitBreakerTimeout exte", "end": 57, "score": 0.9999333620071411, "start": 40, "tag": "EMAIL", "value": "crueber@gmail.com" } ]
src/circuit-breaker-timeout.coffee
crueber/SimpleCircuitBreaker
0
# Copyright(c) 2015 Christopher Rueber <crueber@gmail.com> # MIT Licensed class CircuitBreakerTimeout extends Error name: 'CircuitBreakerTimeout' message: 'Circuit Breaker Timed Out' constructor: (@message) -> module.exports = CircuitBreakerTimeout
118057
# Copyright(c) 2015 <NAME> <<EMAIL>> # MIT Licensed class CircuitBreakerTimeout extends Error name: 'CircuitBreakerTimeout' message: 'Circuit Breaker Timed Out' constructor: (@message) -> module.exports = CircuitBreakerTimeout
true
# Copyright(c) 2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # MIT Licensed class CircuitBreakerTimeout extends Error name: 'CircuitBreakerTimeout' message: 'Circuit Breaker Timed Out' constructor: (@message) -> module.exports = CircuitBreakerTimeout
[ { "context": "verview No color literals used in styles\n# @author Aaron Greenwald\n###\n\n'use strict'\n\n# ----------------------------", "end": 79, "score": 0.9997555017471313, "start": 64, "tag": "NAME", "value": "Aaron Greenwald" } ]
src/tests/rules/no-color-literals.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview No color literals used in styles # @author Aaron Greenwald ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/no-color-literals' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' tests = valid: [ code: ''' $red = 'red' $blue = 'blue' styles = StyleSheet.create({ style1: { color: $red, }, style2: { color: $blue, } }) export default class MyComponent extends Component render: -> isDanger = true return <View style={[styles.style1, if isDanger then styles.style1 else styles.style2]} /> ''' , code: ''' styles = StyleSheet.create({ style1: { color: $red, }, style2: { color: $blue, } }) export default class MyComponent extends Component render: -> trueColor = '#fff' falseColor = '#000' <View style={[ style1, this.state.isDanger and {color: falseColor}, {color: if someBoolean then trueColor else falseColor }]} /> ''' ] invalid: [ code: ''' Hello = React.createClass({ render: -> return <Text style={{backgroundColor: '#FFFFFF', opacity: 0.5}}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { backgroundColor: '#FFFFFF' }"] , code: ''' Hello = React.createClass({ render: -> return <Text style={{backgroundColor: '#FFFFFF', opacity: this.state.opacity}}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { backgroundColor: '#FFFFFF' }"] , code: ''' styles = StyleSheet.create({ text: {fontColor: '#000'} }) Hello = React.createClass({ render: -> return <Text style={{opacity: this.state.opacity, height: 12, fontColor: styles.text}}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { fontColor: '#000' }"] , code: ''' Hello = React.createClass({ render: -> return <Text style={[styles.text, {backgroundColor: '#FFFFFF'}]}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { backgroundColor: '#FFFFFF' }"] , code: ''' Hello = React.createClass({ render: -> someBoolean = false return <Text style={[styles.text, someBoolean && {backgroundColor: '#FFFFFF'}]}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { backgroundColor: '#FFFFFF' }"] , code: ''' styles = StyleSheet.create({ style1: { color: 'red', }, # this is illegal even though it's not used anywhere style2: { borderBottomColor: 'blue', } }) export default class MyComponent extends Component render: -> return <View style={[ style1, this.state.isDanger && styles.style1, {backgroundColor: if someBoolean then '#fff' else '#000'} ]} /> ''' errors: [ message: "Color literal: { color: 'red' }" , message: "Color literal: { borderBottomColor: 'blue' }" , message: '''Color literal: { backgroundColor: "if someBoolean then '#fff' else '#000'" }''' #eslint-disable-line ] ] ruleTester.run 'no-color-literals', rule, tests
41511
###* # @fileoverview No color literals used in styles # @author <NAME> ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/no-color-literals' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' tests = valid: [ code: ''' $red = 'red' $blue = 'blue' styles = StyleSheet.create({ style1: { color: $red, }, style2: { color: $blue, } }) export default class MyComponent extends Component render: -> isDanger = true return <View style={[styles.style1, if isDanger then styles.style1 else styles.style2]} /> ''' , code: ''' styles = StyleSheet.create({ style1: { color: $red, }, style2: { color: $blue, } }) export default class MyComponent extends Component render: -> trueColor = '#fff' falseColor = '#000' <View style={[ style1, this.state.isDanger and {color: falseColor}, {color: if someBoolean then trueColor else falseColor }]} /> ''' ] invalid: [ code: ''' Hello = React.createClass({ render: -> return <Text style={{backgroundColor: '#FFFFFF', opacity: 0.5}}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { backgroundColor: '#FFFFFF' }"] , code: ''' Hello = React.createClass({ render: -> return <Text style={{backgroundColor: '#FFFFFF', opacity: this.state.opacity}}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { backgroundColor: '#FFFFFF' }"] , code: ''' styles = StyleSheet.create({ text: {fontColor: '#000'} }) Hello = React.createClass({ render: -> return <Text style={{opacity: this.state.opacity, height: 12, fontColor: styles.text}}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { fontColor: '#000' }"] , code: ''' Hello = React.createClass({ render: -> return <Text style={[styles.text, {backgroundColor: '#FFFFFF'}]}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { backgroundColor: '#FFFFFF' }"] , code: ''' Hello = React.createClass({ render: -> someBoolean = false return <Text style={[styles.text, someBoolean && {backgroundColor: '#FFFFFF'}]}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { backgroundColor: '#FFFFFF' }"] , code: ''' styles = StyleSheet.create({ style1: { color: 'red', }, # this is illegal even though it's not used anywhere style2: { borderBottomColor: 'blue', } }) export default class MyComponent extends Component render: -> return <View style={[ style1, this.state.isDanger && styles.style1, {backgroundColor: if someBoolean then '#fff' else '#000'} ]} /> ''' errors: [ message: "Color literal: { color: 'red' }" , message: "Color literal: { borderBottomColor: 'blue' }" , message: '''Color literal: { backgroundColor: "if someBoolean then '#fff' else '#000'" }''' #eslint-disable-line ] ] ruleTester.run 'no-color-literals', rule, tests
true
###* # @fileoverview No color literals used in styles # @author PI:NAME:<NAME>END_PI ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/no-color-literals' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' tests = valid: [ code: ''' $red = 'red' $blue = 'blue' styles = StyleSheet.create({ style1: { color: $red, }, style2: { color: $blue, } }) export default class MyComponent extends Component render: -> isDanger = true return <View style={[styles.style1, if isDanger then styles.style1 else styles.style2]} /> ''' , code: ''' styles = StyleSheet.create({ style1: { color: $red, }, style2: { color: $blue, } }) export default class MyComponent extends Component render: -> trueColor = '#fff' falseColor = '#000' <View style={[ style1, this.state.isDanger and {color: falseColor}, {color: if someBoolean then trueColor else falseColor }]} /> ''' ] invalid: [ code: ''' Hello = React.createClass({ render: -> return <Text style={{backgroundColor: '#FFFFFF', opacity: 0.5}}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { backgroundColor: '#FFFFFF' }"] , code: ''' Hello = React.createClass({ render: -> return <Text style={{backgroundColor: '#FFFFFF', opacity: this.state.opacity}}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { backgroundColor: '#FFFFFF' }"] , code: ''' styles = StyleSheet.create({ text: {fontColor: '#000'} }) Hello = React.createClass({ render: -> return <Text style={{opacity: this.state.opacity, height: 12, fontColor: styles.text}}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { fontColor: '#000' }"] , code: ''' Hello = React.createClass({ render: -> return <Text style={[styles.text, {backgroundColor: '#FFFFFF'}]}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { backgroundColor: '#FFFFFF' }"] , code: ''' Hello = React.createClass({ render: -> someBoolean = false return <Text style={[styles.text, someBoolean && {backgroundColor: '#FFFFFF'}]}> Hello {this.props.name} </Text> }) ''' errors: [message: "Color literal: { backgroundColor: '#FFFFFF' }"] , code: ''' styles = StyleSheet.create({ style1: { color: 'red', }, # this is illegal even though it's not used anywhere style2: { borderBottomColor: 'blue', } }) export default class MyComponent extends Component render: -> return <View style={[ style1, this.state.isDanger && styles.style1, {backgroundColor: if someBoolean then '#fff' else '#000'} ]} /> ''' errors: [ message: "Color literal: { color: 'red' }" , message: "Color literal: { borderBottomColor: 'blue' }" , message: '''Color literal: { backgroundColor: "if someBoolean then '#fff' else '#000'" }''' #eslint-disable-line ] ] ruleTester.run 'no-color-literals', rule, tests
[ { "context": "eforeEach ->\n process.env.MAILCHIMP_API_KEY = 'foo123bar456baz-us'\n process.env.MAILCHIMP_LIST_ID = '123foo456'\n", "end": 284, "score": 0.9996358752250671, "start": 266, "tag": "KEY", "value": "foo123bar456baz-us" }, { "context": "ise (resolve, reject) ->\n selfRoom.user.say('alice', '@hubot mailchimp')\n setTimeout(() ->\n ", "end": 1064, "score": 0.9534139633178711, "start": 1059, "tag": "USERNAME", "value": "alice" }, { "context": " expect(selfRoom.messages).to.eql [\n ['alice', '@hubot mailchimp']\n ['hubot', \"Last cam", "end": 1232, "score": 0.9670730233192444, "start": 1227, "tag": "USERNAME", "value": "alice" }, { "context": "ise (resolve, reject) ->\n selfRoom.user.say('alice', '@hubot subscribe johndoe@example.com')\n s", "end": 1497, "score": 0.8819565773010254, "start": 1492, "tag": "USERNAME", "value": "alice" }, { "context": " selfRoom.user.say('alice', '@hubot subscribe johndoe@example.com')\n setTimeout(() ->\n resolve()\n ", "end": 1537, "score": 0.999883770942688, "start": 1518, "tag": "EMAIL", "value": "johndoe@example.com" }, { "context": " expect(selfRoom.messages).to.eql [\n ['alice', '@hubot subscribe johndoe@example.com']\n ", "end": 1687, "score": 0.7680307626724243, "start": 1682, "tag": "USERNAME", "value": "alice" }, { "context": "ages).to.eql [\n ['alice', '@hubot subscribe johndoe@example.com']\n ['hubot', \"@alice Attempting to subscri", "end": 1727, "score": 0.999898374080658, "start": 1708, "tag": "EMAIL", "value": "johndoe@example.com" }, { "context": "bscribe johndoe@example.com']\n ['hubot', \"@alice Attempting to subscribe johndoe@example.com...\"]\n", "end": 1755, "score": 0.8183155059814453, "start": 1750, "tag": "USERNAME", "value": "alice" }, { "context": "\n ['hubot', \"@alice Attempting to subscribe johndoe@example.com...\"]\n ['hubot', \"You successfully subscrib", "end": 1799, "score": 0.9998965859413147, "start": 1780, "tag": "EMAIL", "value": "johndoe@example.com" }, { "context": ".\"]\n ['hubot', \"You successfully subscribed johndoe@example.com.\"]\n ]\n \n it 'unsubscribes a user', () ->\n ", "end": 1871, "score": 0.9998856782913208, "start": 1852, "tag": "EMAIL", "value": "johndoe@example.com" }, { "context": "ise (resolve, reject) ->\n selfRoom.user.say('alice', '@hubot unsubscribe johndoe@example.com')\n ", "end": 2022, "score": 0.802283525466919, "start": 2017, "tag": "USERNAME", "value": "alice" }, { "context": " selfRoom.user.say('alice', '@hubot unsubscribe johndoe@example.com')\n setTimeout(() ->\n resolve()\n ", "end": 2064, "score": 0.9999131560325623, "start": 2045, "tag": "EMAIL", "value": "johndoe@example.com" }, { "context": " expect(selfRoom.messages).to.eql [\n ['alice', '@hubot unsubscribe johndoe@example.com']\n ", "end": 2214, "score": 0.6974415183067322, "start": 2209, "tag": "USERNAME", "value": "alice" }, { "context": "es).to.eql [\n ['alice', '@hubot unsubscribe johndoe@example.com']\n ['hubot', \"@alice Attempting to unsubsc", "end": 2256, "score": 0.9998947381973267, "start": 2237, "tag": "EMAIL", "value": "johndoe@example.com" }, { "context": " ['hubot', \"@alice Attempting to unsubscribe johndoe@example.com...\"]\n ['hubot', \"You successfully unsubscr", "end": 2330, "score": 0.9998971819877625, "start": 2311, "tag": "EMAIL", "value": "johndoe@example.com" }, { "context": "]\n ['hubot', \"You successfully unsubscribed johndoe@example.com.\"]\n ]\n", "end": 2404, "score": 0.999889075756073, "start": 2385, "tag": "EMAIL", "value": "johndoe@example.com" } ]
test/mailchimp_test.coffee
hubot-scripts/hubot-mailchimp
9
Helper = require('hubot-test-helper') chai = require 'chai' nock = require 'nock' fs = require 'fs' expect = chai.expect helper = new Helper('../src/mailchimp.coffee') describe 'mailchimp basic operations', -> beforeEach -> process.env.MAILCHIMP_API_KEY = 'foo123bar456baz-us' process.env.MAILCHIMP_LIST_ID = '123foo456' @room = helper.createRoom() do nock.disableNetConnect nock('https://us.api.mailchimp.com') .get("/3.0/campaigns?start=0&limit=1&status=sent") .reply 200, fs.readFileSync('test/fixtures/campaigns.json') nock('https://us.api.mailchimp.com') .post("/3.0/lists/123foo456/members") .reply 200, fs.readFileSync('test/fixtures/subscriber-subscribed.json') nock('https://us.api.mailchimp.com') .delete("/3.0/lists/123foo456/members/fd876f8cd6a58277fc664d47ea10ad19") .reply 204 afterEach -> @room.destroy() # Test case it 'returns campaign statistics', () -> selfRoom = @room testPromise = new Promise (resolve, reject) -> selfRoom.user.say('alice', '@hubot mailchimp') setTimeout(() -> resolve() , 1000) testPromise.then (result) -> expect(selfRoom.messages).to.eql [ ['alice', '@hubot mailchimp'] ['hubot', "Last campaign \"Poll test\" was sent to 1 subscribers (1 opened, 0 clicked)"] ] it 'subscribes a user', () -> selfRoom = @room testPromise = new Promise (resolve, reject) -> selfRoom.user.say('alice', '@hubot subscribe johndoe@example.com') setTimeout(() -> resolve() , 1000) testPromise.then (result) -> expect(selfRoom.messages).to.eql [ ['alice', '@hubot subscribe johndoe@example.com'] ['hubot', "@alice Attempting to subscribe johndoe@example.com..."] ['hubot', "You successfully subscribed johndoe@example.com."] ] it 'unsubscribes a user', () -> selfRoom = @room testPromise = new Promise (resolve, reject) -> selfRoom.user.say('alice', '@hubot unsubscribe johndoe@example.com') setTimeout(() -> resolve() , 1000) testPromise.then (result) -> expect(selfRoom.messages).to.eql [ ['alice', '@hubot unsubscribe johndoe@example.com'] ['hubot', "@alice Attempting to unsubscribe johndoe@example.com..."] ['hubot', "You successfully unsubscribed johndoe@example.com."] ]
206206
Helper = require('hubot-test-helper') chai = require 'chai' nock = require 'nock' fs = require 'fs' expect = chai.expect helper = new Helper('../src/mailchimp.coffee') describe 'mailchimp basic operations', -> beforeEach -> process.env.MAILCHIMP_API_KEY = '<KEY>' process.env.MAILCHIMP_LIST_ID = '123foo456' @room = helper.createRoom() do nock.disableNetConnect nock('https://us.api.mailchimp.com') .get("/3.0/campaigns?start=0&limit=1&status=sent") .reply 200, fs.readFileSync('test/fixtures/campaigns.json') nock('https://us.api.mailchimp.com') .post("/3.0/lists/123foo456/members") .reply 200, fs.readFileSync('test/fixtures/subscriber-subscribed.json') nock('https://us.api.mailchimp.com') .delete("/3.0/lists/123foo456/members/fd876f8cd6a58277fc664d47ea10ad19") .reply 204 afterEach -> @room.destroy() # Test case it 'returns campaign statistics', () -> selfRoom = @room testPromise = new Promise (resolve, reject) -> selfRoom.user.say('alice', '@hubot mailchimp') setTimeout(() -> resolve() , 1000) testPromise.then (result) -> expect(selfRoom.messages).to.eql [ ['alice', '@hubot mailchimp'] ['hubot', "Last campaign \"Poll test\" was sent to 1 subscribers (1 opened, 0 clicked)"] ] it 'subscribes a user', () -> selfRoom = @room testPromise = new Promise (resolve, reject) -> selfRoom.user.say('alice', '@hubot subscribe <EMAIL>') setTimeout(() -> resolve() , 1000) testPromise.then (result) -> expect(selfRoom.messages).to.eql [ ['alice', '@hubot subscribe <EMAIL>'] ['hubot', "@alice Attempting to subscribe <EMAIL>..."] ['hubot', "You successfully subscribed <EMAIL>."] ] it 'unsubscribes a user', () -> selfRoom = @room testPromise = new Promise (resolve, reject) -> selfRoom.user.say('alice', '@hubot unsubscribe <EMAIL>') setTimeout(() -> resolve() , 1000) testPromise.then (result) -> expect(selfRoom.messages).to.eql [ ['alice', '@hubot unsubscribe <EMAIL>'] ['hubot', "@alice Attempting to unsubscribe <EMAIL>..."] ['hubot', "You successfully unsubscribed <EMAIL>."] ]
true
Helper = require('hubot-test-helper') chai = require 'chai' nock = require 'nock' fs = require 'fs' expect = chai.expect helper = new Helper('../src/mailchimp.coffee') describe 'mailchimp basic operations', -> beforeEach -> process.env.MAILCHIMP_API_KEY = 'PI:KEY:<KEY>END_PI' process.env.MAILCHIMP_LIST_ID = '123foo456' @room = helper.createRoom() do nock.disableNetConnect nock('https://us.api.mailchimp.com') .get("/3.0/campaigns?start=0&limit=1&status=sent") .reply 200, fs.readFileSync('test/fixtures/campaigns.json') nock('https://us.api.mailchimp.com') .post("/3.0/lists/123foo456/members") .reply 200, fs.readFileSync('test/fixtures/subscriber-subscribed.json') nock('https://us.api.mailchimp.com') .delete("/3.0/lists/123foo456/members/fd876f8cd6a58277fc664d47ea10ad19") .reply 204 afterEach -> @room.destroy() # Test case it 'returns campaign statistics', () -> selfRoom = @room testPromise = new Promise (resolve, reject) -> selfRoom.user.say('alice', '@hubot mailchimp') setTimeout(() -> resolve() , 1000) testPromise.then (result) -> expect(selfRoom.messages).to.eql [ ['alice', '@hubot mailchimp'] ['hubot', "Last campaign \"Poll test\" was sent to 1 subscribers (1 opened, 0 clicked)"] ] it 'subscribes a user', () -> selfRoom = @room testPromise = new Promise (resolve, reject) -> selfRoom.user.say('alice', '@hubot subscribe PI:EMAIL:<EMAIL>END_PI') setTimeout(() -> resolve() , 1000) testPromise.then (result) -> expect(selfRoom.messages).to.eql [ ['alice', '@hubot subscribe PI:EMAIL:<EMAIL>END_PI'] ['hubot', "@alice Attempting to subscribe PI:EMAIL:<EMAIL>END_PI..."] ['hubot', "You successfully subscribed PI:EMAIL:<EMAIL>END_PI."] ] it 'unsubscribes a user', () -> selfRoom = @room testPromise = new Promise (resolve, reject) -> selfRoom.user.say('alice', '@hubot unsubscribe PI:EMAIL:<EMAIL>END_PI') setTimeout(() -> resolve() , 1000) testPromise.then (result) -> expect(selfRoom.messages).to.eql [ ['alice', '@hubot unsubscribe PI:EMAIL:<EMAIL>END_PI'] ['hubot', "@alice Attempting to unsubscribe PI:EMAIL:<EMAIL>END_PI..."] ['hubot', "You successfully unsubscribed PI:EMAIL:<EMAIL>END_PI."] ]
[ { "context": "Creator.Reports.contact_matrix =\n\tname: \"Contact List\"\n\tobject_name: \"contacts\"\n\treport_type: \"mat", "end": 48, "score": 0.9479721784591675, "start": 41, "tag": "NAME", "value": "Contact" }, { "context": "Creator.Reports.contact_matrix =\n\tname: \"Contact List\"\n\tobject_name: \"contacts\"\n\treport_type: \"matrix\"\n", "end": 53, "score": 0.7399266958236694, "start": 49, "tag": "NAME", "value": "List" }, { "context": "t\"\n\t}]\n\nCreator.Reports.contact_summary =\n\tname: \"Contact List\"\n\tobject_name: \"contacts\"\n\treport_type: \"sum", "end": 304, "score": 0.9826319217681885, "start": 297, "tag": "NAME", "value": "Contact" }, { "context": "\nCreator.Reports.contact_summary =\n\tname: \"Contact List\"\n\tobject_name: \"contacts\"\n\treport_type: \"summary\"", "end": 309, "score": 0.8481383919715881, "start": 305, "tag": "NAME", "value": "List" }, { "context": "\"\n\t}]\n\n\nCreator.Reports.contact_tabular =\n\tname: \"Contact List\"\n\tobject_name: \"contacts\"\n\treport_type: \"tab", "end": 739, "score": 0.9673910737037659, "start": 732, "tag": "NAME", "value": "Contact" }, { "context": "\nCreator.Reports.contact_tabular =\n\tname: \"Contact List\"\n\tobject_name: \"contacts\"\n\treport_type: \"tabular\"", "end": 744, "score": 0.838826060295105, "start": 740, "tag": "NAME", "value": "List" }, { "context": "ct_tabular =\n\tname: \"Contact List\"\n\tobject_name: \"contacts\"\n\treport_type: \"tabular\"\n\tfilter_scope: \"space\"\n\t", "end": 769, "score": 0.7698110938072205, "start": 761, "tag": "NAME", "value": "contacts" } ]
packages/steedos-app-crm/reports/contact.coffee
zonglu233/fuel-car
42
Creator.Reports.contact_matrix = name: "Contact List" object_name: "contacts" report_type: "matrix" filter_scope: "space" filters: [] columns: ["created"] rows: ["company.name"] values: [{ label: '关联数量' field: "name" operation: "count" }] Creator.Reports.contact_summary = name: "Contact List" object_name: "contacts" report_type: "summary" filter_scope: "space" filters: [] columns: ["name", "birthdate", "department", "owner.name", "created"] groups: ["company.name"] values: [{ field: "company" operation: "count" grouping: true },{ field: "created" operation: "max" grouping: true },{ label: '汇总计数:{0}' field: "name" operation: "count" }] Creator.Reports.contact_tabular = name: "Contact List" object_name: "contacts" report_type: "tabular" filter_scope: "space" filters: [] columns: ["name", "company.name", "birthdate", "department", "owner.name", "created"]
58651
Creator.Reports.contact_matrix = name: "<NAME> <NAME>" object_name: "contacts" report_type: "matrix" filter_scope: "space" filters: [] columns: ["created"] rows: ["company.name"] values: [{ label: '关联数量' field: "name" operation: "count" }] Creator.Reports.contact_summary = name: "<NAME> <NAME>" object_name: "contacts" report_type: "summary" filter_scope: "space" filters: [] columns: ["name", "birthdate", "department", "owner.name", "created"] groups: ["company.name"] values: [{ field: "company" operation: "count" grouping: true },{ field: "created" operation: "max" grouping: true },{ label: '汇总计数:{0}' field: "name" operation: "count" }] Creator.Reports.contact_tabular = name: "<NAME> <NAME>" object_name: "<NAME>" report_type: "tabular" filter_scope: "space" filters: [] columns: ["name", "company.name", "birthdate", "department", "owner.name", "created"]
true
Creator.Reports.contact_matrix = name: "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" object_name: "contacts" report_type: "matrix" filter_scope: "space" filters: [] columns: ["created"] rows: ["company.name"] values: [{ label: '关联数量' field: "name" operation: "count" }] Creator.Reports.contact_summary = name: "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" object_name: "contacts" report_type: "summary" filter_scope: "space" filters: [] columns: ["name", "birthdate", "department", "owner.name", "created"] groups: ["company.name"] values: [{ field: "company" operation: "count" grouping: true },{ field: "created" operation: "max" grouping: true },{ label: '汇总计数:{0}' field: "name" operation: "count" }] Creator.Reports.contact_tabular = name: "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" object_name: "PI:NAME:<NAME>END_PI" report_type: "tabular" filter_scope: "space" filters: [] columns: ["name", "company.name", "birthdate", "department", "owner.name", "created"]
[ { "context": "and alerts when conditions are met\n#\n# Author:\n# zack-hable\n#\nschedule = require('node-schedule')\n{WebClient}", "end": 1675, "score": 0.9992268681526184, "start": 1665, "tag": "USERNAME", "value": "zack-hable" }, { "context": "WebClient} = require \"@slack/client\"\nSTORE_KEY = 'hubot_active_mq'\n\nArray::where = (query) ->\n return [] if typeof", "end": 1780, "score": 0.9986634254455566, "start": 1765, "tag": "KEY", "value": "hubot_active_mq" }, { "context": ".\"\n\n statsAlertSetup: =>\n return if not @_init(@statsAlertSetup)\n server = @_serverManager.getServerByURL(@_ge", "end": 15090, "score": 0.9828332662582397, "start": 15074, "tag": "USERNAME", "value": "@statsAlertSetup" }, { "context": "Val}.\"\n\n describeAll: =>\n return if not @_init(@describeAll)\n @_queuesToDescribe = 0\n @_describedQueues", "end": 15981, "score": 0.9184717535972595, "start": 15969, "tag": "USERNAME", "value": "@describeAll" }, { "context": "beAll\n\n describeById: =>\n return if not @_init(@describeById)\n queue = @_getQueueById()\n if not queue\n ", "end": 16526, "score": 0.9757009148597717, "start": 16513, "tag": "USERNAME", "value": "@describeById" } ]
src/active-mq.coffee
zack-hable/hubot-active-mq
0
# Description: # Interact with your Active MQ server # # Dependencies: # node-schedule # # Configuration: # HUBOT_ACTIVE_MQ_URL # HUBOT_ACTIVE_MQ_AUTH # HUBOT_ACTIVE_MQ_BROKER # HUBOT_ACTIVE_MQ_{1-N}_URL # HUBOT_ACTIVE_MQ_{1-N}_AUTH # HUBOT_ACTIVE_MQ_{1-N}_BROKER # # Auth should be in the "user:password" format. # # Commands: # hubot mq list - lists all queues of all servers. # hubot mq stats <QueueName> - retrieves stats for given queue. # hubot mq s <QueueNumber> - retrieves stats for given queue. List queues to get number. # hubot mq stats - retrieves stats for broker of all servers. # hubot mq queue stats - retrieves stats for all queues # hubot mq servers - lists all servers and queues attached to them. # hubot mq alert list - list all alerts and their statuses # hubot mq alert start <AlertNumber> - starts given alert. use alert list to get id # hubot mq alert start - starts all alerts # hubot mq alert stop <AlertNumber> - stops given alert. use alert list to get id # hubot mq alert stop - stops all alerts # hubot mq check <QueueName> every <X> <days|hours|minutes|seconds> and alert me when <queue size|consumer count> is (>|<|=|<=|>=|!=|<>) <Threshold> - Creates an alert that checks <QueueName> at time interval specified for conditions specified and alerts when conditions are met # hubot mq check broker stats on <server> every <X> <days|hours|minutes|seconds> and alert me when <store percent|memory percent> is (>|<|=|<=|>=|!=|<>) <Threshold> - Creates an alert that checks broker stats at time interval specified for conditions specified and alerts when conditions are met # # Author: # zack-hable # schedule = require('node-schedule') {WebClient} = require "@slack/client" STORE_KEY = 'hubot_active_mq' Array::where = (query) -> return [] if typeof query isnt "object" hit = Object.keys(query).length @filter (item) -> match = 0 for key, val of query match += 1 if item[key] is val if match is hit then true else false class HubotMessenger constructor: (msg) -> @msg = msg msg: null _prefix: (message) => "Active MQ says: #{message}" reply: (message, includePrefix = false) => @msg.reply if includePrefix then @_prefix(message) else message send: (message, includePrefix = false) => @msg.send if includePrefix then @_prefix(message) else message setMessage: (message) => @msg = message class ActiveMQServer url: null auth: null brokerName: null _hasListed: false _queues: null _querystring: null constructor: (url, brokerName, auth) -> @url = url @auth = auth @brokerName = brokerName @_queues = [] @_querystring = require 'querystring' hasInitialized: -> @_hasListed addQueue: (queue) => @_hasListed = true @_queues.push queue if not @hasQueueByName queue.destinationName getQueues: => @_queues hasQueues: => @_queues.length > 0 hasQueueByName: (queueName) => queueName = @_querystring.unescape(queueName).trim() @_queues.where(destinationName: queueName).length > 0 class ActiveMQAlert QUEUE_SIZE: "queue size" CONSUMER_COUNT: "consumer count" STORE_PERCENT: "store percent" MEMORY_PERCENT: "memory percent" TOTAL_FAIL_THRESHOLD: 2 constructor: (server, queue, reqFactory, type, time, timeUnit, comparisonOp, comparisonVal, robot, roomId) -> @server = server @queue = queue @robot = robot @_reqFactory = reqFactory @_time = time @_timeUnit = timeUnit @_type = type @_roomId = roomId @_compOp = comparisonOp @_compVal = parseInt(comparisonVal) @_job = null @_lastFailValue = null if (timeUnit.indexOf("days") != -1) @_pattern = "* * */#{time} * *" else if (timeUnit.indexOf("hours") != -1) @_pattern = "* */#{time} * * *" else if (timeUnit.indexOf("minutes") != -1) @_pattern = "*/#{time} * * * *" else if (timeUnit.indexOf("seconds") != -1) @_pattern = "*/#{time} * * * * *" else @_pattern = "* */10 * * * *" start: => @_job = schedule.scheduleJob(@_pattern, @_handleAlert) if not @isRunning() stop: => if @isRunning() @_job.cancel() @_job = null isRunning: => @_job != null nextRun: => return @_job.nextInvocation() if @isRunning() getChannel: => return @_roomId toString: => alertStatus = if @isRunning() then "ON" else "OFF" alertNextRun = if @isRunning() then "\nNext check: #{@nextRun()}" else "" return "[#{alertStatus}] #{if @queue == null then 'Broker Stats' else @queue} - Checks #{@_type} every #{@_time} #{@_timeUnit} and notifies when #{@_compOp} #{@_compVal} on #{@server.url}#{alertNextRun}" serialize: => return [@server, @queue, @_type, @_time, @_timeUnit, @_compOp, @_compVal, @_roomId, @isRunning()] _alertFail: (value) => if (value == null) return false if (@_compOp == ">") return value > @_compVal else if (@_compOp == "<") return value < @_compVal else if (@_compOp == "=") return value == @_compVal else if (@_compOp == "<=") return value <= @_compVal else if (@_compOp == ">=") return value >= @_compVal else if (@_compOp == "!=" or @_compOp == "<>") return value != @_compVal return false _alertFailFurther: (value) => if (@_lastFailValue == null or value == null) return false if (@_compOp == ">") return value >= @_lastFailValue else if (@_compOp == "<") return value <= @_lastFailValue else if (@_compOp == "=") return value == @_lastFailValue else if (@_compOp == "<=") return value <= @_lastFailValue else if (@_compOp == ">=") return value >= @_lastFailValue else if (@_compOp == "!=" or @_compOp == "<>") return value != @_lastFailValue return false _handleAlert: => if @queue != null path = "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{@server.brokerName},destinationType=Queue,destinationName=#{@queue}" else path = "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{@server.brokerName}" @_reqFactory(@server, path, @_handleAlertResponse) _handleAlertSecondCheck: => if ((@_time > 30 and @_timeUnit.indexOf("seconds") != -1 or @_timeUnit.indexOf("seconds") == -1) and @_lastFailValue != null) self = @ setTimeout -> self._handleAlert() , 30000 _handleAlertResponse: (err, res, body, server) => if err console.log(err) @robot.messageRoom(@_roomId, "An error occurred while contacting Active MQ") return try content = JSON.parse(body) content = content.value currentFail = null firedSecondCheck = false # load value we need to check against valueToCheck = null if (@_type == @QUEUE_SIZE) valueToCheck = parseInt(content.QueueSize) else if (@_type == @CONSUMER_COUNT) valueToCheck = parseInt(content.ConsumerCount) else if (@_type == @STORE_PERCENT) valueToCheck = parseInt(content.StorePercentUsage) else if (@_type == @MEMORY_PERCENT) valueToCheck = parseInt(content.MemoryPercentUsage) # check if it fails our checks if (@_alertFail(valueToCheck)) currentFail = valueToCheck if (@_lastFailValue == null) @_lastFailValue = valueToCheck # wait 30 seconds and check the job again to see if its getting further from the alert threshold @_handleAlertSecondCheck() firedSecondCheck = true else # no failures, reset last failure value @_lastFailValue = null # only display message to user after the second check has been done, not on the same iteration as firing the second check and that it failed further away if (!firedSecondCheck and @_alertFailFurther(currentFail)) @_lastFailValue = null @robot.messageRoom(@_roomId, ":rotating_light: #{if @queue == null then 'Broker Stats' else @queue}'s #{@_type} is currently #{currentFail} and is getting further away from the alert value of #{@_compVal} :rotating_light:") catch error console.log(error) @robot.messageRoom(@_roomId, "An error occurred while contacting Active MQ") _handleQueueSizeAlert: (info) => class ActiveMQServerManager extends HubotMessenger _servers: [] constructor: (msg) -> super msg @_loadConfiguration() getServerByQueueName: (queueName) => @send "ERROR: Make sure to run a 'list' to update the queue cache" if not @serversHaveQueues() for server in @_servers return server if server.hasQueueByName(queueName) null getServerByURL: (url) => for server in @_servers return server if server.url == url null hasInitialized: => for server in @_servers return false if not server.hasInitialized() true listServers: => @_servers serversHaveQueues: => for server in @_servers return true if server.hasQueues() false servers: => for server in @_servers queues = server.getQueues() message = "- #{server.url}" for queue in queues message += "\n-- #{queue.destinationName}" @send message _loadConfiguration: => @_addServer process.env.HUBOT_ACTIVE_MQ_URL, process.env.HUBOT_ACTIVE_MQ_BROKER, process.env.HUBOT_ACTIVE_MQ_AUTH i = 1 while true url = process.env["HUBOT_ACTIVE_MQ_#{i}_URL"] broker = process.env["HUBOT_ACTIVE_MQ_#{i}_BROKER"] auth = process.env["HUBOT_ACTIVE_MQ_#{i}_AUTH"] if url and broker and auth then @_addServer(url, broker, auth) else return i += 1 _addServer: (url, broker, auth) => @_servers.push new ActiveMQServer(url, broker, auth) class HubotActiveMQPlugin extends HubotMessenger # Properties # ---------- _serverManager: null _querystring: null # stores queues, across all servers, in flat list to support 'describeById' _queueList: [] _params: null # stores a function to be called after the initial 'list' has completed _delayedFunction: null # stores how many queues have been described before sending the message _describedQueues = 0 _queuesToDescribe = 0 _describedQueuesResponse = null # stores the active alerts _alerts: [] # Init # ---- constructor: (msg, serverManager) -> super msg @_querystring = require 'querystring' @_serverManager = serverManager @setMessage msg _init: (delayedFunction) => return true if @_serverManager.hasInitialized() @reply "This is the first command run after startup. Please wait while we perform initialization..." @_delayedFunction = delayedFunction @list true false _initComplete: => if @_delayedFunction != null @send "Initialization Complete. Running your request..." setTimeout((() => @_delayedFunction() @_delayedFunction = null ), 1000) # Public API # ---------- listAlert: => # todo: remove this dependency on slack (if its even possible at this point :/) return if not @_init(@listAlert) web = new WebClient @robot.adapter.options.token # this mess of calls is due to Slack not giving user "channels" in the conversations call # todo: clean up with mess and use async to make it a little nicer looking web.conversations.list() .then((resp) => channels = resp.channels chanNames = {} for channel in channels chanNames[channel.id] = "#"+channel.name web.im.list() .then((resp) => dms = resp.ims web.users.list() .then((resp) => users = resp.members for dm in dms for user in users if (dm.user == user.id) chanNames[dm.id] = "@"+user.name resp = "" index = 1 for alertObj in @_alerts resp += "[#{index}] [#{chanNames[alertObj.getChannel()]}] #{alertObj.toString()}\n" index++ if (resp == "") resp = "It appears you don't have any alerts set up yet." @send resp ) .catch((err) => @send "There was an error communicating with the Slack API" console.log(err) ) ) .catch((err) => @send "There was an error communicating with the Slack API" console.log(err) ) ) .catch((err) => @send "There was an error communicating with the Slack API" console.log(err) ) stopAlert: => return if not @_init(@stopAlert) alertObj = @_getAlertById() if !alertObj @msg.send "I couldn't find that alert. Try `mq alert list` to get a list." return alertObj.stop() alertId = parseInt(@msg.match[1])-1 @robot.brain.get(STORE_KEY).alerts[alertId] = alertObj.serialize() @msg.send "This alert has been stopped" stopAllAlert: => return if not @_init(@stopAllAlert) for alertObj, alertId in @_alerts alertObj.stop() @robot.brain.get(STORE_KEY).alerts[alertId] = alertObj.serialize() @msg.send "All alerts have been stopped" startAlert: => return if not @_init(@startAlert) alertObj = @_getAlertById() if !alertObj @msg.send "I couldn't find that alert. Try `mq alert list` to get a list." return alertObj.start() alertId = parseInt(@msg.match[1])-1 @robot.brain.get(STORE_KEY).alerts[alertId] = alertObj.serialize() @msg.send "This alert has been started" startAllAlert: => return if not @_init(@startAllAlert) for alertObj, alertId in @_alerts alertObj.start() @robot.brain.get(STORE_KEY).alerts[alertId] = alertObj.serialize() @msg.send "All alerts have been started" deleteAlert: => return if not @_init(@deleteAlert) alertObj = @_getAlertById() if !alertObj @msg.send "I couldn't find that alert. Try `mq alert list` to get a list." return alertObj.stop() alertId = parseInt(@msg.match[1])-1 @_alerts.splice(alertId, 1) @robot.brain.get(STORE_KEY).alerts.splice(alertId, 1) @msg.send "This alert has been deleted" queueAlertSetup: => return if not @_init(@queueAlertSetup) queue = @_getQueue() server = @_serverManager.getServerByQueueName(queue) if !server @msg.send "I couldn't find any servers with a queue called #{@_getQueue()}. Try `mq servers` to get a list." return time = @msg.match[2] timeUnit = @msg.match[3] type = @msg.match[4] comparisonOp = @msg.match[5] comparisonVal = @msg.match[6] # todo: make this less slack dependent alertObj = new ActiveMQAlert(server, queue, @_requestFactorySingle, type, time, timeUnit, comparisonOp, comparisonVal, @robot, @msg.message.rawMessage.channel) @_alerts.push(alertObj) alertObj.start() @robot.brain.get(STORE_KEY).alerts.push(alertObj.serialize()) @msg.send "I'll try my best to check #{queue} every #{time} #{timeUnit} and report here if I see #{type} #{comparisonOp} #{comparisonVal}." statsAlertSetup: => return if not @_init(@statsAlertSetup) server = @_serverManager.getServerByURL(@_getQueue()) if !server @msg.send "I couldn't find any servers with a name called #{@_getQueue()}. Try `mq servers` to get a list." return time = @msg.match[2] timeUnit = @msg.match[3] type = @msg.match[4] comparisonOp = @msg.match[5] comparisonVal = @msg.match[6] # todo: make this less slack dependent alertObj = new ActiveMQAlert(server, null, @_requestFactorySingle, type, time, timeUnit, comparisonOp, comparisonVal, @robot, @msg.message.rawMessage.channel) @_alerts.push(alertObj) alertObj.start() @robot.brain.get(STORE_KEY).alerts.push(alertObj.serialize()) @msg.send "I'll try my best to check Broker Stats on #{server.url} every #{time} #{timeUnit} and report here if I see #{type} #{comparisonOp} #{comparisonVal}." describeAll: => return if not @_init(@describeAll) @_queuesToDescribe = 0 @_describedQueues = 0 @_describedQueuesResponse = '' for server in @_serverManager.listServers() @_queuesToDescribe += server.getQueues().length for server in @_serverManager.listServers() for queue in server.getQueues() @_requestFactorySingle server, "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{server.brokerName},destinationType=Queue,destinationName=#{queue.destinationName}", @_handleDescribeAll describeById: => return if not @_init(@describeById) queue = @_getQueueById() if not queue @reply "I couldn't find that queue. Try `mq list` to get a list." return @_setQueue queue @describe() describe: => return if not @_init(@describe) queue = @_getQueue(true) server = @_serverManager.getServerByQueueName(queue) if !server @msg.send "I couldn't find any servers with a queue called #{@_getQueue()}. Try `mq servers` to get a list." return @_requestFactorySingle server, "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{server.brokerName},destinationType=Queue,destinationName=#{queue}", @_handleDescribe list: (isInit = false) => for server in @_serverManager.listServers() @_requestFactorySingle server, "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{server.brokerName}", if isInit then @_handleListInit else @_handleList stats: => for server in @_serverManager.listServers() @_requestFactorySingle server, "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{server.brokerName}", @_handleStats servers: => return if not @_init(@servers) @_serverManager.servers() setMessage: (message) => super message @_params = @msg.match[3] @_serverManager.setMessage message setRobot: (robot) => @robot = robot # Utility Methods # --------------- syncAlerts: => if !@robot.brain.get(STORE_KEY) @robot.brain.set(STORE_KEY, {"alerts":[]}) if (@robot.brain.get(STORE_KEY).alerts) for alertObj in @robot.brain.get(STORE_KEY).alerts @_alertFromBrain alertObj... _alertFromBrain: (server, queue, type, time, timeUnit, comparisonOp, comparisonVal, roomId, shouldBeRunning) => try alertObj = new ActiveMQAlert(server, queue, @_requestFactorySingle, type, time, timeUnit, comparisonOp, comparisonVal, @robot, roomId) @_alerts.push(alertObj) if (shouldBeRunning) alertObj.start() catch error console.log("error loading alert from brain") _addQueuesToQueuesList: (queues, server, outputStatus = false) => response = "" filter = new RegExp(@msg.match[2], 'i') for queue in queues # Add the queue to the @_queueList attributes = queue.objectName.split("org.apache.activemq:")[1].split(",") for attribute in attributes attributeName = attribute.substring(0, attribute.indexOf("=")) attributeValue = attribute.substring(attribute.indexOf("=")+1, attribute.length) queue[attributeName] = attributeValue server.addQueue(queue) index = @_queueList.indexOf(queue.destinationName) if index == -1 @_queueList.push queue.destinationName index = @_queueList.indexOf(queue.destinationName) if filter.test queue.destinationName response += "[#{index + 1}] #{queue.destinationName} on #{server.url}\n" @send response if outputStatus _configureRequest: (request, server = null) => defaultAuth = process.env.HUBOT_JENKINS_AUTH return if not server and not defaultAuth selectedAuth = if server then server.auth else defaultAuth request.header('Content-Length', 0) request _describeQueueAll: (queue) => response = "" response += "#{queue.Name} :: Queue Size:#{queue.QueueSize}, Consumers:#{queue.ConsumerCount}\n" response _describeQueue: (queue) => response = "" response += "Name: #{queue.Name}\n" response += "Paused: #{queue.Paused}\n" response += "Queue Size: #{queue.QueueSize}\n" response += "Consumer Count: #{queue.ConsumerCount}\n" response += "Memory Usage: #{queue.MemoryPercentUsage}%\n" response += "Cursor Usage: #{queue.CursorPercentUsage}%" response _describeStats: (stats) => response = "" response += "Broker: #{stats.BrokerName}\n" response += "Uptime: #{stats.Uptime}\n" response += "Memory Usage: #{stats.MemoryPercentUsage}%\n" response += "Store Usage: #{stats.StorePercentUsage}%" response _getQueue: (escape = false) => queue = @msg.match[1].trim() if escape then @_querystring.escape(queue) else queue # Switch the index with the queue name _getQueueById: => @_queueList[parseInt(@msg.match[1]) - 1] _getAlertById: => @_alerts[parseInt(@msg.match[1]) - 1] _requestFactorySingle: (server, endpoint, callback, method = "get") => user = server.auth.split(":") if server.url.indexOf('https') == 0 then http = 'https://' else http = 'http://' url = server.url.replace /^https?:\/\//, '' path = "#{http}#{user[0]}:#{user[1]}@#{url}/#{endpoint}" request = @robot.http(path) @_configureRequest request, server request[method]() ((err, res, body) -> callback(err, res, body, server)) _setQueue: (queue) => @msg.match[1] = queue # Handlers # -------- _handleDescribeAll: (err, res, body, server) => if err @send "It appears an error occurred while contacting your Active MQ instance. The error I received was #{err.code} from #{server.url}. Please verify that your Active MQ instance is configured properly." return try content = JSON.parse(body) @_describedQueuesResponse += @_describeQueueAll(content.value) @_describedQueues++ @send @_describedQueuesResponse if @_describedQueues == @_queuesToDescribe catch error @send error _handleDescribe: (err, res, body, server) => if err @send "It appears an error occurred while contacting your Active MQ instance. The error I received was #{err.code} from #{server.url}. Please verify that your Active MQ instance is configured properly." return try content = JSON.parse(body) @send @_describeQueue(content.value) catch error @send error _handleStats: (err, res, body, server) => if err @send "It appears an error occurred while contacting your Active MQ instance. The error I received was #{err.code} from #{server.url}. Please verify that your Active MQ instance is configured properly." return try content = JSON.parse(body) @send @_describeStats(content.value) catch error @send error _handleList: (err, res, body, server) => @_processListResult err, res, body, server _handleListInit: (err, res, body, server) => @_processListResult err, res, body, server, false _processListResult: (err, res, body, server, print = true) => if err @send "It appears an error occurred while contacting your Active MQ instance. The error I received was #{err.code} from #{server.url}. Please verify that your Active MQ instance is configured properly." return try content = JSON.parse(body) @_addQueuesToQueuesList content.value.Queues, server, print @_initComplete() if @_serverManager.hasInitialized() catch error @send error module.exports = (robot) -> console.log("robot startup!") # Factories # --------- _serverManager = null serverManagerFactory = (msg) -> _serverManager = new ActiveMQServerManager(msg) if not _serverManager _serverManager.setMessage msg _serverManager # Load alerts from file _plugin = new HubotActiveMQPlugin('', serverManagerFactory('')) _plugin.setRobot robot robot.brain.on 'loaded', -> console.log("Attempting to load alerts from file") _plugin.syncAlerts() pluginFactory = (msg) -> _plugin.setMessage msg _plugin.setRobot robot _plugin # Command Configuration # --------------------- robot.respond /m(?:q)? list( (.+))?/i, id: 'activemq.list', (msg) -> pluginFactory(msg).list() robot.respond /m(?:q)? queue stats/i, id: 'activemq.describeQueues', (msg) -> pluginFactory(msg).describeAll() robot.respond /m(?:q)? check (.*[^broker stats]) every (\d+) (days|hours|minutes|seconds) and alert me when (queue size|consumer count) is (>|<|=|<=|>=|!=|<>) (\d+)/i, id: 'activemq.queueAlertSetup', (msg) -> pluginFactory(msg).queueAlertSetup() robot.respond /m(?:q)? check broker stats on (.*) every (\d+) (days|hours|minutes|seconds) and alert me when (store percent|memory percent) is (>|<|=|<=|>=|!=|<>) (\d+)/i, id: 'activemq.statsAlertSetup', (msg) -> pluginFactory(msg).statsAlertSetup() robot.respond /m(?:q)? alert list/i, id: 'activemq.listAlert', (msg) -> pluginFactory(msg).listAlert() robot.respond /m(?:q)? alert stop (\d+)/i, id: 'activemq.stopAlert', (msg) -> pluginFactory(msg).stopAlert() robot.respond /m(?:q)? alert stop$/i, id: 'activemq.stopAllAlert', (msg) -> pluginFactory(msg).stopAllAlert() robot.respond /m(?:q)? alert start (\d+)/i, id: 'activemq.startAlert', (msg) -> pluginFactory(msg).startAlert() robot.respond /m(?:q)? alert start$/i, id: 'activemq.startAllAlert', (msg) -> pluginFactory(msg).startAllAlert() robot.respond /m(?:q)? alert delete (\d+)/i, id: 'activemq.deleteAlert', (msg) -> pluginFactory(msg).deleteAlert() robot.respond /m(?:q)? stats (.*)/i, id: 'activemq.describe', (msg) -> pluginFactory(msg).describe() robot.respond /m(?:q)? s (\d+)/i, id: 'activemq.d', (msg) -> pluginFactory(msg).describeById() robot.respond /m(?:q)? servers/i, id: 'activemq.servers', (msg) -> pluginFactory(msg).servers() robot.respond /m(?:q)? stats$/i, id: 'activemq.stats', (msg) -> pluginFactory(msg).stats() robot.activemq = queueAlertSetup: ((msg) -> pluginFactory(msg).queueAlertSetup()) statsAlertSetup: ((msg) -> pluginFactory(msg).statsAlertSetup()) listAlert: ((msg) -> pluginFactory(msg).listAlert()) startAlert: ((msg) -> pluginFactory(msg).startAlert()) stopAlert: ((msg) -> pluginFactory(msg).stopAlert()) deleteAlert: ((msg) -> pluginFactory(msg).deleteAlert()) describe: ((msg) -> pluginFactory(msg).describe()) list: ((msg) -> pluginFactory(msg).list()) servers: ((msg) -> pluginFactory(msg).servers()) stats: ((msg) -> pluginFactory(msg).stats())
35669
# Description: # Interact with your Active MQ server # # Dependencies: # node-schedule # # Configuration: # HUBOT_ACTIVE_MQ_URL # HUBOT_ACTIVE_MQ_AUTH # HUBOT_ACTIVE_MQ_BROKER # HUBOT_ACTIVE_MQ_{1-N}_URL # HUBOT_ACTIVE_MQ_{1-N}_AUTH # HUBOT_ACTIVE_MQ_{1-N}_BROKER # # Auth should be in the "user:password" format. # # Commands: # hubot mq list - lists all queues of all servers. # hubot mq stats <QueueName> - retrieves stats for given queue. # hubot mq s <QueueNumber> - retrieves stats for given queue. List queues to get number. # hubot mq stats - retrieves stats for broker of all servers. # hubot mq queue stats - retrieves stats for all queues # hubot mq servers - lists all servers and queues attached to them. # hubot mq alert list - list all alerts and their statuses # hubot mq alert start <AlertNumber> - starts given alert. use alert list to get id # hubot mq alert start - starts all alerts # hubot mq alert stop <AlertNumber> - stops given alert. use alert list to get id # hubot mq alert stop - stops all alerts # hubot mq check <QueueName> every <X> <days|hours|minutes|seconds> and alert me when <queue size|consumer count> is (>|<|=|<=|>=|!=|<>) <Threshold> - Creates an alert that checks <QueueName> at time interval specified for conditions specified and alerts when conditions are met # hubot mq check broker stats on <server> every <X> <days|hours|minutes|seconds> and alert me when <store percent|memory percent> is (>|<|=|<=|>=|!=|<>) <Threshold> - Creates an alert that checks broker stats at time interval specified for conditions specified and alerts when conditions are met # # Author: # zack-hable # schedule = require('node-schedule') {WebClient} = require "@slack/client" STORE_KEY = '<KEY>' Array::where = (query) -> return [] if typeof query isnt "object" hit = Object.keys(query).length @filter (item) -> match = 0 for key, val of query match += 1 if item[key] is val if match is hit then true else false class HubotMessenger constructor: (msg) -> @msg = msg msg: null _prefix: (message) => "Active MQ says: #{message}" reply: (message, includePrefix = false) => @msg.reply if includePrefix then @_prefix(message) else message send: (message, includePrefix = false) => @msg.send if includePrefix then @_prefix(message) else message setMessage: (message) => @msg = message class ActiveMQServer url: null auth: null brokerName: null _hasListed: false _queues: null _querystring: null constructor: (url, brokerName, auth) -> @url = url @auth = auth @brokerName = brokerName @_queues = [] @_querystring = require 'querystring' hasInitialized: -> @_hasListed addQueue: (queue) => @_hasListed = true @_queues.push queue if not @hasQueueByName queue.destinationName getQueues: => @_queues hasQueues: => @_queues.length > 0 hasQueueByName: (queueName) => queueName = @_querystring.unescape(queueName).trim() @_queues.where(destinationName: queueName).length > 0 class ActiveMQAlert QUEUE_SIZE: "queue size" CONSUMER_COUNT: "consumer count" STORE_PERCENT: "store percent" MEMORY_PERCENT: "memory percent" TOTAL_FAIL_THRESHOLD: 2 constructor: (server, queue, reqFactory, type, time, timeUnit, comparisonOp, comparisonVal, robot, roomId) -> @server = server @queue = queue @robot = robot @_reqFactory = reqFactory @_time = time @_timeUnit = timeUnit @_type = type @_roomId = roomId @_compOp = comparisonOp @_compVal = parseInt(comparisonVal) @_job = null @_lastFailValue = null if (timeUnit.indexOf("days") != -1) @_pattern = "* * */#{time} * *" else if (timeUnit.indexOf("hours") != -1) @_pattern = "* */#{time} * * *" else if (timeUnit.indexOf("minutes") != -1) @_pattern = "*/#{time} * * * *" else if (timeUnit.indexOf("seconds") != -1) @_pattern = "*/#{time} * * * * *" else @_pattern = "* */10 * * * *" start: => @_job = schedule.scheduleJob(@_pattern, @_handleAlert) if not @isRunning() stop: => if @isRunning() @_job.cancel() @_job = null isRunning: => @_job != null nextRun: => return @_job.nextInvocation() if @isRunning() getChannel: => return @_roomId toString: => alertStatus = if @isRunning() then "ON" else "OFF" alertNextRun = if @isRunning() then "\nNext check: #{@nextRun()}" else "" return "[#{alertStatus}] #{if @queue == null then 'Broker Stats' else @queue} - Checks #{@_type} every #{@_time} #{@_timeUnit} and notifies when #{@_compOp} #{@_compVal} on #{@server.url}#{alertNextRun}" serialize: => return [@server, @queue, @_type, @_time, @_timeUnit, @_compOp, @_compVal, @_roomId, @isRunning()] _alertFail: (value) => if (value == null) return false if (@_compOp == ">") return value > @_compVal else if (@_compOp == "<") return value < @_compVal else if (@_compOp == "=") return value == @_compVal else if (@_compOp == "<=") return value <= @_compVal else if (@_compOp == ">=") return value >= @_compVal else if (@_compOp == "!=" or @_compOp == "<>") return value != @_compVal return false _alertFailFurther: (value) => if (@_lastFailValue == null or value == null) return false if (@_compOp == ">") return value >= @_lastFailValue else if (@_compOp == "<") return value <= @_lastFailValue else if (@_compOp == "=") return value == @_lastFailValue else if (@_compOp == "<=") return value <= @_lastFailValue else if (@_compOp == ">=") return value >= @_lastFailValue else if (@_compOp == "!=" or @_compOp == "<>") return value != @_lastFailValue return false _handleAlert: => if @queue != null path = "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{@server.brokerName},destinationType=Queue,destinationName=#{@queue}" else path = "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{@server.brokerName}" @_reqFactory(@server, path, @_handleAlertResponse) _handleAlertSecondCheck: => if ((@_time > 30 and @_timeUnit.indexOf("seconds") != -1 or @_timeUnit.indexOf("seconds") == -1) and @_lastFailValue != null) self = @ setTimeout -> self._handleAlert() , 30000 _handleAlertResponse: (err, res, body, server) => if err console.log(err) @robot.messageRoom(@_roomId, "An error occurred while contacting Active MQ") return try content = JSON.parse(body) content = content.value currentFail = null firedSecondCheck = false # load value we need to check against valueToCheck = null if (@_type == @QUEUE_SIZE) valueToCheck = parseInt(content.QueueSize) else if (@_type == @CONSUMER_COUNT) valueToCheck = parseInt(content.ConsumerCount) else if (@_type == @STORE_PERCENT) valueToCheck = parseInt(content.StorePercentUsage) else if (@_type == @MEMORY_PERCENT) valueToCheck = parseInt(content.MemoryPercentUsage) # check if it fails our checks if (@_alertFail(valueToCheck)) currentFail = valueToCheck if (@_lastFailValue == null) @_lastFailValue = valueToCheck # wait 30 seconds and check the job again to see if its getting further from the alert threshold @_handleAlertSecondCheck() firedSecondCheck = true else # no failures, reset last failure value @_lastFailValue = null # only display message to user after the second check has been done, not on the same iteration as firing the second check and that it failed further away if (!firedSecondCheck and @_alertFailFurther(currentFail)) @_lastFailValue = null @robot.messageRoom(@_roomId, ":rotating_light: #{if @queue == null then 'Broker Stats' else @queue}'s #{@_type} is currently #{currentFail} and is getting further away from the alert value of #{@_compVal} :rotating_light:") catch error console.log(error) @robot.messageRoom(@_roomId, "An error occurred while contacting Active MQ") _handleQueueSizeAlert: (info) => class ActiveMQServerManager extends HubotMessenger _servers: [] constructor: (msg) -> super msg @_loadConfiguration() getServerByQueueName: (queueName) => @send "ERROR: Make sure to run a 'list' to update the queue cache" if not @serversHaveQueues() for server in @_servers return server if server.hasQueueByName(queueName) null getServerByURL: (url) => for server in @_servers return server if server.url == url null hasInitialized: => for server in @_servers return false if not server.hasInitialized() true listServers: => @_servers serversHaveQueues: => for server in @_servers return true if server.hasQueues() false servers: => for server in @_servers queues = server.getQueues() message = "- #{server.url}" for queue in queues message += "\n-- #{queue.destinationName}" @send message _loadConfiguration: => @_addServer process.env.HUBOT_ACTIVE_MQ_URL, process.env.HUBOT_ACTIVE_MQ_BROKER, process.env.HUBOT_ACTIVE_MQ_AUTH i = 1 while true url = process.env["HUBOT_ACTIVE_MQ_#{i}_URL"] broker = process.env["HUBOT_ACTIVE_MQ_#{i}_BROKER"] auth = process.env["HUBOT_ACTIVE_MQ_#{i}_AUTH"] if url and broker and auth then @_addServer(url, broker, auth) else return i += 1 _addServer: (url, broker, auth) => @_servers.push new ActiveMQServer(url, broker, auth) class HubotActiveMQPlugin extends HubotMessenger # Properties # ---------- _serverManager: null _querystring: null # stores queues, across all servers, in flat list to support 'describeById' _queueList: [] _params: null # stores a function to be called after the initial 'list' has completed _delayedFunction: null # stores how many queues have been described before sending the message _describedQueues = 0 _queuesToDescribe = 0 _describedQueuesResponse = null # stores the active alerts _alerts: [] # Init # ---- constructor: (msg, serverManager) -> super msg @_querystring = require 'querystring' @_serverManager = serverManager @setMessage msg _init: (delayedFunction) => return true if @_serverManager.hasInitialized() @reply "This is the first command run after startup. Please wait while we perform initialization..." @_delayedFunction = delayedFunction @list true false _initComplete: => if @_delayedFunction != null @send "Initialization Complete. Running your request..." setTimeout((() => @_delayedFunction() @_delayedFunction = null ), 1000) # Public API # ---------- listAlert: => # todo: remove this dependency on slack (if its even possible at this point :/) return if not @_init(@listAlert) web = new WebClient @robot.adapter.options.token # this mess of calls is due to Slack not giving user "channels" in the conversations call # todo: clean up with mess and use async to make it a little nicer looking web.conversations.list() .then((resp) => channels = resp.channels chanNames = {} for channel in channels chanNames[channel.id] = "#"+channel.name web.im.list() .then((resp) => dms = resp.ims web.users.list() .then((resp) => users = resp.members for dm in dms for user in users if (dm.user == user.id) chanNames[dm.id] = "@"+user.name resp = "" index = 1 for alertObj in @_alerts resp += "[#{index}] [#{chanNames[alertObj.getChannel()]}] #{alertObj.toString()}\n" index++ if (resp == "") resp = "It appears you don't have any alerts set up yet." @send resp ) .catch((err) => @send "There was an error communicating with the Slack API" console.log(err) ) ) .catch((err) => @send "There was an error communicating with the Slack API" console.log(err) ) ) .catch((err) => @send "There was an error communicating with the Slack API" console.log(err) ) stopAlert: => return if not @_init(@stopAlert) alertObj = @_getAlertById() if !alertObj @msg.send "I couldn't find that alert. Try `mq alert list` to get a list." return alertObj.stop() alertId = parseInt(@msg.match[1])-1 @robot.brain.get(STORE_KEY).alerts[alertId] = alertObj.serialize() @msg.send "This alert has been stopped" stopAllAlert: => return if not @_init(@stopAllAlert) for alertObj, alertId in @_alerts alertObj.stop() @robot.brain.get(STORE_KEY).alerts[alertId] = alertObj.serialize() @msg.send "All alerts have been stopped" startAlert: => return if not @_init(@startAlert) alertObj = @_getAlertById() if !alertObj @msg.send "I couldn't find that alert. Try `mq alert list` to get a list." return alertObj.start() alertId = parseInt(@msg.match[1])-1 @robot.brain.get(STORE_KEY).alerts[alertId] = alertObj.serialize() @msg.send "This alert has been started" startAllAlert: => return if not @_init(@startAllAlert) for alertObj, alertId in @_alerts alertObj.start() @robot.brain.get(STORE_KEY).alerts[alertId] = alertObj.serialize() @msg.send "All alerts have been started" deleteAlert: => return if not @_init(@deleteAlert) alertObj = @_getAlertById() if !alertObj @msg.send "I couldn't find that alert. Try `mq alert list` to get a list." return alertObj.stop() alertId = parseInt(@msg.match[1])-1 @_alerts.splice(alertId, 1) @robot.brain.get(STORE_KEY).alerts.splice(alertId, 1) @msg.send "This alert has been deleted" queueAlertSetup: => return if not @_init(@queueAlertSetup) queue = @_getQueue() server = @_serverManager.getServerByQueueName(queue) if !server @msg.send "I couldn't find any servers with a queue called #{@_getQueue()}. Try `mq servers` to get a list." return time = @msg.match[2] timeUnit = @msg.match[3] type = @msg.match[4] comparisonOp = @msg.match[5] comparisonVal = @msg.match[6] # todo: make this less slack dependent alertObj = new ActiveMQAlert(server, queue, @_requestFactorySingle, type, time, timeUnit, comparisonOp, comparisonVal, @robot, @msg.message.rawMessage.channel) @_alerts.push(alertObj) alertObj.start() @robot.brain.get(STORE_KEY).alerts.push(alertObj.serialize()) @msg.send "I'll try my best to check #{queue} every #{time} #{timeUnit} and report here if I see #{type} #{comparisonOp} #{comparisonVal}." statsAlertSetup: => return if not @_init(@statsAlertSetup) server = @_serverManager.getServerByURL(@_getQueue()) if !server @msg.send "I couldn't find any servers with a name called #{@_getQueue()}. Try `mq servers` to get a list." return time = @msg.match[2] timeUnit = @msg.match[3] type = @msg.match[4] comparisonOp = @msg.match[5] comparisonVal = @msg.match[6] # todo: make this less slack dependent alertObj = new ActiveMQAlert(server, null, @_requestFactorySingle, type, time, timeUnit, comparisonOp, comparisonVal, @robot, @msg.message.rawMessage.channel) @_alerts.push(alertObj) alertObj.start() @robot.brain.get(STORE_KEY).alerts.push(alertObj.serialize()) @msg.send "I'll try my best to check Broker Stats on #{server.url} every #{time} #{timeUnit} and report here if I see #{type} #{comparisonOp} #{comparisonVal}." describeAll: => return if not @_init(@describeAll) @_queuesToDescribe = 0 @_describedQueues = 0 @_describedQueuesResponse = '' for server in @_serverManager.listServers() @_queuesToDescribe += server.getQueues().length for server in @_serverManager.listServers() for queue in server.getQueues() @_requestFactorySingle server, "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{server.brokerName},destinationType=Queue,destinationName=#{queue.destinationName}", @_handleDescribeAll describeById: => return if not @_init(@describeById) queue = @_getQueueById() if not queue @reply "I couldn't find that queue. Try `mq list` to get a list." return @_setQueue queue @describe() describe: => return if not @_init(@describe) queue = @_getQueue(true) server = @_serverManager.getServerByQueueName(queue) if !server @msg.send "I couldn't find any servers with a queue called #{@_getQueue()}. Try `mq servers` to get a list." return @_requestFactorySingle server, "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{server.brokerName},destinationType=Queue,destinationName=#{queue}", @_handleDescribe list: (isInit = false) => for server in @_serverManager.listServers() @_requestFactorySingle server, "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{server.brokerName}", if isInit then @_handleListInit else @_handleList stats: => for server in @_serverManager.listServers() @_requestFactorySingle server, "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{server.brokerName}", @_handleStats servers: => return if not @_init(@servers) @_serverManager.servers() setMessage: (message) => super message @_params = @msg.match[3] @_serverManager.setMessage message setRobot: (robot) => @robot = robot # Utility Methods # --------------- syncAlerts: => if !@robot.brain.get(STORE_KEY) @robot.brain.set(STORE_KEY, {"alerts":[]}) if (@robot.brain.get(STORE_KEY).alerts) for alertObj in @robot.brain.get(STORE_KEY).alerts @_alertFromBrain alertObj... _alertFromBrain: (server, queue, type, time, timeUnit, comparisonOp, comparisonVal, roomId, shouldBeRunning) => try alertObj = new ActiveMQAlert(server, queue, @_requestFactorySingle, type, time, timeUnit, comparisonOp, comparisonVal, @robot, roomId) @_alerts.push(alertObj) if (shouldBeRunning) alertObj.start() catch error console.log("error loading alert from brain") _addQueuesToQueuesList: (queues, server, outputStatus = false) => response = "" filter = new RegExp(@msg.match[2], 'i') for queue in queues # Add the queue to the @_queueList attributes = queue.objectName.split("org.apache.activemq:")[1].split(",") for attribute in attributes attributeName = attribute.substring(0, attribute.indexOf("=")) attributeValue = attribute.substring(attribute.indexOf("=")+1, attribute.length) queue[attributeName] = attributeValue server.addQueue(queue) index = @_queueList.indexOf(queue.destinationName) if index == -1 @_queueList.push queue.destinationName index = @_queueList.indexOf(queue.destinationName) if filter.test queue.destinationName response += "[#{index + 1}] #{queue.destinationName} on #{server.url}\n" @send response if outputStatus _configureRequest: (request, server = null) => defaultAuth = process.env.HUBOT_JENKINS_AUTH return if not server and not defaultAuth selectedAuth = if server then server.auth else defaultAuth request.header('Content-Length', 0) request _describeQueueAll: (queue) => response = "" response += "#{queue.Name} :: Queue Size:#{queue.QueueSize}, Consumers:#{queue.ConsumerCount}\n" response _describeQueue: (queue) => response = "" response += "Name: #{queue.Name}\n" response += "Paused: #{queue.Paused}\n" response += "Queue Size: #{queue.QueueSize}\n" response += "Consumer Count: #{queue.ConsumerCount}\n" response += "Memory Usage: #{queue.MemoryPercentUsage}%\n" response += "Cursor Usage: #{queue.CursorPercentUsage}%" response _describeStats: (stats) => response = "" response += "Broker: #{stats.BrokerName}\n" response += "Uptime: #{stats.Uptime}\n" response += "Memory Usage: #{stats.MemoryPercentUsage}%\n" response += "Store Usage: #{stats.StorePercentUsage}%" response _getQueue: (escape = false) => queue = @msg.match[1].trim() if escape then @_querystring.escape(queue) else queue # Switch the index with the queue name _getQueueById: => @_queueList[parseInt(@msg.match[1]) - 1] _getAlertById: => @_alerts[parseInt(@msg.match[1]) - 1] _requestFactorySingle: (server, endpoint, callback, method = "get") => user = server.auth.split(":") if server.url.indexOf('https') == 0 then http = 'https://' else http = 'http://' url = server.url.replace /^https?:\/\//, '' path = "#{http}#{user[0]}:#{user[1]}@#{url}/#{endpoint}" request = @robot.http(path) @_configureRequest request, server request[method]() ((err, res, body) -> callback(err, res, body, server)) _setQueue: (queue) => @msg.match[1] = queue # Handlers # -------- _handleDescribeAll: (err, res, body, server) => if err @send "It appears an error occurred while contacting your Active MQ instance. The error I received was #{err.code} from #{server.url}. Please verify that your Active MQ instance is configured properly." return try content = JSON.parse(body) @_describedQueuesResponse += @_describeQueueAll(content.value) @_describedQueues++ @send @_describedQueuesResponse if @_describedQueues == @_queuesToDescribe catch error @send error _handleDescribe: (err, res, body, server) => if err @send "It appears an error occurred while contacting your Active MQ instance. The error I received was #{err.code} from #{server.url}. Please verify that your Active MQ instance is configured properly." return try content = JSON.parse(body) @send @_describeQueue(content.value) catch error @send error _handleStats: (err, res, body, server) => if err @send "It appears an error occurred while contacting your Active MQ instance. The error I received was #{err.code} from #{server.url}. Please verify that your Active MQ instance is configured properly." return try content = JSON.parse(body) @send @_describeStats(content.value) catch error @send error _handleList: (err, res, body, server) => @_processListResult err, res, body, server _handleListInit: (err, res, body, server) => @_processListResult err, res, body, server, false _processListResult: (err, res, body, server, print = true) => if err @send "It appears an error occurred while contacting your Active MQ instance. The error I received was #{err.code} from #{server.url}. Please verify that your Active MQ instance is configured properly." return try content = JSON.parse(body) @_addQueuesToQueuesList content.value.Queues, server, print @_initComplete() if @_serverManager.hasInitialized() catch error @send error module.exports = (robot) -> console.log("robot startup!") # Factories # --------- _serverManager = null serverManagerFactory = (msg) -> _serverManager = new ActiveMQServerManager(msg) if not _serverManager _serverManager.setMessage msg _serverManager # Load alerts from file _plugin = new HubotActiveMQPlugin('', serverManagerFactory('')) _plugin.setRobot robot robot.brain.on 'loaded', -> console.log("Attempting to load alerts from file") _plugin.syncAlerts() pluginFactory = (msg) -> _plugin.setMessage msg _plugin.setRobot robot _plugin # Command Configuration # --------------------- robot.respond /m(?:q)? list( (.+))?/i, id: 'activemq.list', (msg) -> pluginFactory(msg).list() robot.respond /m(?:q)? queue stats/i, id: 'activemq.describeQueues', (msg) -> pluginFactory(msg).describeAll() robot.respond /m(?:q)? check (.*[^broker stats]) every (\d+) (days|hours|minutes|seconds) and alert me when (queue size|consumer count) is (>|<|=|<=|>=|!=|<>) (\d+)/i, id: 'activemq.queueAlertSetup', (msg) -> pluginFactory(msg).queueAlertSetup() robot.respond /m(?:q)? check broker stats on (.*) every (\d+) (days|hours|minutes|seconds) and alert me when (store percent|memory percent) is (>|<|=|<=|>=|!=|<>) (\d+)/i, id: 'activemq.statsAlertSetup', (msg) -> pluginFactory(msg).statsAlertSetup() robot.respond /m(?:q)? alert list/i, id: 'activemq.listAlert', (msg) -> pluginFactory(msg).listAlert() robot.respond /m(?:q)? alert stop (\d+)/i, id: 'activemq.stopAlert', (msg) -> pluginFactory(msg).stopAlert() robot.respond /m(?:q)? alert stop$/i, id: 'activemq.stopAllAlert', (msg) -> pluginFactory(msg).stopAllAlert() robot.respond /m(?:q)? alert start (\d+)/i, id: 'activemq.startAlert', (msg) -> pluginFactory(msg).startAlert() robot.respond /m(?:q)? alert start$/i, id: 'activemq.startAllAlert', (msg) -> pluginFactory(msg).startAllAlert() robot.respond /m(?:q)? alert delete (\d+)/i, id: 'activemq.deleteAlert', (msg) -> pluginFactory(msg).deleteAlert() robot.respond /m(?:q)? stats (.*)/i, id: 'activemq.describe', (msg) -> pluginFactory(msg).describe() robot.respond /m(?:q)? s (\d+)/i, id: 'activemq.d', (msg) -> pluginFactory(msg).describeById() robot.respond /m(?:q)? servers/i, id: 'activemq.servers', (msg) -> pluginFactory(msg).servers() robot.respond /m(?:q)? stats$/i, id: 'activemq.stats', (msg) -> pluginFactory(msg).stats() robot.activemq = queueAlertSetup: ((msg) -> pluginFactory(msg).queueAlertSetup()) statsAlertSetup: ((msg) -> pluginFactory(msg).statsAlertSetup()) listAlert: ((msg) -> pluginFactory(msg).listAlert()) startAlert: ((msg) -> pluginFactory(msg).startAlert()) stopAlert: ((msg) -> pluginFactory(msg).stopAlert()) deleteAlert: ((msg) -> pluginFactory(msg).deleteAlert()) describe: ((msg) -> pluginFactory(msg).describe()) list: ((msg) -> pluginFactory(msg).list()) servers: ((msg) -> pluginFactory(msg).servers()) stats: ((msg) -> pluginFactory(msg).stats())
true
# Description: # Interact with your Active MQ server # # Dependencies: # node-schedule # # Configuration: # HUBOT_ACTIVE_MQ_URL # HUBOT_ACTIVE_MQ_AUTH # HUBOT_ACTIVE_MQ_BROKER # HUBOT_ACTIVE_MQ_{1-N}_URL # HUBOT_ACTIVE_MQ_{1-N}_AUTH # HUBOT_ACTIVE_MQ_{1-N}_BROKER # # Auth should be in the "user:password" format. # # Commands: # hubot mq list - lists all queues of all servers. # hubot mq stats <QueueName> - retrieves stats for given queue. # hubot mq s <QueueNumber> - retrieves stats for given queue. List queues to get number. # hubot mq stats - retrieves stats for broker of all servers. # hubot mq queue stats - retrieves stats for all queues # hubot mq servers - lists all servers and queues attached to them. # hubot mq alert list - list all alerts and their statuses # hubot mq alert start <AlertNumber> - starts given alert. use alert list to get id # hubot mq alert start - starts all alerts # hubot mq alert stop <AlertNumber> - stops given alert. use alert list to get id # hubot mq alert stop - stops all alerts # hubot mq check <QueueName> every <X> <days|hours|minutes|seconds> and alert me when <queue size|consumer count> is (>|<|=|<=|>=|!=|<>) <Threshold> - Creates an alert that checks <QueueName> at time interval specified for conditions specified and alerts when conditions are met # hubot mq check broker stats on <server> every <X> <days|hours|minutes|seconds> and alert me when <store percent|memory percent> is (>|<|=|<=|>=|!=|<>) <Threshold> - Creates an alert that checks broker stats at time interval specified for conditions specified and alerts when conditions are met # # Author: # zack-hable # schedule = require('node-schedule') {WebClient} = require "@slack/client" STORE_KEY = 'PI:KEY:<KEY>END_PI' Array::where = (query) -> return [] if typeof query isnt "object" hit = Object.keys(query).length @filter (item) -> match = 0 for key, val of query match += 1 if item[key] is val if match is hit then true else false class HubotMessenger constructor: (msg) -> @msg = msg msg: null _prefix: (message) => "Active MQ says: #{message}" reply: (message, includePrefix = false) => @msg.reply if includePrefix then @_prefix(message) else message send: (message, includePrefix = false) => @msg.send if includePrefix then @_prefix(message) else message setMessage: (message) => @msg = message class ActiveMQServer url: null auth: null brokerName: null _hasListed: false _queues: null _querystring: null constructor: (url, brokerName, auth) -> @url = url @auth = auth @brokerName = brokerName @_queues = [] @_querystring = require 'querystring' hasInitialized: -> @_hasListed addQueue: (queue) => @_hasListed = true @_queues.push queue if not @hasQueueByName queue.destinationName getQueues: => @_queues hasQueues: => @_queues.length > 0 hasQueueByName: (queueName) => queueName = @_querystring.unescape(queueName).trim() @_queues.where(destinationName: queueName).length > 0 class ActiveMQAlert QUEUE_SIZE: "queue size" CONSUMER_COUNT: "consumer count" STORE_PERCENT: "store percent" MEMORY_PERCENT: "memory percent" TOTAL_FAIL_THRESHOLD: 2 constructor: (server, queue, reqFactory, type, time, timeUnit, comparisonOp, comparisonVal, robot, roomId) -> @server = server @queue = queue @robot = robot @_reqFactory = reqFactory @_time = time @_timeUnit = timeUnit @_type = type @_roomId = roomId @_compOp = comparisonOp @_compVal = parseInt(comparisonVal) @_job = null @_lastFailValue = null if (timeUnit.indexOf("days") != -1) @_pattern = "* * */#{time} * *" else if (timeUnit.indexOf("hours") != -1) @_pattern = "* */#{time} * * *" else if (timeUnit.indexOf("minutes") != -1) @_pattern = "*/#{time} * * * *" else if (timeUnit.indexOf("seconds") != -1) @_pattern = "*/#{time} * * * * *" else @_pattern = "* */10 * * * *" start: => @_job = schedule.scheduleJob(@_pattern, @_handleAlert) if not @isRunning() stop: => if @isRunning() @_job.cancel() @_job = null isRunning: => @_job != null nextRun: => return @_job.nextInvocation() if @isRunning() getChannel: => return @_roomId toString: => alertStatus = if @isRunning() then "ON" else "OFF" alertNextRun = if @isRunning() then "\nNext check: #{@nextRun()}" else "" return "[#{alertStatus}] #{if @queue == null then 'Broker Stats' else @queue} - Checks #{@_type} every #{@_time} #{@_timeUnit} and notifies when #{@_compOp} #{@_compVal} on #{@server.url}#{alertNextRun}" serialize: => return [@server, @queue, @_type, @_time, @_timeUnit, @_compOp, @_compVal, @_roomId, @isRunning()] _alertFail: (value) => if (value == null) return false if (@_compOp == ">") return value > @_compVal else if (@_compOp == "<") return value < @_compVal else if (@_compOp == "=") return value == @_compVal else if (@_compOp == "<=") return value <= @_compVal else if (@_compOp == ">=") return value >= @_compVal else if (@_compOp == "!=" or @_compOp == "<>") return value != @_compVal return false _alertFailFurther: (value) => if (@_lastFailValue == null or value == null) return false if (@_compOp == ">") return value >= @_lastFailValue else if (@_compOp == "<") return value <= @_lastFailValue else if (@_compOp == "=") return value == @_lastFailValue else if (@_compOp == "<=") return value <= @_lastFailValue else if (@_compOp == ">=") return value >= @_lastFailValue else if (@_compOp == "!=" or @_compOp == "<>") return value != @_lastFailValue return false _handleAlert: => if @queue != null path = "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{@server.brokerName},destinationType=Queue,destinationName=#{@queue}" else path = "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{@server.brokerName}" @_reqFactory(@server, path, @_handleAlertResponse) _handleAlertSecondCheck: => if ((@_time > 30 and @_timeUnit.indexOf("seconds") != -1 or @_timeUnit.indexOf("seconds") == -1) and @_lastFailValue != null) self = @ setTimeout -> self._handleAlert() , 30000 _handleAlertResponse: (err, res, body, server) => if err console.log(err) @robot.messageRoom(@_roomId, "An error occurred while contacting Active MQ") return try content = JSON.parse(body) content = content.value currentFail = null firedSecondCheck = false # load value we need to check against valueToCheck = null if (@_type == @QUEUE_SIZE) valueToCheck = parseInt(content.QueueSize) else if (@_type == @CONSUMER_COUNT) valueToCheck = parseInt(content.ConsumerCount) else if (@_type == @STORE_PERCENT) valueToCheck = parseInt(content.StorePercentUsage) else if (@_type == @MEMORY_PERCENT) valueToCheck = parseInt(content.MemoryPercentUsage) # check if it fails our checks if (@_alertFail(valueToCheck)) currentFail = valueToCheck if (@_lastFailValue == null) @_lastFailValue = valueToCheck # wait 30 seconds and check the job again to see if its getting further from the alert threshold @_handleAlertSecondCheck() firedSecondCheck = true else # no failures, reset last failure value @_lastFailValue = null # only display message to user after the second check has been done, not on the same iteration as firing the second check and that it failed further away if (!firedSecondCheck and @_alertFailFurther(currentFail)) @_lastFailValue = null @robot.messageRoom(@_roomId, ":rotating_light: #{if @queue == null then 'Broker Stats' else @queue}'s #{@_type} is currently #{currentFail} and is getting further away from the alert value of #{@_compVal} :rotating_light:") catch error console.log(error) @robot.messageRoom(@_roomId, "An error occurred while contacting Active MQ") _handleQueueSizeAlert: (info) => class ActiveMQServerManager extends HubotMessenger _servers: [] constructor: (msg) -> super msg @_loadConfiguration() getServerByQueueName: (queueName) => @send "ERROR: Make sure to run a 'list' to update the queue cache" if not @serversHaveQueues() for server in @_servers return server if server.hasQueueByName(queueName) null getServerByURL: (url) => for server in @_servers return server if server.url == url null hasInitialized: => for server in @_servers return false if not server.hasInitialized() true listServers: => @_servers serversHaveQueues: => for server in @_servers return true if server.hasQueues() false servers: => for server in @_servers queues = server.getQueues() message = "- #{server.url}" for queue in queues message += "\n-- #{queue.destinationName}" @send message _loadConfiguration: => @_addServer process.env.HUBOT_ACTIVE_MQ_URL, process.env.HUBOT_ACTIVE_MQ_BROKER, process.env.HUBOT_ACTIVE_MQ_AUTH i = 1 while true url = process.env["HUBOT_ACTIVE_MQ_#{i}_URL"] broker = process.env["HUBOT_ACTIVE_MQ_#{i}_BROKER"] auth = process.env["HUBOT_ACTIVE_MQ_#{i}_AUTH"] if url and broker and auth then @_addServer(url, broker, auth) else return i += 1 _addServer: (url, broker, auth) => @_servers.push new ActiveMQServer(url, broker, auth) class HubotActiveMQPlugin extends HubotMessenger # Properties # ---------- _serverManager: null _querystring: null # stores queues, across all servers, in flat list to support 'describeById' _queueList: [] _params: null # stores a function to be called after the initial 'list' has completed _delayedFunction: null # stores how many queues have been described before sending the message _describedQueues = 0 _queuesToDescribe = 0 _describedQueuesResponse = null # stores the active alerts _alerts: [] # Init # ---- constructor: (msg, serverManager) -> super msg @_querystring = require 'querystring' @_serverManager = serverManager @setMessage msg _init: (delayedFunction) => return true if @_serverManager.hasInitialized() @reply "This is the first command run after startup. Please wait while we perform initialization..." @_delayedFunction = delayedFunction @list true false _initComplete: => if @_delayedFunction != null @send "Initialization Complete. Running your request..." setTimeout((() => @_delayedFunction() @_delayedFunction = null ), 1000) # Public API # ---------- listAlert: => # todo: remove this dependency on slack (if its even possible at this point :/) return if not @_init(@listAlert) web = new WebClient @robot.adapter.options.token # this mess of calls is due to Slack not giving user "channels" in the conversations call # todo: clean up with mess and use async to make it a little nicer looking web.conversations.list() .then((resp) => channels = resp.channels chanNames = {} for channel in channels chanNames[channel.id] = "#"+channel.name web.im.list() .then((resp) => dms = resp.ims web.users.list() .then((resp) => users = resp.members for dm in dms for user in users if (dm.user == user.id) chanNames[dm.id] = "@"+user.name resp = "" index = 1 for alertObj in @_alerts resp += "[#{index}] [#{chanNames[alertObj.getChannel()]}] #{alertObj.toString()}\n" index++ if (resp == "") resp = "It appears you don't have any alerts set up yet." @send resp ) .catch((err) => @send "There was an error communicating with the Slack API" console.log(err) ) ) .catch((err) => @send "There was an error communicating with the Slack API" console.log(err) ) ) .catch((err) => @send "There was an error communicating with the Slack API" console.log(err) ) stopAlert: => return if not @_init(@stopAlert) alertObj = @_getAlertById() if !alertObj @msg.send "I couldn't find that alert. Try `mq alert list` to get a list." return alertObj.stop() alertId = parseInt(@msg.match[1])-1 @robot.brain.get(STORE_KEY).alerts[alertId] = alertObj.serialize() @msg.send "This alert has been stopped" stopAllAlert: => return if not @_init(@stopAllAlert) for alertObj, alertId in @_alerts alertObj.stop() @robot.brain.get(STORE_KEY).alerts[alertId] = alertObj.serialize() @msg.send "All alerts have been stopped" startAlert: => return if not @_init(@startAlert) alertObj = @_getAlertById() if !alertObj @msg.send "I couldn't find that alert. Try `mq alert list` to get a list." return alertObj.start() alertId = parseInt(@msg.match[1])-1 @robot.brain.get(STORE_KEY).alerts[alertId] = alertObj.serialize() @msg.send "This alert has been started" startAllAlert: => return if not @_init(@startAllAlert) for alertObj, alertId in @_alerts alertObj.start() @robot.brain.get(STORE_KEY).alerts[alertId] = alertObj.serialize() @msg.send "All alerts have been started" deleteAlert: => return if not @_init(@deleteAlert) alertObj = @_getAlertById() if !alertObj @msg.send "I couldn't find that alert. Try `mq alert list` to get a list." return alertObj.stop() alertId = parseInt(@msg.match[1])-1 @_alerts.splice(alertId, 1) @robot.brain.get(STORE_KEY).alerts.splice(alertId, 1) @msg.send "This alert has been deleted" queueAlertSetup: => return if not @_init(@queueAlertSetup) queue = @_getQueue() server = @_serverManager.getServerByQueueName(queue) if !server @msg.send "I couldn't find any servers with a queue called #{@_getQueue()}. Try `mq servers` to get a list." return time = @msg.match[2] timeUnit = @msg.match[3] type = @msg.match[4] comparisonOp = @msg.match[5] comparisonVal = @msg.match[6] # todo: make this less slack dependent alertObj = new ActiveMQAlert(server, queue, @_requestFactorySingle, type, time, timeUnit, comparisonOp, comparisonVal, @robot, @msg.message.rawMessage.channel) @_alerts.push(alertObj) alertObj.start() @robot.brain.get(STORE_KEY).alerts.push(alertObj.serialize()) @msg.send "I'll try my best to check #{queue} every #{time} #{timeUnit} and report here if I see #{type} #{comparisonOp} #{comparisonVal}." statsAlertSetup: => return if not @_init(@statsAlertSetup) server = @_serverManager.getServerByURL(@_getQueue()) if !server @msg.send "I couldn't find any servers with a name called #{@_getQueue()}. Try `mq servers` to get a list." return time = @msg.match[2] timeUnit = @msg.match[3] type = @msg.match[4] comparisonOp = @msg.match[5] comparisonVal = @msg.match[6] # todo: make this less slack dependent alertObj = new ActiveMQAlert(server, null, @_requestFactorySingle, type, time, timeUnit, comparisonOp, comparisonVal, @robot, @msg.message.rawMessage.channel) @_alerts.push(alertObj) alertObj.start() @robot.brain.get(STORE_KEY).alerts.push(alertObj.serialize()) @msg.send "I'll try my best to check Broker Stats on #{server.url} every #{time} #{timeUnit} and report here if I see #{type} #{comparisonOp} #{comparisonVal}." describeAll: => return if not @_init(@describeAll) @_queuesToDescribe = 0 @_describedQueues = 0 @_describedQueuesResponse = '' for server in @_serverManager.listServers() @_queuesToDescribe += server.getQueues().length for server in @_serverManager.listServers() for queue in server.getQueues() @_requestFactorySingle server, "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{server.brokerName},destinationType=Queue,destinationName=#{queue.destinationName}", @_handleDescribeAll describeById: => return if not @_init(@describeById) queue = @_getQueueById() if not queue @reply "I couldn't find that queue. Try `mq list` to get a list." return @_setQueue queue @describe() describe: => return if not @_init(@describe) queue = @_getQueue(true) server = @_serverManager.getServerByQueueName(queue) if !server @msg.send "I couldn't find any servers with a queue called #{@_getQueue()}. Try `mq servers` to get a list." return @_requestFactorySingle server, "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{server.brokerName},destinationType=Queue,destinationName=#{queue}", @_handleDescribe list: (isInit = false) => for server in @_serverManager.listServers() @_requestFactorySingle server, "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{server.brokerName}", if isInit then @_handleListInit else @_handleList stats: => for server in @_serverManager.listServers() @_requestFactorySingle server, "api/jolokia/read/org.apache.activemq:type=Broker,brokerName=#{server.brokerName}", @_handleStats servers: => return if not @_init(@servers) @_serverManager.servers() setMessage: (message) => super message @_params = @msg.match[3] @_serverManager.setMessage message setRobot: (robot) => @robot = robot # Utility Methods # --------------- syncAlerts: => if !@robot.brain.get(STORE_KEY) @robot.brain.set(STORE_KEY, {"alerts":[]}) if (@robot.brain.get(STORE_KEY).alerts) for alertObj in @robot.brain.get(STORE_KEY).alerts @_alertFromBrain alertObj... _alertFromBrain: (server, queue, type, time, timeUnit, comparisonOp, comparisonVal, roomId, shouldBeRunning) => try alertObj = new ActiveMQAlert(server, queue, @_requestFactorySingle, type, time, timeUnit, comparisonOp, comparisonVal, @robot, roomId) @_alerts.push(alertObj) if (shouldBeRunning) alertObj.start() catch error console.log("error loading alert from brain") _addQueuesToQueuesList: (queues, server, outputStatus = false) => response = "" filter = new RegExp(@msg.match[2], 'i') for queue in queues # Add the queue to the @_queueList attributes = queue.objectName.split("org.apache.activemq:")[1].split(",") for attribute in attributes attributeName = attribute.substring(0, attribute.indexOf("=")) attributeValue = attribute.substring(attribute.indexOf("=")+1, attribute.length) queue[attributeName] = attributeValue server.addQueue(queue) index = @_queueList.indexOf(queue.destinationName) if index == -1 @_queueList.push queue.destinationName index = @_queueList.indexOf(queue.destinationName) if filter.test queue.destinationName response += "[#{index + 1}] #{queue.destinationName} on #{server.url}\n" @send response if outputStatus _configureRequest: (request, server = null) => defaultAuth = process.env.HUBOT_JENKINS_AUTH return if not server and not defaultAuth selectedAuth = if server then server.auth else defaultAuth request.header('Content-Length', 0) request _describeQueueAll: (queue) => response = "" response += "#{queue.Name} :: Queue Size:#{queue.QueueSize}, Consumers:#{queue.ConsumerCount}\n" response _describeQueue: (queue) => response = "" response += "Name: #{queue.Name}\n" response += "Paused: #{queue.Paused}\n" response += "Queue Size: #{queue.QueueSize}\n" response += "Consumer Count: #{queue.ConsumerCount}\n" response += "Memory Usage: #{queue.MemoryPercentUsage}%\n" response += "Cursor Usage: #{queue.CursorPercentUsage}%" response _describeStats: (stats) => response = "" response += "Broker: #{stats.BrokerName}\n" response += "Uptime: #{stats.Uptime}\n" response += "Memory Usage: #{stats.MemoryPercentUsage}%\n" response += "Store Usage: #{stats.StorePercentUsage}%" response _getQueue: (escape = false) => queue = @msg.match[1].trim() if escape then @_querystring.escape(queue) else queue # Switch the index with the queue name _getQueueById: => @_queueList[parseInt(@msg.match[1]) - 1] _getAlertById: => @_alerts[parseInt(@msg.match[1]) - 1] _requestFactorySingle: (server, endpoint, callback, method = "get") => user = server.auth.split(":") if server.url.indexOf('https') == 0 then http = 'https://' else http = 'http://' url = server.url.replace /^https?:\/\//, '' path = "#{http}#{user[0]}:#{user[1]}@#{url}/#{endpoint}" request = @robot.http(path) @_configureRequest request, server request[method]() ((err, res, body) -> callback(err, res, body, server)) _setQueue: (queue) => @msg.match[1] = queue # Handlers # -------- _handleDescribeAll: (err, res, body, server) => if err @send "It appears an error occurred while contacting your Active MQ instance. The error I received was #{err.code} from #{server.url}. Please verify that your Active MQ instance is configured properly." return try content = JSON.parse(body) @_describedQueuesResponse += @_describeQueueAll(content.value) @_describedQueues++ @send @_describedQueuesResponse if @_describedQueues == @_queuesToDescribe catch error @send error _handleDescribe: (err, res, body, server) => if err @send "It appears an error occurred while contacting your Active MQ instance. The error I received was #{err.code} from #{server.url}. Please verify that your Active MQ instance is configured properly." return try content = JSON.parse(body) @send @_describeQueue(content.value) catch error @send error _handleStats: (err, res, body, server) => if err @send "It appears an error occurred while contacting your Active MQ instance. The error I received was #{err.code} from #{server.url}. Please verify that your Active MQ instance is configured properly." return try content = JSON.parse(body) @send @_describeStats(content.value) catch error @send error _handleList: (err, res, body, server) => @_processListResult err, res, body, server _handleListInit: (err, res, body, server) => @_processListResult err, res, body, server, false _processListResult: (err, res, body, server, print = true) => if err @send "It appears an error occurred while contacting your Active MQ instance. The error I received was #{err.code} from #{server.url}. Please verify that your Active MQ instance is configured properly." return try content = JSON.parse(body) @_addQueuesToQueuesList content.value.Queues, server, print @_initComplete() if @_serverManager.hasInitialized() catch error @send error module.exports = (robot) -> console.log("robot startup!") # Factories # --------- _serverManager = null serverManagerFactory = (msg) -> _serverManager = new ActiveMQServerManager(msg) if not _serverManager _serverManager.setMessage msg _serverManager # Load alerts from file _plugin = new HubotActiveMQPlugin('', serverManagerFactory('')) _plugin.setRobot robot robot.brain.on 'loaded', -> console.log("Attempting to load alerts from file") _plugin.syncAlerts() pluginFactory = (msg) -> _plugin.setMessage msg _plugin.setRobot robot _plugin # Command Configuration # --------------------- robot.respond /m(?:q)? list( (.+))?/i, id: 'activemq.list', (msg) -> pluginFactory(msg).list() robot.respond /m(?:q)? queue stats/i, id: 'activemq.describeQueues', (msg) -> pluginFactory(msg).describeAll() robot.respond /m(?:q)? check (.*[^broker stats]) every (\d+) (days|hours|minutes|seconds) and alert me when (queue size|consumer count) is (>|<|=|<=|>=|!=|<>) (\d+)/i, id: 'activemq.queueAlertSetup', (msg) -> pluginFactory(msg).queueAlertSetup() robot.respond /m(?:q)? check broker stats on (.*) every (\d+) (days|hours|minutes|seconds) and alert me when (store percent|memory percent) is (>|<|=|<=|>=|!=|<>) (\d+)/i, id: 'activemq.statsAlertSetup', (msg) -> pluginFactory(msg).statsAlertSetup() robot.respond /m(?:q)? alert list/i, id: 'activemq.listAlert', (msg) -> pluginFactory(msg).listAlert() robot.respond /m(?:q)? alert stop (\d+)/i, id: 'activemq.stopAlert', (msg) -> pluginFactory(msg).stopAlert() robot.respond /m(?:q)? alert stop$/i, id: 'activemq.stopAllAlert', (msg) -> pluginFactory(msg).stopAllAlert() robot.respond /m(?:q)? alert start (\d+)/i, id: 'activemq.startAlert', (msg) -> pluginFactory(msg).startAlert() robot.respond /m(?:q)? alert start$/i, id: 'activemq.startAllAlert', (msg) -> pluginFactory(msg).startAllAlert() robot.respond /m(?:q)? alert delete (\d+)/i, id: 'activemq.deleteAlert', (msg) -> pluginFactory(msg).deleteAlert() robot.respond /m(?:q)? stats (.*)/i, id: 'activemq.describe', (msg) -> pluginFactory(msg).describe() robot.respond /m(?:q)? s (\d+)/i, id: 'activemq.d', (msg) -> pluginFactory(msg).describeById() robot.respond /m(?:q)? servers/i, id: 'activemq.servers', (msg) -> pluginFactory(msg).servers() robot.respond /m(?:q)? stats$/i, id: 'activemq.stats', (msg) -> pluginFactory(msg).stats() robot.activemq = queueAlertSetup: ((msg) -> pluginFactory(msg).queueAlertSetup()) statsAlertSetup: ((msg) -> pluginFactory(msg).statsAlertSetup()) listAlert: ((msg) -> pluginFactory(msg).listAlert()) startAlert: ((msg) -> pluginFactory(msg).startAlert()) stopAlert: ((msg) -> pluginFactory(msg).stopAlert()) deleteAlert: ((msg) -> pluginFactory(msg).deleteAlert()) describe: ((msg) -> pluginFactory(msg).describe()) list: ((msg) -> pluginFactory(msg).list()) servers: ((msg) -> pluginFactory(msg).servers()) stats: ((msg) -> pluginFactory(msg).stats())
[ { "context": "k) ->\n callback\n data: fullName: 'Chuck Norris'\n\n describe 'getDictionary', ->\n it 'should r", "end": 416, "score": 0.9998502731323242, "start": 404, "tag": "NAME", "value": "Chuck Norris" }, { "context": "tDict) ->\n expect(builtDict['{me}']).toBe 'Chuck Norris'\n done()\n @$rootScope.$apply()\n\n i", "end": 1495, "score": 0.9987051486968994, "start": 1483, "tag": "NAME", "value": "Chuck Norris" } ]
client/src/common/services/dynamic-fields.test.coffee
MollardMichael/scrumble
27
describe 'dynamicFields', -> beforeEach module 'Scrumble.common' beforeEach inject ( dynamicFields, $rootScope, sprintUtils, trelloUtils TrelloClient ) -> @dynamicFields = dynamicFields @$rootScope = $rootScope @sprintUtils = sprintUtils @trelloUtils = trelloUtils TrelloClient.get = -> then: (callback) -> callback data: fullName: 'Chuck Norris' describe 'getDictionary', -> it 'should return an object', -> expect(@dynamicFields.getAvailableFields()).toEqual jasmine.any(Array) it 'should returns an array of objects with uniq icons', -> fields = @dynamicFields.getAvailableFields() expect(_.uniq(fields, 'icon').length).toEqual fields.length describe 'render', -> it 'should replace sprint fields', (done) -> text = '{sprintNumber},{sprintGoal},{speed},{total}' sprint = number: 10 goal: 'Eat more carrots' resources: speed: 1.6666667 totalPoints: 24.199 @dynamicFields.ready sprint .then (builtDict) -> expect(builtDict['{sprintNumber}']).toBe sprint.number expect(builtDict['{sprintGoal}']).toBe sprint.goal expect(builtDict['{speed}']).toBe '1.7' expect(builtDict['{total}']).toBe '24.2' done() @$rootScope.$apply() it 'should replace {me}', (done) -> @dynamicFields.ready() .then (builtDict) -> expect(builtDict['{me}']).toBe 'Chuck Norris' done() @$rootScope.$apply() it 'should replace {toValidate} and {blocked}', (done) -> project = columnMapping: toValidate: 'A' blocked: 'B' points = 'A': 3.5 'B': 0 spyOn(@trelloUtils, 'getColumnPoints').and.callFake (id) -> points[id] @dynamicFields.ready(null, project) .then (builtDict) -> expect(builtDict['{toValidate}']).toBe 3.5 expect(builtDict['{blocked}']).toBe 0 done() @$rootScope.$apply() it 'should return undefined if {toValidate} and {blocked} are undefined', (done) -> @dynamicFields.ready() .then (builtDict) -> expect(builtDict['{toValidate}']).toBe undefined expect(builtDict['{blocked}']).toBe undefined done() @$rootScope.$apply() it 'should replace {done} and {gap}', (done) -> sprint = bdcData: [ done: 10 standard: 8 , done: 15.89 standard: 16 , done: null standard: 24 , done: null standard: 32 ] @dynamicFields.ready(sprint) .then (builtDict) -> expect(builtDict['{done}']).toBe '15.9' expect(builtDict['{gap}']).toBe '0.1' done() @$rootScope.$apply() it 'should replace several times', (done) -> text = '{sprintNumber},{sprintNumber}' result = @dynamicFields.render text, {'{sprintNumber}': 10} expect(result).toBe '10,10' done() it 'should replace {today#YYYY-MM-DD}', (done) -> text = 'On {today#YYYY-MM-DD} I will eat 10 carrots. Yes, on {today#YYYY-MM-DD}' expected = 'On ' + moment().format('YYYY-MM-DD') + ' I will eat 10 carrots. Yes, on ' + moment().format('YYYY-MM-DD') result = @dynamicFields.render text, {} expect(result).toBe expected done() it 'should replace {yesterday#YYYY-MM-DD}', (done) -> text = 'On {yesterday#YYYY-MM-DD} I will eat 10 carrots. Yes, on {yesterday#YYYY-MM-DD}' expected = 'On ' + moment().subtract(1, 'days').format('YYYY-MM-DD') + ' I will eat 10 carrots. Yes, on ' + moment().subtract(1, 'days').format('YYYY-MM-DD') result = @dynamicFields.render text, {} expect(result).toBe expected done() it 'should replace {ahead:value1 behind:value2}', (done) -> text = '{ahead:Avance behind:Retard}: nombre de points d\'avance: {ahead:bien behind:pas bien}' expectedAhead = 'Avance: nombre de points d\'avance: bien' expectedBehind = 'Retard: nombre de points d\'avance: pas bien' @sprintUtils.isAhead = -> true result = @dynamicFields.render text, {} expect(result).toBe expectedAhead @sprintUtils.isAhead = -> undefined result = @dynamicFields.render text, {} expect(result).toBe expectedAhead @sprintUtils.isAhead = -> false result = @dynamicFields.render text, {} expect(result).toBe expectedBehind done() it 'should not raise error with undefined input', (done) -> text = undefined result = @dynamicFields.render text, {} expect(result).toBe '' done()
47716
describe 'dynamicFields', -> beforeEach module 'Scrumble.common' beforeEach inject ( dynamicFields, $rootScope, sprintUtils, trelloUtils TrelloClient ) -> @dynamicFields = dynamicFields @$rootScope = $rootScope @sprintUtils = sprintUtils @trelloUtils = trelloUtils TrelloClient.get = -> then: (callback) -> callback data: fullName: '<NAME>' describe 'getDictionary', -> it 'should return an object', -> expect(@dynamicFields.getAvailableFields()).toEqual jasmine.any(Array) it 'should returns an array of objects with uniq icons', -> fields = @dynamicFields.getAvailableFields() expect(_.uniq(fields, 'icon').length).toEqual fields.length describe 'render', -> it 'should replace sprint fields', (done) -> text = '{sprintNumber},{sprintGoal},{speed},{total}' sprint = number: 10 goal: 'Eat more carrots' resources: speed: 1.6666667 totalPoints: 24.199 @dynamicFields.ready sprint .then (builtDict) -> expect(builtDict['{sprintNumber}']).toBe sprint.number expect(builtDict['{sprintGoal}']).toBe sprint.goal expect(builtDict['{speed}']).toBe '1.7' expect(builtDict['{total}']).toBe '24.2' done() @$rootScope.$apply() it 'should replace {me}', (done) -> @dynamicFields.ready() .then (builtDict) -> expect(builtDict['{me}']).toBe '<NAME>' done() @$rootScope.$apply() it 'should replace {toValidate} and {blocked}', (done) -> project = columnMapping: toValidate: 'A' blocked: 'B' points = 'A': 3.5 'B': 0 spyOn(@trelloUtils, 'getColumnPoints').and.callFake (id) -> points[id] @dynamicFields.ready(null, project) .then (builtDict) -> expect(builtDict['{toValidate}']).toBe 3.5 expect(builtDict['{blocked}']).toBe 0 done() @$rootScope.$apply() it 'should return undefined if {toValidate} and {blocked} are undefined', (done) -> @dynamicFields.ready() .then (builtDict) -> expect(builtDict['{toValidate}']).toBe undefined expect(builtDict['{blocked}']).toBe undefined done() @$rootScope.$apply() it 'should replace {done} and {gap}', (done) -> sprint = bdcData: [ done: 10 standard: 8 , done: 15.89 standard: 16 , done: null standard: 24 , done: null standard: 32 ] @dynamicFields.ready(sprint) .then (builtDict) -> expect(builtDict['{done}']).toBe '15.9' expect(builtDict['{gap}']).toBe '0.1' done() @$rootScope.$apply() it 'should replace several times', (done) -> text = '{sprintNumber},{sprintNumber}' result = @dynamicFields.render text, {'{sprintNumber}': 10} expect(result).toBe '10,10' done() it 'should replace {today#YYYY-MM-DD}', (done) -> text = 'On {today#YYYY-MM-DD} I will eat 10 carrots. Yes, on {today#YYYY-MM-DD}' expected = 'On ' + moment().format('YYYY-MM-DD') + ' I will eat 10 carrots. Yes, on ' + moment().format('YYYY-MM-DD') result = @dynamicFields.render text, {} expect(result).toBe expected done() it 'should replace {yesterday#YYYY-MM-DD}', (done) -> text = 'On {yesterday#YYYY-MM-DD} I will eat 10 carrots. Yes, on {yesterday#YYYY-MM-DD}' expected = 'On ' + moment().subtract(1, 'days').format('YYYY-MM-DD') + ' I will eat 10 carrots. Yes, on ' + moment().subtract(1, 'days').format('YYYY-MM-DD') result = @dynamicFields.render text, {} expect(result).toBe expected done() it 'should replace {ahead:value1 behind:value2}', (done) -> text = '{ahead:Avance behind:Retard}: nombre de points d\'avance: {ahead:bien behind:pas bien}' expectedAhead = 'Avance: nombre de points d\'avance: bien' expectedBehind = 'Retard: nombre de points d\'avance: pas bien' @sprintUtils.isAhead = -> true result = @dynamicFields.render text, {} expect(result).toBe expectedAhead @sprintUtils.isAhead = -> undefined result = @dynamicFields.render text, {} expect(result).toBe expectedAhead @sprintUtils.isAhead = -> false result = @dynamicFields.render text, {} expect(result).toBe expectedBehind done() it 'should not raise error with undefined input', (done) -> text = undefined result = @dynamicFields.render text, {} expect(result).toBe '' done()
true
describe 'dynamicFields', -> beforeEach module 'Scrumble.common' beforeEach inject ( dynamicFields, $rootScope, sprintUtils, trelloUtils TrelloClient ) -> @dynamicFields = dynamicFields @$rootScope = $rootScope @sprintUtils = sprintUtils @trelloUtils = trelloUtils TrelloClient.get = -> then: (callback) -> callback data: fullName: 'PI:NAME:<NAME>END_PI' describe 'getDictionary', -> it 'should return an object', -> expect(@dynamicFields.getAvailableFields()).toEqual jasmine.any(Array) it 'should returns an array of objects with uniq icons', -> fields = @dynamicFields.getAvailableFields() expect(_.uniq(fields, 'icon').length).toEqual fields.length describe 'render', -> it 'should replace sprint fields', (done) -> text = '{sprintNumber},{sprintGoal},{speed},{total}' sprint = number: 10 goal: 'Eat more carrots' resources: speed: 1.6666667 totalPoints: 24.199 @dynamicFields.ready sprint .then (builtDict) -> expect(builtDict['{sprintNumber}']).toBe sprint.number expect(builtDict['{sprintGoal}']).toBe sprint.goal expect(builtDict['{speed}']).toBe '1.7' expect(builtDict['{total}']).toBe '24.2' done() @$rootScope.$apply() it 'should replace {me}', (done) -> @dynamicFields.ready() .then (builtDict) -> expect(builtDict['{me}']).toBe 'PI:NAME:<NAME>END_PI' done() @$rootScope.$apply() it 'should replace {toValidate} and {blocked}', (done) -> project = columnMapping: toValidate: 'A' blocked: 'B' points = 'A': 3.5 'B': 0 spyOn(@trelloUtils, 'getColumnPoints').and.callFake (id) -> points[id] @dynamicFields.ready(null, project) .then (builtDict) -> expect(builtDict['{toValidate}']).toBe 3.5 expect(builtDict['{blocked}']).toBe 0 done() @$rootScope.$apply() it 'should return undefined if {toValidate} and {blocked} are undefined', (done) -> @dynamicFields.ready() .then (builtDict) -> expect(builtDict['{toValidate}']).toBe undefined expect(builtDict['{blocked}']).toBe undefined done() @$rootScope.$apply() it 'should replace {done} and {gap}', (done) -> sprint = bdcData: [ done: 10 standard: 8 , done: 15.89 standard: 16 , done: null standard: 24 , done: null standard: 32 ] @dynamicFields.ready(sprint) .then (builtDict) -> expect(builtDict['{done}']).toBe '15.9' expect(builtDict['{gap}']).toBe '0.1' done() @$rootScope.$apply() it 'should replace several times', (done) -> text = '{sprintNumber},{sprintNumber}' result = @dynamicFields.render text, {'{sprintNumber}': 10} expect(result).toBe '10,10' done() it 'should replace {today#YYYY-MM-DD}', (done) -> text = 'On {today#YYYY-MM-DD} I will eat 10 carrots. Yes, on {today#YYYY-MM-DD}' expected = 'On ' + moment().format('YYYY-MM-DD') + ' I will eat 10 carrots. Yes, on ' + moment().format('YYYY-MM-DD') result = @dynamicFields.render text, {} expect(result).toBe expected done() it 'should replace {yesterday#YYYY-MM-DD}', (done) -> text = 'On {yesterday#YYYY-MM-DD} I will eat 10 carrots. Yes, on {yesterday#YYYY-MM-DD}' expected = 'On ' + moment().subtract(1, 'days').format('YYYY-MM-DD') + ' I will eat 10 carrots. Yes, on ' + moment().subtract(1, 'days').format('YYYY-MM-DD') result = @dynamicFields.render text, {} expect(result).toBe expected done() it 'should replace {ahead:value1 behind:value2}', (done) -> text = '{ahead:Avance behind:Retard}: nombre de points d\'avance: {ahead:bien behind:pas bien}' expectedAhead = 'Avance: nombre de points d\'avance: bien' expectedBehind = 'Retard: nombre de points d\'avance: pas bien' @sprintUtils.isAhead = -> true result = @dynamicFields.render text, {} expect(result).toBe expectedAhead @sprintUtils.isAhead = -> undefined result = @dynamicFields.render text, {} expect(result).toBe expectedAhead @sprintUtils.isAhead = -> false result = @dynamicFields.render text, {} expect(result).toBe expectedBehind done() it 'should not raise error with undefined input', (done) -> text = undefined result = @dynamicFields.render text, {} expect(result).toBe '' done()
[ { "context": "to the user via the jQuery Noty plugin\n#\n# @author Marten Seemann <martenseemann@gmail.com>\n# @see http://needim.gi", "end": 98, "score": 0.9998373985290527, "start": 84, "tag": "NAME", "value": "Marten Seemann" }, { "context": "he jQuery Noty plugin\n#\n# @author Marten Seemann <martenseemann@gmail.com>\n# @see http://needim.github.com/noty/\n\n\"use stri", "end": 123, "score": 0.9999330639839172, "start": 100, "tag": "EMAIL", "value": "martenseemann@gmail.com" } ]
assets/js/src/notification_handler.coffee
marten-seemann/oxid-lager-manager
0
# handle notifications displayed to the user via the jQuery Noty plugin # # @author Marten Seemann <martenseemann@gmail.com> # @see http://needim.github.com/noty/ "use strict" class window.NotificationHandler # Constructor # # will instantaneously display the loading notification, if neccessary # # @param [Boolean] loading_state should category_tree and article_table be assumed to be loading at the beginning constructor: ( )-> showLoading: (text) -> noty text: text type: "alert" timeout: 5000 hideLoading: -> $.noty.closeAll() # show a success box (green background color) # # @text [String] the text to be displayed showSuccess: (text) -> noty text: text type: "success" timeout: 1800 # show an error box (red background color) # # will be displayed for 8000 ms (that is much longer than a success box is displayed) # # @param [String] text the text to be displayed # @param [Integer] timeot how long should the notification be displayed showError: (text, timeout = 8000 ) -> noty text: text type: "error" timeout: timeout
46615
# handle notifications displayed to the user via the jQuery Noty plugin # # @author <NAME> <<EMAIL>> # @see http://needim.github.com/noty/ "use strict" class window.NotificationHandler # Constructor # # will instantaneously display the loading notification, if neccessary # # @param [Boolean] loading_state should category_tree and article_table be assumed to be loading at the beginning constructor: ( )-> showLoading: (text) -> noty text: text type: "alert" timeout: 5000 hideLoading: -> $.noty.closeAll() # show a success box (green background color) # # @text [String] the text to be displayed showSuccess: (text) -> noty text: text type: "success" timeout: 1800 # show an error box (red background color) # # will be displayed for 8000 ms (that is much longer than a success box is displayed) # # @param [String] text the text to be displayed # @param [Integer] timeot how long should the notification be displayed showError: (text, timeout = 8000 ) -> noty text: text type: "error" timeout: timeout
true
# handle notifications displayed to the user via the jQuery Noty plugin # # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # @see http://needim.github.com/noty/ "use strict" class window.NotificationHandler # Constructor # # will instantaneously display the loading notification, if neccessary # # @param [Boolean] loading_state should category_tree and article_table be assumed to be loading at the beginning constructor: ( )-> showLoading: (text) -> noty text: text type: "alert" timeout: 5000 hideLoading: -> $.noty.closeAll() # show a success box (green background color) # # @text [String] the text to be displayed showSuccess: (text) -> noty text: text type: "success" timeout: 1800 # show an error box (red background color) # # will be displayed for 8000 ms (that is much longer than a success box is displayed) # # @param [String] text the text to be displayed # @param [Integer] timeot how long should the notification be displayed showError: (text, timeout = 8000 ) -> noty text: text type: "error" timeout: timeout
[ { "context": "rent time as seed.\n constructor: (@seed) ->\n # Knuth and Lewis' improvements to Park and Miller's LCPR", "end": 213, "score": 0.6707061529159546, "start": 208, "tag": "NAME", "value": "Knuth" }, { "context": " seed.\n constructor: (@seed) ->\n # Knuth and Lewis' improvements to Park and Miller's LCPRNG\n @mu", "end": 223, "score": 0.878280758857727, "start": 219, "tag": "NAME", "value": "ewis" } ]
app/lib/world/rand.coffee
gugumiao/codecombat
2
# http://coffeescriptcookbook.com/chapters/math/generating-predictable-random-numbers class Rand @className: 'Rand' # If created without a seed, uses current time as seed. constructor: (@seed) -> # Knuth and Lewis' improvements to Park and Miller's LCPRNG @multiplier = 1664525 @modulo = 4294967296 # 2**32-1 @offset = 1013904223 unless @seed? and 0 <= @seed < @modulo @seed = (new Date().valueOf() * new Date().getMilliseconds()) % @modulo # sets new seed value, even handling negative numbers setSeed: (seed) -> @seed = ((seed % @modulo) + @modulo) % @modulo # return a random integer 0 <= n < @modulo randn: => # new_seed = (a * seed + c) % m @seed = (@multiplier * @seed + @offset) % @modulo # return a random float 0 <= f < 1.0 randf: => @randn() / @modulo # return a random int 0 <= f < n rand: (n) => Math.floor @randf() * n # return a random int min <= f < max rand2: (min, max) => min + @rand max - min # return a random float min <= f < max randf2: (min, max) => min + @randf() * (max - min) # return a random float within range around x randfRange: (x, range) => x + (-0.5 + @randf()) * range # shuffle array in place, and also return it shuffle: (arr) => return arr unless arr.length > 2 for i in [arr.length-1 .. 1] j = Math.floor @randf() * (i + 1) t = arr[j] arr[j] = arr[i] arr[i] = t arr choice: (arr) => return arr[@rand arr.length] module.exports = Rand
10094
# http://coffeescriptcookbook.com/chapters/math/generating-predictable-random-numbers class Rand @className: 'Rand' # If created without a seed, uses current time as seed. constructor: (@seed) -> # <NAME> and L<NAME>' improvements to Park and Miller's LCPRNG @multiplier = 1664525 @modulo = 4294967296 # 2**32-1 @offset = 1013904223 unless @seed? and 0 <= @seed < @modulo @seed = (new Date().valueOf() * new Date().getMilliseconds()) % @modulo # sets new seed value, even handling negative numbers setSeed: (seed) -> @seed = ((seed % @modulo) + @modulo) % @modulo # return a random integer 0 <= n < @modulo randn: => # new_seed = (a * seed + c) % m @seed = (@multiplier * @seed + @offset) % @modulo # return a random float 0 <= f < 1.0 randf: => @randn() / @modulo # return a random int 0 <= f < n rand: (n) => Math.floor @randf() * n # return a random int min <= f < max rand2: (min, max) => min + @rand max - min # return a random float min <= f < max randf2: (min, max) => min + @randf() * (max - min) # return a random float within range around x randfRange: (x, range) => x + (-0.5 + @randf()) * range # shuffle array in place, and also return it shuffle: (arr) => return arr unless arr.length > 2 for i in [arr.length-1 .. 1] j = Math.floor @randf() * (i + 1) t = arr[j] arr[j] = arr[i] arr[i] = t arr choice: (arr) => return arr[@rand arr.length] module.exports = Rand
true
# http://coffeescriptcookbook.com/chapters/math/generating-predictable-random-numbers class Rand @className: 'Rand' # If created without a seed, uses current time as seed. constructor: (@seed) -> # PI:NAME:<NAME>END_PI and LPI:NAME:<NAME>END_PI' improvements to Park and Miller's LCPRNG @multiplier = 1664525 @modulo = 4294967296 # 2**32-1 @offset = 1013904223 unless @seed? and 0 <= @seed < @modulo @seed = (new Date().valueOf() * new Date().getMilliseconds()) % @modulo # sets new seed value, even handling negative numbers setSeed: (seed) -> @seed = ((seed % @modulo) + @modulo) % @modulo # return a random integer 0 <= n < @modulo randn: => # new_seed = (a * seed + c) % m @seed = (@multiplier * @seed + @offset) % @modulo # return a random float 0 <= f < 1.0 randf: => @randn() / @modulo # return a random int 0 <= f < n rand: (n) => Math.floor @randf() * n # return a random int min <= f < max rand2: (min, max) => min + @rand max - min # return a random float min <= f < max randf2: (min, max) => min + @randf() * (max - min) # return a random float within range around x randfRange: (x, range) => x + (-0.5 + @randf()) * range # shuffle array in place, and also return it shuffle: (arr) => return arr unless arr.length > 2 for i in [arr.length-1 .. 1] j = Math.floor @randf() * (i + 1) t = arr[j] arr[j] = arr[i] arr[i] = t arr choice: (arr) => return arr[@rand arr.length] module.exports = Rand
[ { "context": "e to another object in the PDF object heirarchy\nBy Devon Govett\n###\n\nzlib = require 'zlib'\nsetImmediate = setImme", "end": 103, "score": 0.9997290372848511, "start": 91, "tag": "NAME", "value": "Devon Govett" } ]
lib/reference.coffee
goodeggs/pdfkit
0
### PDFReference - represents a reference to another object in the PDF object heirarchy By Devon Govett ### zlib = require 'zlib' setImmediate = setImmediate ? process.nextTick # backfill for node <0.10 class PDFReference constructor: (@id, @data = {}) -> @gen = 0 @stream = null @finalizedStream = null object: (compress, fn) -> unless @finalizedStream? return @finalize compress, => @object compress, fn out = ["#{@id} #{@gen} obj"] out.push PDFObject.convert(@data) if @stream out.push "stream" out.push @finalizedStream out.push "endstream" out.push "endobj" fn out.join '\n' add: (s) -> @stream ?= [] @stream.push if Buffer.isBuffer(s) then s.toString('binary') else s finalize: (compress = false, fn) -> # cache the finalized stream if @stream data = @stream.join '\n' if compress and not @data.Filter # create a byte array instead of passing a string to the Buffer # fixes a weird unicode bug. data = new Buffer(data.charCodeAt(i) for i in [0...data.length]) zlib.deflate data, (err, compressedData) => throw err if err @finalizedStream = compressedData.toString 'binary' @data.Filter = 'FlateDecode' @data.Length = @finalizedStream.length fn() else @finalizedStream = data @data.Length = @finalizedStream.length setImmediate fn else @finalizedStream = '' setImmediate fn toString: -> "#{@id} #{@gen} R" module.exports = PDFReference PDFObject = require './object'
97832
### PDFReference - represents a reference to another object in the PDF object heirarchy By <NAME> ### zlib = require 'zlib' setImmediate = setImmediate ? process.nextTick # backfill for node <0.10 class PDFReference constructor: (@id, @data = {}) -> @gen = 0 @stream = null @finalizedStream = null object: (compress, fn) -> unless @finalizedStream? return @finalize compress, => @object compress, fn out = ["#{@id} #{@gen} obj"] out.push PDFObject.convert(@data) if @stream out.push "stream" out.push @finalizedStream out.push "endstream" out.push "endobj" fn out.join '\n' add: (s) -> @stream ?= [] @stream.push if Buffer.isBuffer(s) then s.toString('binary') else s finalize: (compress = false, fn) -> # cache the finalized stream if @stream data = @stream.join '\n' if compress and not @data.Filter # create a byte array instead of passing a string to the Buffer # fixes a weird unicode bug. data = new Buffer(data.charCodeAt(i) for i in [0...data.length]) zlib.deflate data, (err, compressedData) => throw err if err @finalizedStream = compressedData.toString 'binary' @data.Filter = 'FlateDecode' @data.Length = @finalizedStream.length fn() else @finalizedStream = data @data.Length = @finalizedStream.length setImmediate fn else @finalizedStream = '' setImmediate fn toString: -> "#{@id} #{@gen} R" module.exports = PDFReference PDFObject = require './object'
true
### PDFReference - represents a reference to another object in the PDF object heirarchy By PI:NAME:<NAME>END_PI ### zlib = require 'zlib' setImmediate = setImmediate ? process.nextTick # backfill for node <0.10 class PDFReference constructor: (@id, @data = {}) -> @gen = 0 @stream = null @finalizedStream = null object: (compress, fn) -> unless @finalizedStream? return @finalize compress, => @object compress, fn out = ["#{@id} #{@gen} obj"] out.push PDFObject.convert(@data) if @stream out.push "stream" out.push @finalizedStream out.push "endstream" out.push "endobj" fn out.join '\n' add: (s) -> @stream ?= [] @stream.push if Buffer.isBuffer(s) then s.toString('binary') else s finalize: (compress = false, fn) -> # cache the finalized stream if @stream data = @stream.join '\n' if compress and not @data.Filter # create a byte array instead of passing a string to the Buffer # fixes a weird unicode bug. data = new Buffer(data.charCodeAt(i) for i in [0...data.length]) zlib.deflate data, (err, compressedData) => throw err if err @finalizedStream = compressedData.toString 'binary' @data.Filter = 'FlateDecode' @data.Length = @finalizedStream.length fn() else @finalizedStream = data @data.Length = @finalizedStream.length setImmediate fn else @finalizedStream = '' setImmediate fn toString: -> "#{@id} #{@gen} R" module.exports = PDFReference PDFObject = require './object'
[ { "context": "ow: 1\n id: 'sdlkfj'\n name: 'calico'\n ,\n flow: 2\n id: ", "end": 1336, "score": 0.9104750156402588, "start": 1330, "tag": "NAME", "value": "calico" }, { "context": "low: 2\n id: 'ssdf' \n name: 'tabby'\n ]\n @getTriggers.resolve @trigge", "end": 1418, "score": 0.9680101871490479, "start": 1413, "tag": "NAME", "value": "tabby" }, { "context": "', \n $cookies: {uuid: 'ascension', token: 'what goes up, must come DEAD'}\n $location: @location\n DeviceServ", "end": 3540, "score": 0.9877196550369263, "start": 3512, "tag": "PASSWORD", "value": "what goes up, must come DEAD" }, { "context": ", \n $cookies: {uuid: 'sex-injury', token: 'Awwww yeeeaahhurkghf'}\n $location: @location\n DeviceServ", "end": 4095, "score": 0.9621453881263733, "start": 4075, "tag": "PASSWORD", "value": "Awwww yeeeaahhurkghf" } ]
test/home/home-controller-spec.coffee
octoblu/blu-web-room
1
describe 'HomeController', -> beforeEach -> module 'blu' inject ($controller, $q, $rootScope) -> @q = $q @getTriggers = @q.defer() @triggerPromise = @q.defer() @rootScope = $rootScope @location = path: sinon.stub() @triggerService = getTriggers: sinon.stub().returns(@getTriggers.promise) trigger: sinon.stub().returns(@triggerPromise) @deviceService = getDevice: sinon.stub().returns $q.when(owner: 'owner-uuid') @controller = $controller describe 'when the user is authenticated (valid uuid | token)', -> beforeEach -> @sut = @controller('HomeController', { TriggerService : @triggerService, DeviceService : @deviceService, $cookies: {uuid: 'uuid', token: 'token'}, $location: @location }) @rootScope.$digest() it 'should call the deviceService.getDevice', -> expect(@deviceService.getDevice).to.have.been.calledWith 'uuid', 'token' it 'should call the triggerService.getTriggers', -> expect(@triggerService.getTriggers).to.have.been.calledWith 'uuid', 'token', 'owner-uuid' describe 'when triggerService.getTriggers resolves with a list of triggers', -> beforeEach -> @triggers = [ flow: 1 id: 'sdlkfj' name: 'calico' , flow: 2 id: 'ssdf' name: 'tabby' ] @getTriggers.resolve @triggers it 'should set a triggers property with the list of triggers', -> @rootScope.$digest() expect(@sut.triggers).to.deep.equal @triggers it 'should set triggersLoaded to true', -> @rootScope.$digest() expect(@sut.triggersLoaded).to.be.true describe 'when triggerService.getTriggers resolves with no triggers', -> beforeEach -> @triggers = [] @noFlows = true @getTriggers.resolve @triggers it 'should set the noFlows property to true', -> @rootScope.$digest() expect(@sut.noFlows).to.be.true describe 'when triggerService.getTriggers rejects the promise', -> beforeEach -> @getTriggers.reject new Error 'ERROR WILL ROBINSON ERROR' it 'should have an errorMsg property', -> @rootScope.$digest() expect(@sut.errorMessage).to.equal 'ERROR WILL ROBINSON ERROR' it 'should not redirect to login property', -> @rootScope.$digest() expect(@location.path).not.to.have.been.called describe 'when the user does not have a valid uuid', -> beforeEach -> @sut = @controller('HomeController', { TriggerService : @triggerService, $cookies: {}, $location: @location }) it 'should redirect the user to the register page', -> expect(@location.path).to.have.been.calledWith '/' describe 'when the user has a valid uuid but does not have a token', -> beforeEach -> @sut = @controller 'HomeController', $cookies: {uuid: 1, token: undefined} $location: @location DeviceService: {} TriggerService: {} it 'should redirect the user to the register page', -> expect(@location.path).to.have.been.calledWith '/1/login' describe 'when deviceService rejects on getDevice', -> beforeEach -> @deviceService = getDevice: sinon.stub().returns @q.reject(new Error('Unauthorized')) @sut = @controller 'HomeController', $cookies: {uuid: 'ascension', token: 'what goes up, must come DEAD'} $location: @location DeviceService: @deviceService TriggerService: {} @rootScope.$digest() it 'should redirect the user to the register page', -> expect(@location.path).to.have.been.calledWith '/ascension/login' describe 'when deviceService rejects a different device on getDevice', -> beforeEach -> @deviceService = getDevice: sinon.stub().returns @q.reject(new Error('Unauthorized')) @sut = @controller 'HomeController', $cookies: {uuid: 'sex-injury', token: 'Awwww yeeeaahhurkghf'} $location: @location DeviceService: @deviceService TriggerService: {} @rootScope.$digest() it 'should redirect the user to the register page', -> expect(@location.path).to.have.been.calledWith '/sex-injury/login'
95825
describe 'HomeController', -> beforeEach -> module 'blu' inject ($controller, $q, $rootScope) -> @q = $q @getTriggers = @q.defer() @triggerPromise = @q.defer() @rootScope = $rootScope @location = path: sinon.stub() @triggerService = getTriggers: sinon.stub().returns(@getTriggers.promise) trigger: sinon.stub().returns(@triggerPromise) @deviceService = getDevice: sinon.stub().returns $q.when(owner: 'owner-uuid') @controller = $controller describe 'when the user is authenticated (valid uuid | token)', -> beforeEach -> @sut = @controller('HomeController', { TriggerService : @triggerService, DeviceService : @deviceService, $cookies: {uuid: 'uuid', token: 'token'}, $location: @location }) @rootScope.$digest() it 'should call the deviceService.getDevice', -> expect(@deviceService.getDevice).to.have.been.calledWith 'uuid', 'token' it 'should call the triggerService.getTriggers', -> expect(@triggerService.getTriggers).to.have.been.calledWith 'uuid', 'token', 'owner-uuid' describe 'when triggerService.getTriggers resolves with a list of triggers', -> beforeEach -> @triggers = [ flow: 1 id: 'sdlkfj' name: '<NAME>' , flow: 2 id: 'ssdf' name: '<NAME>' ] @getTriggers.resolve @triggers it 'should set a triggers property with the list of triggers', -> @rootScope.$digest() expect(@sut.triggers).to.deep.equal @triggers it 'should set triggersLoaded to true', -> @rootScope.$digest() expect(@sut.triggersLoaded).to.be.true describe 'when triggerService.getTriggers resolves with no triggers', -> beforeEach -> @triggers = [] @noFlows = true @getTriggers.resolve @triggers it 'should set the noFlows property to true', -> @rootScope.$digest() expect(@sut.noFlows).to.be.true describe 'when triggerService.getTriggers rejects the promise', -> beforeEach -> @getTriggers.reject new Error 'ERROR WILL ROBINSON ERROR' it 'should have an errorMsg property', -> @rootScope.$digest() expect(@sut.errorMessage).to.equal 'ERROR WILL ROBINSON ERROR' it 'should not redirect to login property', -> @rootScope.$digest() expect(@location.path).not.to.have.been.called describe 'when the user does not have a valid uuid', -> beforeEach -> @sut = @controller('HomeController', { TriggerService : @triggerService, $cookies: {}, $location: @location }) it 'should redirect the user to the register page', -> expect(@location.path).to.have.been.calledWith '/' describe 'when the user has a valid uuid but does not have a token', -> beforeEach -> @sut = @controller 'HomeController', $cookies: {uuid: 1, token: undefined} $location: @location DeviceService: {} TriggerService: {} it 'should redirect the user to the register page', -> expect(@location.path).to.have.been.calledWith '/1/login' describe 'when deviceService rejects on getDevice', -> beforeEach -> @deviceService = getDevice: sinon.stub().returns @q.reject(new Error('Unauthorized')) @sut = @controller 'HomeController', $cookies: {uuid: 'ascension', token: '<PASSWORD>'} $location: @location DeviceService: @deviceService TriggerService: {} @rootScope.$digest() it 'should redirect the user to the register page', -> expect(@location.path).to.have.been.calledWith '/ascension/login' describe 'when deviceService rejects a different device on getDevice', -> beforeEach -> @deviceService = getDevice: sinon.stub().returns @q.reject(new Error('Unauthorized')) @sut = @controller 'HomeController', $cookies: {uuid: 'sex-injury', token: '<PASSWORD>'} $location: @location DeviceService: @deviceService TriggerService: {} @rootScope.$digest() it 'should redirect the user to the register page', -> expect(@location.path).to.have.been.calledWith '/sex-injury/login'
true
describe 'HomeController', -> beforeEach -> module 'blu' inject ($controller, $q, $rootScope) -> @q = $q @getTriggers = @q.defer() @triggerPromise = @q.defer() @rootScope = $rootScope @location = path: sinon.stub() @triggerService = getTriggers: sinon.stub().returns(@getTriggers.promise) trigger: sinon.stub().returns(@triggerPromise) @deviceService = getDevice: sinon.stub().returns $q.when(owner: 'owner-uuid') @controller = $controller describe 'when the user is authenticated (valid uuid | token)', -> beforeEach -> @sut = @controller('HomeController', { TriggerService : @triggerService, DeviceService : @deviceService, $cookies: {uuid: 'uuid', token: 'token'}, $location: @location }) @rootScope.$digest() it 'should call the deviceService.getDevice', -> expect(@deviceService.getDevice).to.have.been.calledWith 'uuid', 'token' it 'should call the triggerService.getTriggers', -> expect(@triggerService.getTriggers).to.have.been.calledWith 'uuid', 'token', 'owner-uuid' describe 'when triggerService.getTriggers resolves with a list of triggers', -> beforeEach -> @triggers = [ flow: 1 id: 'sdlkfj' name: 'PI:NAME:<NAME>END_PI' , flow: 2 id: 'ssdf' name: 'PI:NAME:<NAME>END_PI' ] @getTriggers.resolve @triggers it 'should set a triggers property with the list of triggers', -> @rootScope.$digest() expect(@sut.triggers).to.deep.equal @triggers it 'should set triggersLoaded to true', -> @rootScope.$digest() expect(@sut.triggersLoaded).to.be.true describe 'when triggerService.getTriggers resolves with no triggers', -> beforeEach -> @triggers = [] @noFlows = true @getTriggers.resolve @triggers it 'should set the noFlows property to true', -> @rootScope.$digest() expect(@sut.noFlows).to.be.true describe 'when triggerService.getTriggers rejects the promise', -> beforeEach -> @getTriggers.reject new Error 'ERROR WILL ROBINSON ERROR' it 'should have an errorMsg property', -> @rootScope.$digest() expect(@sut.errorMessage).to.equal 'ERROR WILL ROBINSON ERROR' it 'should not redirect to login property', -> @rootScope.$digest() expect(@location.path).not.to.have.been.called describe 'when the user does not have a valid uuid', -> beforeEach -> @sut = @controller('HomeController', { TriggerService : @triggerService, $cookies: {}, $location: @location }) it 'should redirect the user to the register page', -> expect(@location.path).to.have.been.calledWith '/' describe 'when the user has a valid uuid but does not have a token', -> beforeEach -> @sut = @controller 'HomeController', $cookies: {uuid: 1, token: undefined} $location: @location DeviceService: {} TriggerService: {} it 'should redirect the user to the register page', -> expect(@location.path).to.have.been.calledWith '/1/login' describe 'when deviceService rejects on getDevice', -> beforeEach -> @deviceService = getDevice: sinon.stub().returns @q.reject(new Error('Unauthorized')) @sut = @controller 'HomeController', $cookies: {uuid: 'ascension', token: 'PI:PASSWORD:<PASSWORD>END_PI'} $location: @location DeviceService: @deviceService TriggerService: {} @rootScope.$digest() it 'should redirect the user to the register page', -> expect(@location.path).to.have.been.calledWith '/ascension/login' describe 'when deviceService rejects a different device on getDevice', -> beforeEach -> @deviceService = getDevice: sinon.stub().returns @q.reject(new Error('Unauthorized')) @sut = @controller 'HomeController', $cookies: {uuid: 'sex-injury', token: 'PI:PASSWORD:<PASSWORD>END_PI'} $location: @location DeviceService: @deviceService TriggerService: {} @rootScope.$digest() it 'should redirect the user to the register page', -> expect(@location.path).to.have.been.calledWith '/sex-injury/login'
[ { "context": "Slack = require('slack-client')\ntoken = 'xoxb-5042459146-mKyVHVNRYWRl80BxTb3Kqftb'\nslack = new Slack(token, true, true)\n\nmakeMentio", "end": 81, "score": 0.9993857145309448, "start": 41, "tag": "KEY", "value": "xoxb-5042459146-mKyVHVNRYWRl80BxTb3Kqftb" } ]
src/slackbot.coffee
mt5225/plmisc
0
Slack = require('slack-client') token = 'xoxb-5042459146-mKyVHVNRYWRl80BxTb3Kqftb' slack = new Slack(token, true, true) makeMention = (userId) -> '<@' + userId + '>' isDirect = (userId, messageText) -> userTag = makeMention(userId) messageText and messageText.length >= userTag.length and messageText.substr(0, userTag.length) == userTag # --- # generated by js2coffee 2.0.4 slack.on 'open', -> channels = Object.keys(slack.channels).map((k) -> slack.channels[k] ).filter((c) -> c.is_member ).map((c) -> c.name ) groups = Object.keys(slack.groups).map((k) -> slack.groups[k] ).filter((g) -> g.is_open and !g.is_archived ).map((g) -> g.name ) console.log 'Welcome to Slack. You are ' + slack.self.name + ' of ' + slack.team.name if channels.length > 0 console.log 'You are in: ' + channels.join(', ') else console.log 'You are not in any channels.' if groups.length > 0 console.log 'As well as: ' + groups.join(', ') return slack.on 'message', (message) -> channel = slack.getChannelGroupOrDMByID(message.channel) user = slack.getUserByID(message.user) if message.type == 'message' and isDirect(slack.self.id, message.text) trimmedMessage = message.text.substr(makeMention(slack.self.id).length).trim() channel.send user.real_name + ' just said: ' + trimmedMessage return slack.login()
1507
Slack = require('slack-client') token = '<KEY>' slack = new Slack(token, true, true) makeMention = (userId) -> '<@' + userId + '>' isDirect = (userId, messageText) -> userTag = makeMention(userId) messageText and messageText.length >= userTag.length and messageText.substr(0, userTag.length) == userTag # --- # generated by js2coffee 2.0.4 slack.on 'open', -> channels = Object.keys(slack.channels).map((k) -> slack.channels[k] ).filter((c) -> c.is_member ).map((c) -> c.name ) groups = Object.keys(slack.groups).map((k) -> slack.groups[k] ).filter((g) -> g.is_open and !g.is_archived ).map((g) -> g.name ) console.log 'Welcome to Slack. You are ' + slack.self.name + ' of ' + slack.team.name if channels.length > 0 console.log 'You are in: ' + channels.join(', ') else console.log 'You are not in any channels.' if groups.length > 0 console.log 'As well as: ' + groups.join(', ') return slack.on 'message', (message) -> channel = slack.getChannelGroupOrDMByID(message.channel) user = slack.getUserByID(message.user) if message.type == 'message' and isDirect(slack.self.id, message.text) trimmedMessage = message.text.substr(makeMention(slack.self.id).length).trim() channel.send user.real_name + ' just said: ' + trimmedMessage return slack.login()
true
Slack = require('slack-client') token = 'PI:KEY:<KEY>END_PI' slack = new Slack(token, true, true) makeMention = (userId) -> '<@' + userId + '>' isDirect = (userId, messageText) -> userTag = makeMention(userId) messageText and messageText.length >= userTag.length and messageText.substr(0, userTag.length) == userTag # --- # generated by js2coffee 2.0.4 slack.on 'open', -> channels = Object.keys(slack.channels).map((k) -> slack.channels[k] ).filter((c) -> c.is_member ).map((c) -> c.name ) groups = Object.keys(slack.groups).map((k) -> slack.groups[k] ).filter((g) -> g.is_open and !g.is_archived ).map((g) -> g.name ) console.log 'Welcome to Slack. You are ' + slack.self.name + ' of ' + slack.team.name if channels.length > 0 console.log 'You are in: ' + channels.join(', ') else console.log 'You are not in any channels.' if groups.length > 0 console.log 'As well as: ' + groups.join(', ') return slack.on 'message', (message) -> channel = slack.getChannelGroupOrDMByID(message.channel) user = slack.getUserByID(message.user) if message.type == 'message' and isDirect(slack.self.id, message.text) trimmedMessage = message.text.substr(makeMention(slack.self.id).length).trim() channel.send user.real_name + ' just said: ' + trimmedMessage return slack.login()
[ { "context": "t\"\n apiEndPoint: \"http://localhost\"\n jwt_secret: \"@#$%@$^^@#%$^#ASsd@#$%@$^^@#%$^#ASsd\"\n session:\n secret: \"Th#Hous#0fD$v!d!5$l!v3\"\n", "end": 166, "score": 0.8560214638710022, "start": 129, "tag": "KEY", "value": "\"@#$%@$^^@#%$^#ASsd@#$%@$^^@#%$^#ASsd" }, { "context": "^#ASsd@#$%@$^^@#%$^#ASsd\"\n session:\n secret: \"Th#Hous#0fD$v!d!5$l!v3\"\n permissionLevels: # TODO: move to db\n USER", "end": 214, "score": 0.9712671041488647, "start": 192, "tag": "KEY", "value": "Th#Hous#0fD$v!d!5$l!v3" }, { "context": "://localhost/starterapp_test\"\n redis:\n host: \"127.0.0.1\"\n port: 6379\n db: 1\n ttl: 60 * 60 * 24 *", "end": 390, "score": 0.9997513294219971, "start": 381, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " 60 * 24 * 365 # 1 Year\n email:\n marketing : \"contact@starterapp.com\"\n support : \"support@starterapp.com\"\n con", "end": 502, "score": 0.9999234676361084, "start": 480, "tag": "EMAIL", "value": "contact@starterapp.com" }, { "context": "eting : \"contact@starterapp.com\"\n support : \"support@starterapp.com\"\n confirmationCodeTTL : 60 * 60 * 48 # Two day", "end": 543, "score": 0.9999239444732666, "start": 521, "tag": "EMAIL", "value": "support@starterapp.com" } ]
config/config.test.coffee
mattstone/StarterApp-Server
0
config = appName: "Starter App" port: 4000 appEndPoint: "http://localhost" apiEndPoint: "http://localhost" jwt_secret: "@#$%@$^^@#%$^#ASsd@#$%@$^^@#%$^#ASsd" session: secret: "Th#Hous#0fD$v!d!5$l!v3" permissionLevels: # TODO: move to db USER: 1 SUBSCRIBER: 2 ADMIN: 2000 mongodb: uri : "mongodb://localhost/starterapp_test" redis: host: "127.0.0.1" port: 6379 db: 1 ttl: 60 * 60 * 24 * 365 # 1 Year email: marketing : "contact@starterapp.com" support : "support@starterapp.com" confirmationCodeTTL : 60 * 60 * 48 # Two days module.exports = config
61561
config = appName: "Starter App" port: 4000 appEndPoint: "http://localhost" apiEndPoint: "http://localhost" jwt_secret: <KEY>" session: secret: "<KEY>" permissionLevels: # TODO: move to db USER: 1 SUBSCRIBER: 2 ADMIN: 2000 mongodb: uri : "mongodb://localhost/starterapp_test" redis: host: "127.0.0.1" port: 6379 db: 1 ttl: 60 * 60 * 24 * 365 # 1 Year email: marketing : "<EMAIL>" support : "<EMAIL>" confirmationCodeTTL : 60 * 60 * 48 # Two days module.exports = config
true
config = appName: "Starter App" port: 4000 appEndPoint: "http://localhost" apiEndPoint: "http://localhost" jwt_secret: PI:KEY:<KEY>END_PI" session: secret: "PI:KEY:<KEY>END_PI" permissionLevels: # TODO: move to db USER: 1 SUBSCRIBER: 2 ADMIN: 2000 mongodb: uri : "mongodb://localhost/starterapp_test" redis: host: "127.0.0.1" port: 6379 db: 1 ttl: 60 * 60 * 24 * 365 # 1 Year email: marketing : "PI:EMAIL:<EMAIL>END_PI" support : "PI:EMAIL:<EMAIL>END_PI" confirmationCodeTTL : 60 * 60 * 48 # Two days module.exports = config
[ { "context": " attributes: {\n config: {}\n name: \"Unnamed\"\n }\n }\n\n App.server.create_doc(msg)\n ", "end": 752, "score": 0.8360385894775391, "start": 745, "tag": "NAME", "value": "Unnamed" } ]
cmdr_web/src/scripts/views/device_configure.coffee
wesleyan/cmdr-server
2
slinky_require('../core.coffee') slinky_require('configure_list.coffee') slinky_require('bind_view.coffee') App.DevicesConfigureView = App.BindView.extend initialize: () -> App.rooms.bind "change:selection", @render, this @configure_list = new App.ConfigureListView(App.devices) @configure_list.bind "add", @add, this @configure_list.bind "remove", @remove, this App.devices.bind "change:selection", @change_selection, this App.devices.bind "change:update", @render, this @change_selection() add: () -> msg = { _id: App.server.createUUID() belongs_to: App.rooms.selected.get('id') controller: null device: true class: null attributes: { config: {} name: "Unnamed" } } App.server.create_doc(msg) App.devices.add(msg) @render() remove: () -> doc = App.devices.selected.attributes doc.belongs_to = doc.belongs_to.id App.server.remove_doc(doc) App.rooms.selected.attributes.devices.remove(App.devices.selected) App.devices.remove(App.devices.selected) @render set_up_bindings: (room) -> @unbind_all() if @device @field_bind "input[name='name']", @device, ((r) -> r.get('attributes')?.name), ((r, v) -> r.set(attributes: _(r.get('attributes')).extend(name: v))) @field_bind "select[name='type']", @device, ((r) -> r.driver()?.type()), ((r, v) => @update_drivers(v)) @field_bind "select[name='driver']", @device, ((r) -> r.driver()?.get('name')), ((r, v) => r.set(driver: v); @update_options(v)) if @driver_options _(@driver_options).each (opt) => @field_bind ".options [name='#{opt.name}']", @device, ((r) -> r.get('attributes')?.config?[opt.name]), ((r, v) -> config = r.get('attributes')?.config config = {} unless config config[opt.name] = v r.set(attributes: _(r.get('attributes')).extend(config: config))) change_selection: () -> @device = App.devices.selected @update_drivers(@device?.driver()?.type()) @update_options(@device?.driver()?.get('name')) @set_up_bindings() update_drivers: (type) -> options = _(App.drivers.get_by_type(type)) .chain() .filter((d) -> not d.get('abstract')) .invoke("get", "name") .map((d) -> "<option value=\"#{d}\">#{d}</option>") .value() .join("\n") $("select[name='driver']", @el).html options update_options: (name) -> driver = App.drivers.get_by_name(name) if driver @model = App.rooms.selected @driver_options = _(driver.options()).map((d) => _.extend(_.clone(d), ports: @model.get('params').ports)) hash = options: @driver_options $(".options", @el).html(App.templates.driver_options(hash)) @set_up_bindings() render: () -> @model = App.rooms.selected if @model types = _(App.drivers.pluck("type")).chain().compact().uniq().value() hash = types: types $(@el).html App.templates.device_configure(hash) $(".device-list", @el).html @configure_list.render().el #@set_up_bindings(@model) $(".save-button", @el).click((e) => @save(e)) $(".cancel-button", @el).click((e) => @save(e)) this save: () -> App.server.save_doc(App.devices.selected) cancel: () ->
65259
slinky_require('../core.coffee') slinky_require('configure_list.coffee') slinky_require('bind_view.coffee') App.DevicesConfigureView = App.BindView.extend initialize: () -> App.rooms.bind "change:selection", @render, this @configure_list = new App.ConfigureListView(App.devices) @configure_list.bind "add", @add, this @configure_list.bind "remove", @remove, this App.devices.bind "change:selection", @change_selection, this App.devices.bind "change:update", @render, this @change_selection() add: () -> msg = { _id: App.server.createUUID() belongs_to: App.rooms.selected.get('id') controller: null device: true class: null attributes: { config: {} name: "<NAME>" } } App.server.create_doc(msg) App.devices.add(msg) @render() remove: () -> doc = App.devices.selected.attributes doc.belongs_to = doc.belongs_to.id App.server.remove_doc(doc) App.rooms.selected.attributes.devices.remove(App.devices.selected) App.devices.remove(App.devices.selected) @render set_up_bindings: (room) -> @unbind_all() if @device @field_bind "input[name='name']", @device, ((r) -> r.get('attributes')?.name), ((r, v) -> r.set(attributes: _(r.get('attributes')).extend(name: v))) @field_bind "select[name='type']", @device, ((r) -> r.driver()?.type()), ((r, v) => @update_drivers(v)) @field_bind "select[name='driver']", @device, ((r) -> r.driver()?.get('name')), ((r, v) => r.set(driver: v); @update_options(v)) if @driver_options _(@driver_options).each (opt) => @field_bind ".options [name='#{opt.name}']", @device, ((r) -> r.get('attributes')?.config?[opt.name]), ((r, v) -> config = r.get('attributes')?.config config = {} unless config config[opt.name] = v r.set(attributes: _(r.get('attributes')).extend(config: config))) change_selection: () -> @device = App.devices.selected @update_drivers(@device?.driver()?.type()) @update_options(@device?.driver()?.get('name')) @set_up_bindings() update_drivers: (type) -> options = _(App.drivers.get_by_type(type)) .chain() .filter((d) -> not d.get('abstract')) .invoke("get", "name") .map((d) -> "<option value=\"#{d}\">#{d}</option>") .value() .join("\n") $("select[name='driver']", @el).html options update_options: (name) -> driver = App.drivers.get_by_name(name) if driver @model = App.rooms.selected @driver_options = _(driver.options()).map((d) => _.extend(_.clone(d), ports: @model.get('params').ports)) hash = options: @driver_options $(".options", @el).html(App.templates.driver_options(hash)) @set_up_bindings() render: () -> @model = App.rooms.selected if @model types = _(App.drivers.pluck("type")).chain().compact().uniq().value() hash = types: types $(@el).html App.templates.device_configure(hash) $(".device-list", @el).html @configure_list.render().el #@set_up_bindings(@model) $(".save-button", @el).click((e) => @save(e)) $(".cancel-button", @el).click((e) => @save(e)) this save: () -> App.server.save_doc(App.devices.selected) cancel: () ->
true
slinky_require('../core.coffee') slinky_require('configure_list.coffee') slinky_require('bind_view.coffee') App.DevicesConfigureView = App.BindView.extend initialize: () -> App.rooms.bind "change:selection", @render, this @configure_list = new App.ConfigureListView(App.devices) @configure_list.bind "add", @add, this @configure_list.bind "remove", @remove, this App.devices.bind "change:selection", @change_selection, this App.devices.bind "change:update", @render, this @change_selection() add: () -> msg = { _id: App.server.createUUID() belongs_to: App.rooms.selected.get('id') controller: null device: true class: null attributes: { config: {} name: "PI:NAME:<NAME>END_PI" } } App.server.create_doc(msg) App.devices.add(msg) @render() remove: () -> doc = App.devices.selected.attributes doc.belongs_to = doc.belongs_to.id App.server.remove_doc(doc) App.rooms.selected.attributes.devices.remove(App.devices.selected) App.devices.remove(App.devices.selected) @render set_up_bindings: (room) -> @unbind_all() if @device @field_bind "input[name='name']", @device, ((r) -> r.get('attributes')?.name), ((r, v) -> r.set(attributes: _(r.get('attributes')).extend(name: v))) @field_bind "select[name='type']", @device, ((r) -> r.driver()?.type()), ((r, v) => @update_drivers(v)) @field_bind "select[name='driver']", @device, ((r) -> r.driver()?.get('name')), ((r, v) => r.set(driver: v); @update_options(v)) if @driver_options _(@driver_options).each (opt) => @field_bind ".options [name='#{opt.name}']", @device, ((r) -> r.get('attributes')?.config?[opt.name]), ((r, v) -> config = r.get('attributes')?.config config = {} unless config config[opt.name] = v r.set(attributes: _(r.get('attributes')).extend(config: config))) change_selection: () -> @device = App.devices.selected @update_drivers(@device?.driver()?.type()) @update_options(@device?.driver()?.get('name')) @set_up_bindings() update_drivers: (type) -> options = _(App.drivers.get_by_type(type)) .chain() .filter((d) -> not d.get('abstract')) .invoke("get", "name") .map((d) -> "<option value=\"#{d}\">#{d}</option>") .value() .join("\n") $("select[name='driver']", @el).html options update_options: (name) -> driver = App.drivers.get_by_name(name) if driver @model = App.rooms.selected @driver_options = _(driver.options()).map((d) => _.extend(_.clone(d), ports: @model.get('params').ports)) hash = options: @driver_options $(".options", @el).html(App.templates.driver_options(hash)) @set_up_bindings() render: () -> @model = App.rooms.selected if @model types = _(App.drivers.pluck("type")).chain().compact().uniq().value() hash = types: types $(@el).html App.templates.device_configure(hash) $(".device-list", @el).html @configure_list.render().el #@set_up_bindings(@model) $(".save-button", @el).click((e) => @save(e)) $(".cancel-button", @el).click((e) => @save(e)) this save: () -> App.server.save_doc(App.devices.selected) cancel: () ->
[ { "context": " if @directory == \"\"\n @directory = \"/home/#{@username}\"\n\n super( @alias, @hostname, @directory, @u", "end": 1150, "score": 0.8309915065765381, "start": 1141, "tag": "USERNAME", "value": "@username" }, { "context": "e}\"\n\n super( @alias, @hostname, @directory, @username, @port, @localFiles, @usePassword, @lastOpenDirec", "end": 1207, "score": 0.529175877571106, "start": 1199, "tag": "USERNAME", "value": "username" }, { "context": " @hostname,\n port: @port,\n username: @username,\n tryKeyboard: true\n }\n\n\n\n getConn", "end": 1392, "score": 0.9836873412132263, "start": 1383, "tag": "USERNAME", "value": "@username" }, { "context": " @hostname,\n port: @port,\n username: @username,\n }\n\n if atom.config.get('remote-edit-n", "end": 1570, "score": 0.9839276075363159, "start": 1561, "tag": "USERNAME", "value": "@username" }, { "context": ")\n {host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), pas", "end": 2219, "score": 0.9977362155914307, "start": 2210, "tag": "USERNAME", "value": "@username" }, { "context": "e\n {host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), pas", "end": 2365, "score": 0.9980382919311523, "start": 2356, "tag": "USERNAME", "value": "@username" }, { "context": ")\n {host: @hostname, port: @port, username: @username, password: keytarPassword}\n else\n {ho", "end": 2714, "score": 0.9974479675292969, "start": 2705, "tag": "USERNAME", "value": "@username" }, { "context": "tname, port: @port, username: @username, password: keytarPassword}\n else\n {host: @hostname, port: @port", "end": 2740, "score": 0.9985670447349548, "start": 2726, "tag": "PASSWORD", "value": "keytarPassword" }, { "context": "e\n {host: @hostname, port: @port, username: @username, password: @password}\n\n getPrivateKey: (path) ", "end": 2811, "score": 0.9980850219726562, "start": 2802, "tag": "USERNAME", "value": "@username" }, { "context": "tname, port: @port, username: @username, password: @password}\n\n getPrivateKey: (path) ->\n if path[0] =", "end": 2832, "score": 0.9956175088882446, "start": 2823, "tag": "PASSWORD", "value": "@password" }, { "context": "r occured when reading remote directory sftp://#{@username}@#{@hostname}:#{@port}:#{path}\", type: 'error'} )", "end": 7700, "score": 0.8306856751441956, "start": 7692, "tag": "USERNAME", "value": "username" }, { "context": "('info', {message: \"Getting remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path", "end": 8095, "score": 0.7274729013442993, "start": 8087, "tag": "USERNAME", "value": "username" }, { "context": "essage: \"Error when reading remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path", "end": 8486, "score": 0.8665674924850464, "start": 8478, "tag": "USERNAME", "value": "username" }, { "context": "message: \"Successfully read remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path", "end": 8653, "score": 0.6991166472434998, "start": 8645, "tag": "USERNAME", "value": "username" }, { "context": " 'info', {message: \"Writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path", "end": 8914, "score": 0.7992861270904541, "start": 8906, "tag": "USERNAME", "value": "username" }, { "context": "\"Error occured when writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path", "end": 9400, "score": 0.8860546946525574, "start": 9392, "tag": "USERNAME", "value": "username" }, { "context": "essage: \"Successfully wrote remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path", "end": 9622, "score": 0.8047221899032593, "start": 9614, "tag": "USERNAME", "value": "username" }, { "context": " {message: \"Creating remote directory at sftp://#{@username}@#{@hostname}:#{@port}#{folderpath}\", type: 'info", "end": 10770, "score": 0.7699373960494995, "start": 10761, "tag": "USERNAME", "value": "@username" }, { "context": "occured while creating remote directory sftp://#{@username}@#{@hostname}:#{@port}#{folderpath}\", type: 'erro", "end": 11177, "score": 0.9677135944366455, "start": 11169, "tag": "USERNAME", "value": "username" }, { "context": "essage: \"Successfully created directory sftp://#{@username}@#{@hostname}:#{@port}#{folderpath}\", type: 'succ", "end": 11373, "score": 0.9549186825752258, "start": 11365, "tag": "USERNAME", "value": "username" }, { "context": "fo', {message: \"Creating remote file at sftp://#{@username}@#{@hostname}:#{@port}#{filepath}\", type: 'info'}", "end": 11584, "score": 0.9456996917724609, "start": 11576, "tag": "USERNAME", "value": "username" }, { "context": " @emitter.emit('info', {message: \"Fle ftp://#{@username}@#{@hostname}:#{@port}#{filepath} already exists\"", "end": 12100, "score": 0.9501424431800842, "start": 12092, "tag": "USERNAME", "value": "username" }, { "context": "rror occurred while creating remote file ftp://#{@username}@#{@hostname}:#{@port}#{filepath}\", type: 'error'", "end": 12295, "score": 0.8836362361907959, "start": 12287, "tag": "USERNAME", "value": "username" }, { "context": "message: \"Successfully wrote remote file ftp://#{@username}@#{@hostname}:#{@port}#{filepath}\", type: 'succes", "end": 12500, "score": 0.935141384601593, "start": 12492, "tag": "USERNAME", "value": "username" }, { "context": "ccurred when deleting remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{deletepath}\", type: 'erro", "end": 13143, "score": 0.8882726430892944, "start": 13134, "tag": "USERNAME", "value": "@username" }, { "context": "\"Successfully deleted remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{deletepath}\", type: 'succ", "end": 13354, "score": 0.7560893297195435, "start": 13345, "tag": "USERNAME", "value": "@username" }, { "context": "curred when renaming remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{oldPath}\", type: 'error'}", "end": 14735, "score": 0.8427680730819702, "start": 14727, "tag": "USERNAME", "value": "username" }, { "context": "Successfully renamed remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{oldPath}\", type: 'success", "end": 14949, "score": 0.8769288063049316, "start": 14941, "tag": "USERNAME", "value": "username" }, { "context": "', {message: \"Cannot set permissions to sftp://#{@username}@#{@hostname}:#{@port}#{path}\", type: 'error'})\n ", "end": 15429, "score": 0.6525369882583618, "start": 15421, "tag": "USERNAME", "value": "username" } ]
lib/model/sftp-host.coffee
urban-1/remote-edit-ni
0
Host = require './host' RemoteFile = require './remote-file' LocalFile = require './local-file' Dialog = require '../view/dialog' fs = require 'fs-plus' ssh2 = require 'ssh2' async = require 'async' util = require 'util' filesize = require 'file-size' moment = require 'moment' Serializable = require 'serializable' Path = require 'path' osenv = require 'osenv' _ = require 'underscore-plus' try keytar = require 'keytar' catch err console.debug 'Keytar could not be loaded! Passwords will be stored in cleartext to remoteEdit.json!' keytar = undefined module.exports = class SftpHost extends Host Serializable.includeInto(this) atom.deserializers.add(this) Host.registerDeserializers(SftpHost) connection: undefined protocol: "sftp" constructor: (@alias = null, @hostname, @directory, @username, @port = "22", @localFiles = [], @useKeyboard = false, @usePassword = false, @useAgent = true, @usePrivateKey = false, @password, @passphrase, @privateKeyPath, @lastOpenDirectory) -> # Default to /home/<username> which is the most common case... if @directory == "" @directory = "/home/#{@username}" super( @alias, @hostname, @directory, @username, @port, @localFiles, @usePassword, @lastOpenDirectory) getConnectionStringUsingKbdInteractive: -> { host: @hostname, port: @port, username: @username, tryKeyboard: true } getConnectionStringUsingAgent: -> connectionString = { host: @hostname, port: @port, username: @username, } if atom.config.get('remote-edit-ni.agentToUse') != 'Default' _.extend(connectionString, {agent: atom.config.get('remote-edit-ni.agentToUse')}) else if process.platform == "win32" _.extend(connectionString, {agent: 'pageant'}) else _.extend(connectionString, {agent: process.env['SSH_AUTH_SOCK']}) connectionString getConnectionStringUsingKey: -> if atom.config.get('remote-edit-ni.storePasswordsUsingKeytar') and (keytar?) keytarPassphrase = keytar.getPassword(@getServiceNamePassphrase(), @getServiceAccount()) {host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), passphrase: keytarPassphrase} else {host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), passphrase: @passphrase} getConnectionStringUsingPassword: -> if atom.config.get('remote-edit-ni.storePasswordsUsingKeytar') and (keytar?) keytarPassword = keytar.getPassword(@getServiceNamePassword(), @getServiceAccount()) {host: @hostname, port: @port, username: @username, password: keytarPassword} else {host: @hostname, port: @port, username: @username, password: @password} getPrivateKey: (path) -> if path[0] == "~" path = Path.normalize(osenv.home() + path.substring(1, path.length)) return fs.readFileSync(path, 'ascii', (err, data) -> throw err if err? return data.trim() ) createRemoteFileFromFile: (path, file) -> remoteFile = new RemoteFile(Path.normalize("#{path}/#{file.filename}").split(Path.sep).join('/'), (file.longname[0] == '-'), (file.longname[0] == 'd'), (file.longname[0] == 'l'), filesize(file.attrs.size).human(), parseInt(file.attrs.mode, 10).toString(8).substr(2, 4), moment(file.attrs.mtime * 1000).format("HH:mm:ss DD/MM/YYYY")) return remoteFile getServiceNamePassword: -> "atom.remote-edit-ni.ssh.password" getServiceNamePassphrase: -> "atom.remote-edit-ni.ssh.passphrase" #################### # Overridden methods getConnectionString: (connectionOptions) -> if @useAgent connectionOptions = _.extend(@getConnectionStringUsingAgent(), connectionOptions) if @usePrivateKey connectionOptions = _.extend(@getConnectionStringUsingKey(), connectionOptions) if @usePassword connectionOptions = _.extend(@getConnectionStringUsingPassword(), connectionOptions) if @useKeyboard connectionOptions = _.extend(@getConnectionStringUsingKbdInteractive(), connectionOptions) return connectionOptions close: (callback) -> @connection?.end() @connection = null callback?(null) connect: (callback, connectionOptions = {}) -> @emitter.emit 'info', {message: "Connecting to sftp://#{@username}@#{@hostname}:#{@port}", type: 'info'} async.waterfall([ (callback) => if @usePrivateKey fs.exists(@privateKeyPath, ((exists) => if exists callback?(null) else @emitter.emit 'info', {message: "Private key does not exist!", type: 'error'} callback?(new Error("Private key does not exist")) ) ) else callback?(null) (callback) => console.debug "Real Host Connect..." @connection = new ssh2() @connection.on 'error', (err) => @emitter.emit 'info', {message: "Error occured when connecting to sftp://#{@username}@#{@hostname}:#{@port}", type: 'error'} @connection?.end() callback?(err) @connection.on 'ready', => @emitter.emit 'info', {message: "Successfully connected to sftp://#{@username}@#{@hostname}:#{@port}", type: 'success'} callback?(null) # Here we break MV paradigm... but is the nature of the job... @connection.on 'keyboard-interactive', (name, instructions, instructionsLang, prompts, finish) -> # console.log('Connection :: keyboard-interactive') # console.log(prompts) async.waterfall([ (callback) -> passwordDialog = new Dialog({ prompt: "Keyboard Interactive Auth", detail: prompts[0].prompt.replace(/(?:\r\n|\r|\n)/g, '<br>') }) passwordDialog.toggle(callback) ], (err, result) => if err? callback?(err) else finish([result]) ) # Enable keepalive on the connection to keep firewalls and nat happy connectionOptions = _.extend({keepaliveInterval: 10000, keepaliveCountMax: 6}, connectionOptions) # Go do this... @connection.connect(@getConnectionString(connectionOptions)) ], (err) -> callback?(err) ) isConnected: -> @connection? and @connection._sock and @connection._sock.writable and @connection._sshstream and @connection._sshstream.writable getFilesMetadata: (path, callback) -> async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => # temp store in this so we can close it when we are done... @tmp_sftp = sftp sftp.readdir(path, callback) (files, callback) => # ... and now we are done! @tmp_sftp.end() async.map(files, ((file, callback) => callback?(null, @createRemoteFileFromFile(path, file))), callback) (objects, callback) -> objects.push(new RemoteFile((path + "/.."), false, true, false, null, null, null)) if atom.config.get 'remote-edit-ni.showHiddenFiles' callback?(null, objects) else async.filter(objects, ((item, callback) -> item.isHidden(callback)), ((result) -> callback?(null, result))) ], (err, result) => if err? @emitter.emit('info', {message: "Error occured when reading remote directory sftp://#{@username}@#{@hostname}:#{@port}:#{path}", type: 'error'} ) console.error err console.error err.code callback?(err) else callback?(err, (result.sort (a, b) -> return if a.name.toLowerCase() >= b.name.toLowerCase() then 1 else -1)) ) getFile: (localFile, callback) -> @emitter.emit('info', {message: "Getting remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'info'}) async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => sftp.fastGet(localFile.remoteFile.path, localFile.path, (err) => callback?(err, sftp)) ], (err, sftp) => @emitter.emit('info', {message: "Error when reading remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'error'}) if err? @emitter.emit('info', {message: "Successfully read remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'success'}) if !err? sftp?.end() callback?(err, localFile) ) writeFile: (localFile, callback) -> @emitter.emit 'info', {message: "Writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'info'} async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) -> @tmp_sftp = sftp sftp.fastPut(localFile.path, localFile.remoteFile.path, callback) (callback) -> @tmp_sftp.end() callback?() ], (err) => if err? @emitter.emit('info', {message: "Error occured when writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}<br/>#{err}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully wrote remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'success'}) callback?(err) ) serializeParams: -> tmp = if @password then @password else "" { @alias @hostname @directory @username @port localFiles: localFile.serialize() for localFile in @localFiles @useKeyboard @useAgent @usePrivateKey @usePassword password: new Buffer(tmp).toString("base64") @passphrase @privateKeyPath @lastOpenDirectory } deserializeParams: (params) -> tmpArray = [] tmpArray.push(LocalFile.deserialize(localFile, host: this)) for localFile in params.localFiles params.localFiles = tmpArray params.password = if params.password then new Buffer(params.password, "base64").toString("utf8") else "" params # Create the folder and call the callback. The callback will be called # for both error cases (1st arg) and success (2nd arg is the path) createFolder: (folderpath, callback) -> @emitter.emit 'info', {message: "Creating remote directory at sftp://#{@username}@#{@hostname}:#{@port}#{folderpath}", type: 'info'} async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) -> sftp.mkdir(folderpath, callback) sftp.end() callback?(null, folderpath) ], (err) => if err? @emitter.emit('info', {message: "Error occured while creating remote directory sftp://#{@username}@#{@hostname}:#{@port}#{folderpath}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully created directory sftp://#{@username}@#{@hostname}:#{@port}#{folderpath}", type: 'success'}) callback?(err) ) createFile: (filepath, callback) -> @emitter.emit 'info', {message: "Creating remote file at sftp://#{@username}@#{@hostname}:#{@port}#{filepath}", type: 'info'} async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => @tmp_sftp = sftp sftp.exists(filepath, callback) (callback) => @tmp_sftp.writeFile(filepath, "", callback) (callback) => @tmp_sftp.end() callback?() ], (err) => if err? if err == true @emitter.emit('info', {message: "Fle ftp://#{@username}@#{@hostname}:#{@port}#{filepath} already exists", type: 'error'}) else @emitter.emit('info', {message: "Error occurred while creating remote file ftp://#{@username}@#{@hostname}:#{@port}#{filepath}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully wrote remote file ftp://#{@username}@#{@hostname}:#{@port}#{filepath}", type: 'success'}) callback?(err) ) deleteFolderFile: (deletepath, isFolder, callback) -> async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => @tmp_sftp = sftp if isFolder sftp.rmdir(deletepath, callback) else sftp.unlink(deletepath, callback) (callback) => @tmp_sftp.end() callback?(null) ], (err) => if err? @emitter.emit('info', {message: "Error occurred when deleting remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{deletepath}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully deleted remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{deletepath}", type: 'success'}) callback?(err) ) renameFolderFile: (path, oldName, newName, isFolder, callback) => if oldName == newName @emitter.emit('info', {message: "The new name is same as the old", type: 'error'}) return oldPath = path + "/" + oldName newPath = path + "/" + newName @moveFolderFile(oldPath, newPath, isFolder, callback) moveFolderFile: (oldPath, newPath, isFolder, callback) => async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => @tmp_sftp = sftp if isFolder sftp.readdir(newPath, callback) else sftp.exists(newPath, callback) ], (err, result) => if (isFolder and result != undefined) or (!isFolder and err==true) @emitter.emit('info', {message: "#{if isFolder then 'Folder' else 'File'} already exists", type: 'error'}) @tmp_sftp.end() return async.waterfall([ (callback) => @tmp_sftp.rename(oldPath, newPath, callback) (callback) => @tmp_sftp.end() callback?() ], (err) => if err? @emitter.emit('info', {message: "Error occurred when renaming remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{oldPath}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully renamed remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{oldPath}", type: 'success'}) callback?(err) ) ) setPermissions: (path, permissions, callback) => async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => @tmp_sftp = sftp sftp.chmod(path, permissions, callback) ], (err, result) => if err? @emitter.emit('info', {message: "Cannot set permissions to sftp://#{@username}@#{@hostname}:#{@port}#{path}", type: 'error'}) console.error err if err? @tmp_sftp.end() callback?(err) )
147099
Host = require './host' RemoteFile = require './remote-file' LocalFile = require './local-file' Dialog = require '../view/dialog' fs = require 'fs-plus' ssh2 = require 'ssh2' async = require 'async' util = require 'util' filesize = require 'file-size' moment = require 'moment' Serializable = require 'serializable' Path = require 'path' osenv = require 'osenv' _ = require 'underscore-plus' try keytar = require 'keytar' catch err console.debug 'Keytar could not be loaded! Passwords will be stored in cleartext to remoteEdit.json!' keytar = undefined module.exports = class SftpHost extends Host Serializable.includeInto(this) atom.deserializers.add(this) Host.registerDeserializers(SftpHost) connection: undefined protocol: "sftp" constructor: (@alias = null, @hostname, @directory, @username, @port = "22", @localFiles = [], @useKeyboard = false, @usePassword = false, @useAgent = true, @usePrivateKey = false, @password, @passphrase, @privateKeyPath, @lastOpenDirectory) -> # Default to /home/<username> which is the most common case... if @directory == "" @directory = "/home/#{@username}" super( @alias, @hostname, @directory, @username, @port, @localFiles, @usePassword, @lastOpenDirectory) getConnectionStringUsingKbdInteractive: -> { host: @hostname, port: @port, username: @username, tryKeyboard: true } getConnectionStringUsingAgent: -> connectionString = { host: @hostname, port: @port, username: @username, } if atom.config.get('remote-edit-ni.agentToUse') != 'Default' _.extend(connectionString, {agent: atom.config.get('remote-edit-ni.agentToUse')}) else if process.platform == "win32" _.extend(connectionString, {agent: 'pageant'}) else _.extend(connectionString, {agent: process.env['SSH_AUTH_SOCK']}) connectionString getConnectionStringUsingKey: -> if atom.config.get('remote-edit-ni.storePasswordsUsingKeytar') and (keytar?) keytarPassphrase = keytar.getPassword(@getServiceNamePassphrase(), @getServiceAccount()) {host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), passphrase: keytarPassphrase} else {host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), passphrase: @passphrase} getConnectionStringUsingPassword: -> if atom.config.get('remote-edit-ni.storePasswordsUsingKeytar') and (keytar?) keytarPassword = keytar.getPassword(@getServiceNamePassword(), @getServiceAccount()) {host: @hostname, port: @port, username: @username, password: <PASSWORD>} else {host: @hostname, port: @port, username: @username, password: <PASSWORD>} getPrivateKey: (path) -> if path[0] == "~" path = Path.normalize(osenv.home() + path.substring(1, path.length)) return fs.readFileSync(path, 'ascii', (err, data) -> throw err if err? return data.trim() ) createRemoteFileFromFile: (path, file) -> remoteFile = new RemoteFile(Path.normalize("#{path}/#{file.filename}").split(Path.sep).join('/'), (file.longname[0] == '-'), (file.longname[0] == 'd'), (file.longname[0] == 'l'), filesize(file.attrs.size).human(), parseInt(file.attrs.mode, 10).toString(8).substr(2, 4), moment(file.attrs.mtime * 1000).format("HH:mm:ss DD/MM/YYYY")) return remoteFile getServiceNamePassword: -> "atom.remote-edit-ni.ssh.password" getServiceNamePassphrase: -> "atom.remote-edit-ni.ssh.passphrase" #################### # Overridden methods getConnectionString: (connectionOptions) -> if @useAgent connectionOptions = _.extend(@getConnectionStringUsingAgent(), connectionOptions) if @usePrivateKey connectionOptions = _.extend(@getConnectionStringUsingKey(), connectionOptions) if @usePassword connectionOptions = _.extend(@getConnectionStringUsingPassword(), connectionOptions) if @useKeyboard connectionOptions = _.extend(@getConnectionStringUsingKbdInteractive(), connectionOptions) return connectionOptions close: (callback) -> @connection?.end() @connection = null callback?(null) connect: (callback, connectionOptions = {}) -> @emitter.emit 'info', {message: "Connecting to sftp://#{@username}@#{@hostname}:#{@port}", type: 'info'} async.waterfall([ (callback) => if @usePrivateKey fs.exists(@privateKeyPath, ((exists) => if exists callback?(null) else @emitter.emit 'info', {message: "Private key does not exist!", type: 'error'} callback?(new Error("Private key does not exist")) ) ) else callback?(null) (callback) => console.debug "Real Host Connect..." @connection = new ssh2() @connection.on 'error', (err) => @emitter.emit 'info', {message: "Error occured when connecting to sftp://#{@username}@#{@hostname}:#{@port}", type: 'error'} @connection?.end() callback?(err) @connection.on 'ready', => @emitter.emit 'info', {message: "Successfully connected to sftp://#{@username}@#{@hostname}:#{@port}", type: 'success'} callback?(null) # Here we break MV paradigm... but is the nature of the job... @connection.on 'keyboard-interactive', (name, instructions, instructionsLang, prompts, finish) -> # console.log('Connection :: keyboard-interactive') # console.log(prompts) async.waterfall([ (callback) -> passwordDialog = new Dialog({ prompt: "Keyboard Interactive Auth", detail: prompts[0].prompt.replace(/(?:\r\n|\r|\n)/g, '<br>') }) passwordDialog.toggle(callback) ], (err, result) => if err? callback?(err) else finish([result]) ) # Enable keepalive on the connection to keep firewalls and nat happy connectionOptions = _.extend({keepaliveInterval: 10000, keepaliveCountMax: 6}, connectionOptions) # Go do this... @connection.connect(@getConnectionString(connectionOptions)) ], (err) -> callback?(err) ) isConnected: -> @connection? and @connection._sock and @connection._sock.writable and @connection._sshstream and @connection._sshstream.writable getFilesMetadata: (path, callback) -> async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => # temp store in this so we can close it when we are done... @tmp_sftp = sftp sftp.readdir(path, callback) (files, callback) => # ... and now we are done! @tmp_sftp.end() async.map(files, ((file, callback) => callback?(null, @createRemoteFileFromFile(path, file))), callback) (objects, callback) -> objects.push(new RemoteFile((path + "/.."), false, true, false, null, null, null)) if atom.config.get 'remote-edit-ni.showHiddenFiles' callback?(null, objects) else async.filter(objects, ((item, callback) -> item.isHidden(callback)), ((result) -> callback?(null, result))) ], (err, result) => if err? @emitter.emit('info', {message: "Error occured when reading remote directory sftp://#{@username}@#{@hostname}:#{@port}:#{path}", type: 'error'} ) console.error err console.error err.code callback?(err) else callback?(err, (result.sort (a, b) -> return if a.name.toLowerCase() >= b.name.toLowerCase() then 1 else -1)) ) getFile: (localFile, callback) -> @emitter.emit('info', {message: "Getting remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'info'}) async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => sftp.fastGet(localFile.remoteFile.path, localFile.path, (err) => callback?(err, sftp)) ], (err, sftp) => @emitter.emit('info', {message: "Error when reading remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'error'}) if err? @emitter.emit('info', {message: "Successfully read remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'success'}) if !err? sftp?.end() callback?(err, localFile) ) writeFile: (localFile, callback) -> @emitter.emit 'info', {message: "Writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'info'} async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) -> @tmp_sftp = sftp sftp.fastPut(localFile.path, localFile.remoteFile.path, callback) (callback) -> @tmp_sftp.end() callback?() ], (err) => if err? @emitter.emit('info', {message: "Error occured when writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}<br/>#{err}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully wrote remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'success'}) callback?(err) ) serializeParams: -> tmp = if @password then @password else "" { @alias @hostname @directory @username @port localFiles: localFile.serialize() for localFile in @localFiles @useKeyboard @useAgent @usePrivateKey @usePassword password: new Buffer(tmp).toString("base64") @passphrase @privateKeyPath @lastOpenDirectory } deserializeParams: (params) -> tmpArray = [] tmpArray.push(LocalFile.deserialize(localFile, host: this)) for localFile in params.localFiles params.localFiles = tmpArray params.password = if params.password then new Buffer(params.password, "base64").toString("utf8") else "" params # Create the folder and call the callback. The callback will be called # for both error cases (1st arg) and success (2nd arg is the path) createFolder: (folderpath, callback) -> @emitter.emit 'info', {message: "Creating remote directory at sftp://#{@username}@#{@hostname}:#{@port}#{folderpath}", type: 'info'} async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) -> sftp.mkdir(folderpath, callback) sftp.end() callback?(null, folderpath) ], (err) => if err? @emitter.emit('info', {message: "Error occured while creating remote directory sftp://#{@username}@#{@hostname}:#{@port}#{folderpath}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully created directory sftp://#{@username}@#{@hostname}:#{@port}#{folderpath}", type: 'success'}) callback?(err) ) createFile: (filepath, callback) -> @emitter.emit 'info', {message: "Creating remote file at sftp://#{@username}@#{@hostname}:#{@port}#{filepath}", type: 'info'} async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => @tmp_sftp = sftp sftp.exists(filepath, callback) (callback) => @tmp_sftp.writeFile(filepath, "", callback) (callback) => @tmp_sftp.end() callback?() ], (err) => if err? if err == true @emitter.emit('info', {message: "Fle ftp://#{@username}@#{@hostname}:#{@port}#{filepath} already exists", type: 'error'}) else @emitter.emit('info', {message: "Error occurred while creating remote file ftp://#{@username}@#{@hostname}:#{@port}#{filepath}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully wrote remote file ftp://#{@username}@#{@hostname}:#{@port}#{filepath}", type: 'success'}) callback?(err) ) deleteFolderFile: (deletepath, isFolder, callback) -> async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => @tmp_sftp = sftp if isFolder sftp.rmdir(deletepath, callback) else sftp.unlink(deletepath, callback) (callback) => @tmp_sftp.end() callback?(null) ], (err) => if err? @emitter.emit('info', {message: "Error occurred when deleting remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{deletepath}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully deleted remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{deletepath}", type: 'success'}) callback?(err) ) renameFolderFile: (path, oldName, newName, isFolder, callback) => if oldName == newName @emitter.emit('info', {message: "The new name is same as the old", type: 'error'}) return oldPath = path + "/" + oldName newPath = path + "/" + newName @moveFolderFile(oldPath, newPath, isFolder, callback) moveFolderFile: (oldPath, newPath, isFolder, callback) => async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => @tmp_sftp = sftp if isFolder sftp.readdir(newPath, callback) else sftp.exists(newPath, callback) ], (err, result) => if (isFolder and result != undefined) or (!isFolder and err==true) @emitter.emit('info', {message: "#{if isFolder then 'Folder' else 'File'} already exists", type: 'error'}) @tmp_sftp.end() return async.waterfall([ (callback) => @tmp_sftp.rename(oldPath, newPath, callback) (callback) => @tmp_sftp.end() callback?() ], (err) => if err? @emitter.emit('info', {message: "Error occurred when renaming remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{oldPath}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully renamed remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{oldPath}", type: 'success'}) callback?(err) ) ) setPermissions: (path, permissions, callback) => async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => @tmp_sftp = sftp sftp.chmod(path, permissions, callback) ], (err, result) => if err? @emitter.emit('info', {message: "Cannot set permissions to sftp://#{@username}@#{@hostname}:#{@port}#{path}", type: 'error'}) console.error err if err? @tmp_sftp.end() callback?(err) )
true
Host = require './host' RemoteFile = require './remote-file' LocalFile = require './local-file' Dialog = require '../view/dialog' fs = require 'fs-plus' ssh2 = require 'ssh2' async = require 'async' util = require 'util' filesize = require 'file-size' moment = require 'moment' Serializable = require 'serializable' Path = require 'path' osenv = require 'osenv' _ = require 'underscore-plus' try keytar = require 'keytar' catch err console.debug 'Keytar could not be loaded! Passwords will be stored in cleartext to remoteEdit.json!' keytar = undefined module.exports = class SftpHost extends Host Serializable.includeInto(this) atom.deserializers.add(this) Host.registerDeserializers(SftpHost) connection: undefined protocol: "sftp" constructor: (@alias = null, @hostname, @directory, @username, @port = "22", @localFiles = [], @useKeyboard = false, @usePassword = false, @useAgent = true, @usePrivateKey = false, @password, @passphrase, @privateKeyPath, @lastOpenDirectory) -> # Default to /home/<username> which is the most common case... if @directory == "" @directory = "/home/#{@username}" super( @alias, @hostname, @directory, @username, @port, @localFiles, @usePassword, @lastOpenDirectory) getConnectionStringUsingKbdInteractive: -> { host: @hostname, port: @port, username: @username, tryKeyboard: true } getConnectionStringUsingAgent: -> connectionString = { host: @hostname, port: @port, username: @username, } if atom.config.get('remote-edit-ni.agentToUse') != 'Default' _.extend(connectionString, {agent: atom.config.get('remote-edit-ni.agentToUse')}) else if process.platform == "win32" _.extend(connectionString, {agent: 'pageant'}) else _.extend(connectionString, {agent: process.env['SSH_AUTH_SOCK']}) connectionString getConnectionStringUsingKey: -> if atom.config.get('remote-edit-ni.storePasswordsUsingKeytar') and (keytar?) keytarPassphrase = keytar.getPassword(@getServiceNamePassphrase(), @getServiceAccount()) {host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), passphrase: keytarPassphrase} else {host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), passphrase: @passphrase} getConnectionStringUsingPassword: -> if atom.config.get('remote-edit-ni.storePasswordsUsingKeytar') and (keytar?) keytarPassword = keytar.getPassword(@getServiceNamePassword(), @getServiceAccount()) {host: @hostname, port: @port, username: @username, password: PI:PASSWORD:<PASSWORD>END_PI} else {host: @hostname, port: @port, username: @username, password: PI:PASSWORD:<PASSWORD>END_PI} getPrivateKey: (path) -> if path[0] == "~" path = Path.normalize(osenv.home() + path.substring(1, path.length)) return fs.readFileSync(path, 'ascii', (err, data) -> throw err if err? return data.trim() ) createRemoteFileFromFile: (path, file) -> remoteFile = new RemoteFile(Path.normalize("#{path}/#{file.filename}").split(Path.sep).join('/'), (file.longname[0] == '-'), (file.longname[0] == 'd'), (file.longname[0] == 'l'), filesize(file.attrs.size).human(), parseInt(file.attrs.mode, 10).toString(8).substr(2, 4), moment(file.attrs.mtime * 1000).format("HH:mm:ss DD/MM/YYYY")) return remoteFile getServiceNamePassword: -> "atom.remote-edit-ni.ssh.password" getServiceNamePassphrase: -> "atom.remote-edit-ni.ssh.passphrase" #################### # Overridden methods getConnectionString: (connectionOptions) -> if @useAgent connectionOptions = _.extend(@getConnectionStringUsingAgent(), connectionOptions) if @usePrivateKey connectionOptions = _.extend(@getConnectionStringUsingKey(), connectionOptions) if @usePassword connectionOptions = _.extend(@getConnectionStringUsingPassword(), connectionOptions) if @useKeyboard connectionOptions = _.extend(@getConnectionStringUsingKbdInteractive(), connectionOptions) return connectionOptions close: (callback) -> @connection?.end() @connection = null callback?(null) connect: (callback, connectionOptions = {}) -> @emitter.emit 'info', {message: "Connecting to sftp://#{@username}@#{@hostname}:#{@port}", type: 'info'} async.waterfall([ (callback) => if @usePrivateKey fs.exists(@privateKeyPath, ((exists) => if exists callback?(null) else @emitter.emit 'info', {message: "Private key does not exist!", type: 'error'} callback?(new Error("Private key does not exist")) ) ) else callback?(null) (callback) => console.debug "Real Host Connect..." @connection = new ssh2() @connection.on 'error', (err) => @emitter.emit 'info', {message: "Error occured when connecting to sftp://#{@username}@#{@hostname}:#{@port}", type: 'error'} @connection?.end() callback?(err) @connection.on 'ready', => @emitter.emit 'info', {message: "Successfully connected to sftp://#{@username}@#{@hostname}:#{@port}", type: 'success'} callback?(null) # Here we break MV paradigm... but is the nature of the job... @connection.on 'keyboard-interactive', (name, instructions, instructionsLang, prompts, finish) -> # console.log('Connection :: keyboard-interactive') # console.log(prompts) async.waterfall([ (callback) -> passwordDialog = new Dialog({ prompt: "Keyboard Interactive Auth", detail: prompts[0].prompt.replace(/(?:\r\n|\r|\n)/g, '<br>') }) passwordDialog.toggle(callback) ], (err, result) => if err? callback?(err) else finish([result]) ) # Enable keepalive on the connection to keep firewalls and nat happy connectionOptions = _.extend({keepaliveInterval: 10000, keepaliveCountMax: 6}, connectionOptions) # Go do this... @connection.connect(@getConnectionString(connectionOptions)) ], (err) -> callback?(err) ) isConnected: -> @connection? and @connection._sock and @connection._sock.writable and @connection._sshstream and @connection._sshstream.writable getFilesMetadata: (path, callback) -> async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => # temp store in this so we can close it when we are done... @tmp_sftp = sftp sftp.readdir(path, callback) (files, callback) => # ... and now we are done! @tmp_sftp.end() async.map(files, ((file, callback) => callback?(null, @createRemoteFileFromFile(path, file))), callback) (objects, callback) -> objects.push(new RemoteFile((path + "/.."), false, true, false, null, null, null)) if atom.config.get 'remote-edit-ni.showHiddenFiles' callback?(null, objects) else async.filter(objects, ((item, callback) -> item.isHidden(callback)), ((result) -> callback?(null, result))) ], (err, result) => if err? @emitter.emit('info', {message: "Error occured when reading remote directory sftp://#{@username}@#{@hostname}:#{@port}:#{path}", type: 'error'} ) console.error err console.error err.code callback?(err) else callback?(err, (result.sort (a, b) -> return if a.name.toLowerCase() >= b.name.toLowerCase() then 1 else -1)) ) getFile: (localFile, callback) -> @emitter.emit('info', {message: "Getting remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'info'}) async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => sftp.fastGet(localFile.remoteFile.path, localFile.path, (err) => callback?(err, sftp)) ], (err, sftp) => @emitter.emit('info', {message: "Error when reading remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'error'}) if err? @emitter.emit('info', {message: "Successfully read remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'success'}) if !err? sftp?.end() callback?(err, localFile) ) writeFile: (localFile, callback) -> @emitter.emit 'info', {message: "Writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'info'} async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) -> @tmp_sftp = sftp sftp.fastPut(localFile.path, localFile.remoteFile.path, callback) (callback) -> @tmp_sftp.end() callback?() ], (err) => if err? @emitter.emit('info', {message: "Error occured when writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}<br/>#{err}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully wrote remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'success'}) callback?(err) ) serializeParams: -> tmp = if @password then @password else "" { @alias @hostname @directory @username @port localFiles: localFile.serialize() for localFile in @localFiles @useKeyboard @useAgent @usePrivateKey @usePassword password: new Buffer(tmp).toString("base64") @passphrase @privateKeyPath @lastOpenDirectory } deserializeParams: (params) -> tmpArray = [] tmpArray.push(LocalFile.deserialize(localFile, host: this)) for localFile in params.localFiles params.localFiles = tmpArray params.password = if params.password then new Buffer(params.password, "base64").toString("utf8") else "" params # Create the folder and call the callback. The callback will be called # for both error cases (1st arg) and success (2nd arg is the path) createFolder: (folderpath, callback) -> @emitter.emit 'info', {message: "Creating remote directory at sftp://#{@username}@#{@hostname}:#{@port}#{folderpath}", type: 'info'} async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) -> sftp.mkdir(folderpath, callback) sftp.end() callback?(null, folderpath) ], (err) => if err? @emitter.emit('info', {message: "Error occured while creating remote directory sftp://#{@username}@#{@hostname}:#{@port}#{folderpath}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully created directory sftp://#{@username}@#{@hostname}:#{@port}#{folderpath}", type: 'success'}) callback?(err) ) createFile: (filepath, callback) -> @emitter.emit 'info', {message: "Creating remote file at sftp://#{@username}@#{@hostname}:#{@port}#{filepath}", type: 'info'} async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => @tmp_sftp = sftp sftp.exists(filepath, callback) (callback) => @tmp_sftp.writeFile(filepath, "", callback) (callback) => @tmp_sftp.end() callback?() ], (err) => if err? if err == true @emitter.emit('info', {message: "Fle ftp://#{@username}@#{@hostname}:#{@port}#{filepath} already exists", type: 'error'}) else @emitter.emit('info', {message: "Error occurred while creating remote file ftp://#{@username}@#{@hostname}:#{@port}#{filepath}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully wrote remote file ftp://#{@username}@#{@hostname}:#{@port}#{filepath}", type: 'success'}) callback?(err) ) deleteFolderFile: (deletepath, isFolder, callback) -> async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => @tmp_sftp = sftp if isFolder sftp.rmdir(deletepath, callback) else sftp.unlink(deletepath, callback) (callback) => @tmp_sftp.end() callback?(null) ], (err) => if err? @emitter.emit('info', {message: "Error occurred when deleting remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{deletepath}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully deleted remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{deletepath}", type: 'success'}) callback?(err) ) renameFolderFile: (path, oldName, newName, isFolder, callback) => if oldName == newName @emitter.emit('info', {message: "The new name is same as the old", type: 'error'}) return oldPath = path + "/" + oldName newPath = path + "/" + newName @moveFolderFile(oldPath, newPath, isFolder, callback) moveFolderFile: (oldPath, newPath, isFolder, callback) => async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => @tmp_sftp = sftp if isFolder sftp.readdir(newPath, callback) else sftp.exists(newPath, callback) ], (err, result) => if (isFolder and result != undefined) or (!isFolder and err==true) @emitter.emit('info', {message: "#{if isFolder then 'Folder' else 'File'} already exists", type: 'error'}) @tmp_sftp.end() return async.waterfall([ (callback) => @tmp_sftp.rename(oldPath, newPath, callback) (callback) => @tmp_sftp.end() callback?() ], (err) => if err? @emitter.emit('info', {message: "Error occurred when renaming remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{oldPath}", type: 'error'}) console.error err if err? else @emitter.emit('info', {message: "Successfully renamed remote folder/file sftp://#{@username}@#{@hostname}:#{@port}#{oldPath}", type: 'success'}) callback?(err) ) ) setPermissions: (path, permissions, callback) => async.waterfall([ (callback) => @connection.sftp(callback) (sftp, callback) => @tmp_sftp = sftp sftp.chmod(path, permissions, callback) ], (err, result) => if err? @emitter.emit('info', {message: "Cannot set permissions to sftp://#{@username}@#{@hostname}:#{@port}#{path}", type: 'error'}) console.error err if err? @tmp_sftp.end() callback?(err) )
[ { "context": " subjectCache: 1\n quiz:\n invitationId: '502bfa73516bcb3c600003e9'\n workflowId: '502a70", "end": 1220, "score": 0.6278331279754639, "start": 1219, "tag": "KEY", "value": "5" }, { "context": " subjectCache: 1\n quiz:\n invitationId: '502bfa73516bcb3c600003e9'\n workflowId: '502a701e516bcb0001000002'\n\n ", "end": 1243, "score": 0.8115700483322144, "start": 1220, "tag": "PASSWORD", "value": "02bfa73516bcb3c600003e9" }, { "context": "'/proxy'\n surveys:\n candels:\n id: '50251c3b516bcb6ecb000001'\n workflowId: '5025", "end": 1437, "score": 0.5300339460372925, "start": 1436, "tag": "KEY", "value": "5" }, { "context": "251c3b516bcb6ecb000001'\n sloan:\n id: '50251c3b516bcb6ecb000002'\n workflowId: '5025", "end": 1536, "score": 0.6706946492195129, "start": 1535, "tag": "KEY", "value": "5" }, { "context": "516bcb6ecb000001'\n sloan:\n id: '50251c3b516bcb6ecb000002'\n workflowId: '50251c3b51", "end": 1542, "score": 0.5385072231292725, "start": 1541, "tag": "KEY", "value": "3" }, { "context": "6bcb6ecb000001'\n sloan:\n id: '50251c3b516bcb6ecb000002'\n workflowId: '50251c3b516bcb", "end": 1546, "score": 0.5744034647941589, "start": 1543, "tag": "KEY", "value": "516" }, { "context": "cb000001'\n sloan:\n id: '50251c3b516bcb6ecb000002'\n workflowId: '50251c3b516bcb6ecb", "end": 1550, "score": 0.5073504447937012, "start": 1549, "tag": "KEY", "value": "6" }, { "context": " subjectCache: 5\n quiz:\n invitationId: '502bfa73516bcb3c600003e9'\n workflowId: '502a701e516bcb0001000002'\n\n ", "end": 2578, "score": 0.7162412405014038, "start": 2554, "tag": "KEY", "value": "502bfa73516bcb3c600003e9" }, { "context": " subjectCache: 5\n quiz:\n invitationId: '502bfa73516bcb3c600003e9'\n workflowId: '502a701e516bcb0001000002'\n\n ", "end": 4327, "score": 0.9811443090438843, "start": 4303, "tag": "KEY", "value": "502bfa73516bcb3c600003e9" }, { "context": " subjectCache: 5\n quiz:\n invitationId: '502bfa73516bcb3c600003e9'\n workflowId: '502a701e516bcb0001000002'\n\nen", "end": 6228, "score": 0.964556097984314, "start": 6204, "tag": "KEY", "value": "502bfa73516bcb3c600003e9" } ]
app/lib/config.coffee
murraycu/Galaxy-Zoo
16
Config = test: quizzesActive: false apiHost: null surveys: candels: id: '50217561516bcb0fda00000d' workflowId: '50217499516bcb0fda000003' sloan: id: '50217561516bcb0fda00000e' workflowId: '50217499516bcb0fda000002' ukidss: id: '5244909c3ae7402d53000001' workflowId: '52449f803ae740540e000001' ferengi: id: '5249cbce3ae740728d000001' workflowId: '5249cbc33ae74070ed000001' candels_2epoch: id: '' workflowId: '50217499516bcb0fda000003' goods_full: id: '' workflowId: '' sloan_singleband: id: '' workflowId: '' decals: id: '' workflowId: '' gama09: id: '' workflowId: '' gama12: id: '' workflowId: '' gama15: id: '' workflowId: '' illustris: id: '' workflowId: '' decals_dr2: id: '' workflowId: '' sdss_lost_set: id: '' workflowId: '' ferengi_2: id: '' workflowId: '' missing_manga: id: '' workflowId: '' subjectCache: 1 quiz: invitationId: '502bfa73516bcb3c600003e9' workflowId: '502a701e516bcb0001000002' developmentLocal: quizzesActive: false apiHost: 'http://localhost:3000' apiPath: '/proxy' surveys: candels: id: '50251c3b516bcb6ecb000001' workflowId: '50251c3b516bcb6ecb000001' sloan: id: '50251c3b516bcb6ecb000002' workflowId: '50251c3b516bcb6ecb000002' ukidss: id: '5244909c3ae7402d53000001' workflowId: '52449f803ae740540e000001' ferengi: id: '5249cbce3ae740728d000001' workflowId: '5249cbc33ae74070ed000001' candels_2epoch: id: '' workflowId: '50217499516bcb0fda000003' goods_full: id: '' workflowId: '' sloan_singleband: id: '' workflowId: '' decals: id: '' workflowId: '' gama09: id: '' workflowId: '' gama12: id: '' workflowId: '' gama15: id: '' workflowId: '' illustris: id: '' workflowId: '' decals_dr2: id: '' workflowId: '' sdss_lost_set: id: '' workflowId: '' ferengi_2: id: '' workflowId: '' missing_manga: id: '' workflowId: '' subjectCache: 5 quiz: invitationId: '502bfa73516bcb3c600003e9' workflowId: '502a701e516bcb0001000002' developmentRemote: quizzesActive: false apiHost: 'https://dev.zooniverse.org' apiPath: '/proxy' surveys: candels: id: '50251c3b516bcb6ecb000001' workflowId: '50251c3b516bcb6ecb000001' sloan: id: '50251c3b516bcb6ecb000002' workflowId: '50251c3b516bcb6ecb000002' ukidss: id: '5244909c3ae7402d53000001' workflowId: '52449f803ae740540e000001' ferengi: id: '5249cbce3ae740728d000001' workflowId: '5249cbc33ae74070ed000001' candels_2epoch: id: '551456e02f0eef2535000001' workflowId: '5501b09e7b9f9931d4000002' goods_full: id: '551453e12f0eef21f2000001' workflowId: '5501aef27b9f992e7c000002' sloan_singleband: id: '5514521e2f0eef2012000001' workflowId: '5501a9be7b9f992679000001' decals: id: '55db7cf01766276e7b000001' workflowId: '50251c3b516bcb6ecb000002' gama09: id: '' workflowId: '' gama12: id: '' workflowId: '' gama15: id: '' workflowId: '' illustris: id: '55db71251766276613000001' workflowId: '50251c3b516bcb6ecb000002' decals_dr2: id: '56f3d4645925d95984000001' workflowId: '55db7cf01766276e7b000002' sdss_lost_set: id: '56f2b5ed5925d9004200c775' workflowId: '50251c3b516bcb6ecb000002' ferengi_2: id: '58417dcb9afc3a007d000001' workflowId: '5249cbc33ae74070ed000001' missing_manga: id: '5894999f7d25c7236f000001' workflowId: '50251c3b516bcb6ecb000002' subjectCache: 5 quiz: invitationId: '502bfa73516bcb3c600003e9' workflowId: '502a701e516bcb0001000002' production: quizzesActive: false apiHost: 'https://www.galaxyzoo.org' apiPath: '/_ouroboros_api/proxy' surveys: candels: id: '50251c3b516bcb6ecb000001' workflowId: '50251c3b516bcb6ecb000001' sloan: id: '50251c3b516bcb6ecb000002' workflowId: '50251c3b516bcb6ecb000002' ukidss: id: '5244909c3ae7402d53000001' workflowId: '52449f803ae740540e000001' ferengi: id: '5249cbce3ae740728d000001' workflowId: '5249cbc33ae74070ed000001' candels_2epoch: id: '551456e02f0eef2535000001' workflowId: '551456e02f0eef2535000002' goods_full: id: '551453e12f0eef21f2000001' workflowId: '551453e12f0eef21f2000002' sloan_singleband: id: '5514521e2f0eef2012000001' workflowId: '5514521f2f0eef2012000002' decals: id: '55db7cf01766276e7b000001' workflowId: '55db7cf01766276e7b000002' gama09: id: '5853fa7b95ad361930000001' workflowId: '5857c2bb95ad365e69000690' gama12: id: '5853faaf95ad361930000002' workflowId: '5857df7c95ad364bc30009a3' gama15: id: '5853fab395ad361930000003' workflowId: '58580c8295ad362a4a0001fa' illustris: id: '55db71251766276613000001' workflowId: '55db71251766276613000002' decals_dr2: id: '56f3d4645925d95984000001' workflowId: '55db7cf01766276e7b000002' sdss_lost_set: id: '56f2b5ed5925d9004200c775' workflowId: '50251c3b516bcb6ecb000002' ferengi_2: id: '58417dcb9afc3a007d000001' workflowId: '5249cbc33ae74070ed000001' missing_manga: id: '5894999f7d25c7236f000001' workflowId: '50251c3b516bcb6ecb000002' subjectCache: 5 quiz: invitationId: '502bfa73516bcb3c600003e9' workflowId: '502a701e516bcb0001000002' env = if window.location.port > 1024 || !!location.href.match /localhost|demo|preview|beta/ 'developmentRemote' else 'production' module.exports = Config[env]
130531
Config = test: quizzesActive: false apiHost: null surveys: candels: id: '50217561516bcb0fda00000d' workflowId: '50217499516bcb0fda000003' sloan: id: '50217561516bcb0fda00000e' workflowId: '50217499516bcb0fda000002' ukidss: id: '5244909c3ae7402d53000001' workflowId: '52449f803ae740540e000001' ferengi: id: '5249cbce3ae740728d000001' workflowId: '5249cbc33ae74070ed000001' candels_2epoch: id: '' workflowId: '50217499516bcb0fda000003' goods_full: id: '' workflowId: '' sloan_singleband: id: '' workflowId: '' decals: id: '' workflowId: '' gama09: id: '' workflowId: '' gama12: id: '' workflowId: '' gama15: id: '' workflowId: '' illustris: id: '' workflowId: '' decals_dr2: id: '' workflowId: '' sdss_lost_set: id: '' workflowId: '' ferengi_2: id: '' workflowId: '' missing_manga: id: '' workflowId: '' subjectCache: 1 quiz: invitationId: '<KEY> <PASSWORD>' workflowId: '502a701e516bcb0001000002' developmentLocal: quizzesActive: false apiHost: 'http://localhost:3000' apiPath: '/proxy' surveys: candels: id: '<KEY>0251c3b516bcb6ecb000001' workflowId: '50251c3b516bcb6ecb000001' sloan: id: '<KEY>0251c<KEY>b<KEY>bcb<KEY>ecb000002' workflowId: '50251c3b516bcb6ecb000002' ukidss: id: '5244909c3ae7402d53000001' workflowId: '52449f803ae740540e000001' ferengi: id: '5249cbce3ae740728d000001' workflowId: '5249cbc33ae74070ed000001' candels_2epoch: id: '' workflowId: '50217499516bcb0fda000003' goods_full: id: '' workflowId: '' sloan_singleband: id: '' workflowId: '' decals: id: '' workflowId: '' gama09: id: '' workflowId: '' gama12: id: '' workflowId: '' gama15: id: '' workflowId: '' illustris: id: '' workflowId: '' decals_dr2: id: '' workflowId: '' sdss_lost_set: id: '' workflowId: '' ferengi_2: id: '' workflowId: '' missing_manga: id: '' workflowId: '' subjectCache: 5 quiz: invitationId: '<KEY>' workflowId: '502a701e516bcb0001000002' developmentRemote: quizzesActive: false apiHost: 'https://dev.zooniverse.org' apiPath: '/proxy' surveys: candels: id: '50251c3b516bcb6ecb000001' workflowId: '50251c3b516bcb6ecb000001' sloan: id: '50251c3b516bcb6ecb000002' workflowId: '50251c3b516bcb6ecb000002' ukidss: id: '5244909c3ae7402d53000001' workflowId: '52449f803ae740540e000001' ferengi: id: '5249cbce3ae740728d000001' workflowId: '5249cbc33ae74070ed000001' candels_2epoch: id: '551456e02f0eef2535000001' workflowId: '5501b09e7b9f9931d4000002' goods_full: id: '551453e12f0eef21f2000001' workflowId: '5501aef27b9f992e7c000002' sloan_singleband: id: '5514521e2f0eef2012000001' workflowId: '5501a9be7b9f992679000001' decals: id: '55db7cf01766276e7b000001' workflowId: '50251c3b516bcb6ecb000002' gama09: id: '' workflowId: '' gama12: id: '' workflowId: '' gama15: id: '' workflowId: '' illustris: id: '55db71251766276613000001' workflowId: '50251c3b516bcb6ecb000002' decals_dr2: id: '56f3d4645925d95984000001' workflowId: '55db7cf01766276e7b000002' sdss_lost_set: id: '56f2b5ed5925d9004200c775' workflowId: '50251c3b516bcb6ecb000002' ferengi_2: id: '58417dcb9afc3a007d000001' workflowId: '5249cbc33ae74070ed000001' missing_manga: id: '5894999f7d25c7236f000001' workflowId: '50251c3b516bcb6ecb000002' subjectCache: 5 quiz: invitationId: '<KEY>' workflowId: '502a701e516bcb0001000002' production: quizzesActive: false apiHost: 'https://www.galaxyzoo.org' apiPath: '/_ouroboros_api/proxy' surveys: candels: id: '50251c3b516bcb6ecb000001' workflowId: '50251c3b516bcb6ecb000001' sloan: id: '50251c3b516bcb6ecb000002' workflowId: '50251c3b516bcb6ecb000002' ukidss: id: '5244909c3ae7402d53000001' workflowId: '52449f803ae740540e000001' ferengi: id: '5249cbce3ae740728d000001' workflowId: '5249cbc33ae74070ed000001' candels_2epoch: id: '551456e02f0eef2535000001' workflowId: '551456e02f0eef2535000002' goods_full: id: '551453e12f0eef21f2000001' workflowId: '551453e12f0eef21f2000002' sloan_singleband: id: '5514521e2f0eef2012000001' workflowId: '5514521f2f0eef2012000002' decals: id: '55db7cf01766276e7b000001' workflowId: '55db7cf01766276e7b000002' gama09: id: '5853fa7b95ad361930000001' workflowId: '5857c2bb95ad365e69000690' gama12: id: '5853faaf95ad361930000002' workflowId: '5857df7c95ad364bc30009a3' gama15: id: '5853fab395ad361930000003' workflowId: '58580c8295ad362a4a0001fa' illustris: id: '55db71251766276613000001' workflowId: '55db71251766276613000002' decals_dr2: id: '56f3d4645925d95984000001' workflowId: '55db7cf01766276e7b000002' sdss_lost_set: id: '56f2b5ed5925d9004200c775' workflowId: '50251c3b516bcb6ecb000002' ferengi_2: id: '58417dcb9afc3a007d000001' workflowId: '5249cbc33ae74070ed000001' missing_manga: id: '5894999f7d25c7236f000001' workflowId: '50251c3b516bcb6ecb000002' subjectCache: 5 quiz: invitationId: '<KEY>' workflowId: '502a701e516bcb0001000002' env = if window.location.port > 1024 || !!location.href.match /localhost|demo|preview|beta/ 'developmentRemote' else 'production' module.exports = Config[env]
true
Config = test: quizzesActive: false apiHost: null surveys: candels: id: '50217561516bcb0fda00000d' workflowId: '50217499516bcb0fda000003' sloan: id: '50217561516bcb0fda00000e' workflowId: '50217499516bcb0fda000002' ukidss: id: '5244909c3ae7402d53000001' workflowId: '52449f803ae740540e000001' ferengi: id: '5249cbce3ae740728d000001' workflowId: '5249cbc33ae74070ed000001' candels_2epoch: id: '' workflowId: '50217499516bcb0fda000003' goods_full: id: '' workflowId: '' sloan_singleband: id: '' workflowId: '' decals: id: '' workflowId: '' gama09: id: '' workflowId: '' gama12: id: '' workflowId: '' gama15: id: '' workflowId: '' illustris: id: '' workflowId: '' decals_dr2: id: '' workflowId: '' sdss_lost_set: id: '' workflowId: '' ferengi_2: id: '' workflowId: '' missing_manga: id: '' workflowId: '' subjectCache: 1 quiz: invitationId: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI' workflowId: '502a701e516bcb0001000002' developmentLocal: quizzesActive: false apiHost: 'http://localhost:3000' apiPath: '/proxy' surveys: candels: id: 'PI:KEY:<KEY>END_PI0251c3b516bcb6ecb000001' workflowId: '50251c3b516bcb6ecb000001' sloan: id: 'PI:KEY:<KEY>END_PI0251cPI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PIbcbPI:KEY:<KEY>END_PIecb000002' workflowId: '50251c3b516bcb6ecb000002' ukidss: id: '5244909c3ae7402d53000001' workflowId: '52449f803ae740540e000001' ferengi: id: '5249cbce3ae740728d000001' workflowId: '5249cbc33ae74070ed000001' candels_2epoch: id: '' workflowId: '50217499516bcb0fda000003' goods_full: id: '' workflowId: '' sloan_singleband: id: '' workflowId: '' decals: id: '' workflowId: '' gama09: id: '' workflowId: '' gama12: id: '' workflowId: '' gama15: id: '' workflowId: '' illustris: id: '' workflowId: '' decals_dr2: id: '' workflowId: '' sdss_lost_set: id: '' workflowId: '' ferengi_2: id: '' workflowId: '' missing_manga: id: '' workflowId: '' subjectCache: 5 quiz: invitationId: 'PI:KEY:<KEY>END_PI' workflowId: '502a701e516bcb0001000002' developmentRemote: quizzesActive: false apiHost: 'https://dev.zooniverse.org' apiPath: '/proxy' surveys: candels: id: '50251c3b516bcb6ecb000001' workflowId: '50251c3b516bcb6ecb000001' sloan: id: '50251c3b516bcb6ecb000002' workflowId: '50251c3b516bcb6ecb000002' ukidss: id: '5244909c3ae7402d53000001' workflowId: '52449f803ae740540e000001' ferengi: id: '5249cbce3ae740728d000001' workflowId: '5249cbc33ae74070ed000001' candels_2epoch: id: '551456e02f0eef2535000001' workflowId: '5501b09e7b9f9931d4000002' goods_full: id: '551453e12f0eef21f2000001' workflowId: '5501aef27b9f992e7c000002' sloan_singleband: id: '5514521e2f0eef2012000001' workflowId: '5501a9be7b9f992679000001' decals: id: '55db7cf01766276e7b000001' workflowId: '50251c3b516bcb6ecb000002' gama09: id: '' workflowId: '' gama12: id: '' workflowId: '' gama15: id: '' workflowId: '' illustris: id: '55db71251766276613000001' workflowId: '50251c3b516bcb6ecb000002' decals_dr2: id: '56f3d4645925d95984000001' workflowId: '55db7cf01766276e7b000002' sdss_lost_set: id: '56f2b5ed5925d9004200c775' workflowId: '50251c3b516bcb6ecb000002' ferengi_2: id: '58417dcb9afc3a007d000001' workflowId: '5249cbc33ae74070ed000001' missing_manga: id: '5894999f7d25c7236f000001' workflowId: '50251c3b516bcb6ecb000002' subjectCache: 5 quiz: invitationId: 'PI:KEY:<KEY>END_PI' workflowId: '502a701e516bcb0001000002' production: quizzesActive: false apiHost: 'https://www.galaxyzoo.org' apiPath: '/_ouroboros_api/proxy' surveys: candels: id: '50251c3b516bcb6ecb000001' workflowId: '50251c3b516bcb6ecb000001' sloan: id: '50251c3b516bcb6ecb000002' workflowId: '50251c3b516bcb6ecb000002' ukidss: id: '5244909c3ae7402d53000001' workflowId: '52449f803ae740540e000001' ferengi: id: '5249cbce3ae740728d000001' workflowId: '5249cbc33ae74070ed000001' candels_2epoch: id: '551456e02f0eef2535000001' workflowId: '551456e02f0eef2535000002' goods_full: id: '551453e12f0eef21f2000001' workflowId: '551453e12f0eef21f2000002' sloan_singleband: id: '5514521e2f0eef2012000001' workflowId: '5514521f2f0eef2012000002' decals: id: '55db7cf01766276e7b000001' workflowId: '55db7cf01766276e7b000002' gama09: id: '5853fa7b95ad361930000001' workflowId: '5857c2bb95ad365e69000690' gama12: id: '5853faaf95ad361930000002' workflowId: '5857df7c95ad364bc30009a3' gama15: id: '5853fab395ad361930000003' workflowId: '58580c8295ad362a4a0001fa' illustris: id: '55db71251766276613000001' workflowId: '55db71251766276613000002' decals_dr2: id: '56f3d4645925d95984000001' workflowId: '55db7cf01766276e7b000002' sdss_lost_set: id: '56f2b5ed5925d9004200c775' workflowId: '50251c3b516bcb6ecb000002' ferengi_2: id: '58417dcb9afc3a007d000001' workflowId: '5249cbc33ae74070ed000001' missing_manga: id: '5894999f7d25c7236f000001' workflowId: '50251c3b516bcb6ecb000002' subjectCache: 5 quiz: invitationId: 'PI:KEY:<KEY>END_PI' workflowId: '502a701e516bcb0001000002' env = if window.location.port > 1024 || !!location.href.match /localhost|demo|preview|beta/ 'developmentRemote' else 'production' module.exports = Config[env]
[ { "context": "Hello world wbox\"\n\n $scope.user =\n name: \"Wbox\"\n phone: \"12312312\"\n\n $scope.click = -", "end": 157, "score": 0.5139504075050354, "start": 156, "tag": "NAME", "value": "W" }, { "context": "ello world wbox\"\n\n $scope.user =\n name: \"Wbox\"\n phone: \"12312312\"\n\n $scope.click = ->\n ", "end": 160, "score": 0.7658049464225769, "start": 157, "tag": "USERNAME", "value": "box" } ]
app/assets/javascripts/wbox/controllers.coffee
arakcheev/console
0
define ['./services'], (services)-> "use strict" WboxCtrl = ($scope,WboxFactory) -> console.log "Hello world wbox" $scope.user = name: "Wbox" phone: "12312312" $scope.click = -> WboxFactory.getUser().then( (data) => console.debug "Promise returned #{data}" , (error) => console.error "Error : #{error}" ) $scope.user.name = "Click John by Wbox" WboxCtrl.$inject = [ "$scope", "WboxFactory" ] RepoController = ($scope,Repository) -> RepoController.$inject = [ "$scope" "Repository" ] WboxCtrl: WboxCtrl RepoCtrl: RepoController
12852
define ['./services'], (services)-> "use strict" WboxCtrl = ($scope,WboxFactory) -> console.log "Hello world wbox" $scope.user = name: "<NAME>box" phone: "12312312" $scope.click = -> WboxFactory.getUser().then( (data) => console.debug "Promise returned #{data}" , (error) => console.error "Error : #{error}" ) $scope.user.name = "Click John by Wbox" WboxCtrl.$inject = [ "$scope", "WboxFactory" ] RepoController = ($scope,Repository) -> RepoController.$inject = [ "$scope" "Repository" ] WboxCtrl: WboxCtrl RepoCtrl: RepoController
true
define ['./services'], (services)-> "use strict" WboxCtrl = ($scope,WboxFactory) -> console.log "Hello world wbox" $scope.user = name: "PI:NAME:<NAME>END_PIbox" phone: "12312312" $scope.click = -> WboxFactory.getUser().then( (data) => console.debug "Promise returned #{data}" , (error) => console.error "Error : #{error}" ) $scope.user.name = "Click John by Wbox" WboxCtrl.$inject = [ "$scope", "WboxFactory" ] RepoController = ($scope,Repository) -> RepoController.$inject = [ "$scope" "Repository" ] WboxCtrl: WboxCtrl RepoCtrl: RepoController
[ { "context": "###\nThe MIT License (MIT)\n\nCopyright (c) 2013 Michael Bertolacci\n\nPermission is hereby granted, free of charge, to", "end": 64, "score": 0.9997471570968628, "start": 46, "tag": "NAME", "value": "Michael Bertolacci" }, { "context": "e for this service is <a href=\"https://github.com/mbertolacci/lorem-rss\">available on GitHub</a>.\n ", "end": 3481, "score": 0.9996591210365295, "start": 3470, "tag": "USERNAME", "value": "mbertolacci" }, { "context": "ivecommons.org/ns#\" property=\"cc:attributionName\">Michael Bertolacci</span> are licensed under a <a rel=\"license\" href", "end": 6090, "score": 0.9997125864028931, "start": 6072, "tag": "NAME", "value": "Michael Bertolacci" }, { "context": "e_url: 'http://example.com/',\n copyright: 'Michael Bertolacci, licensed under a Creative Commons Attribution 3.", "end": 7129, "score": 0.9998094439506531, "start": 7111, "tag": "NAME", "value": "Michael Bertolacci" }, { "context": "test/#{pubDate.format('X')}\"\n author: 'Delzon Perez',\n date: pubDate.clone().toDate()\n ", "end": 7666, "score": 0.9999019503593445, "start": 7654, "tag": "NAME", "value": "Delzon Perez" } ]
web.coffee
Delzon/lorem-rss-with-images
1
### The MIT License (MIT) Copyright (c) 2013 Michael Bertolacci Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### express = require 'express' RSS = require 'rss' moment = require 'moment' _ = require 'lodash' morgan = require 'morgan' loremIpsum = require 'lorem-ipsum' seedRandom = require 'seed-random' crypto = require 'crypto' app = express() app.use morgan('combined') units = { second: { nextUp: 'minute', mustDivide: 60 } minute: { nextUp: 'hour' mustDivide: 60 } hour: { nextUp: 'day' mustDivide: 24 } day: { nextUp: 'year' mustDivide: 1 } month: { nextUp: 'year' mustDivide: 12 } year: { mustDivide: 1 } } getNearest = (interval, unit) -> if interval == 1 return moment().utc().startOf(unit) else unitOptions = units[unit] if unitOptions.mustDivide % interval != 0 throw "When using #{unit}s the interval must divide #{unitOptions.mustDivide}" now = moment().utc() returnDate = now.clone().startOf(unitOptions.nextUp || unit) returnDate[unit](now[unit]() - now[unit]() % interval) return returnDate app.get '/', (request, response) -> response.send """ <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Lorem RSS</title> <meta name="description" content="Web service that generates lorem ipsum RSS feeds"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.2.3/css/normalize.min.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.2.3/css/foundation.min.css"> <style type="text/css"> ul.indent { position: relative; left: 20px; } </style> </head> <body> <div class="row"> <div class="large-12 columns"> <h1>Lorem RSS</h1> <p> Generates RSS feeds with content updated at regular intervals. I wrote this to answer a <a href="http://stackoverflow.com/questions/18202048/are-there-any-constantly-updating-rss-feed-services-to-use-for-testing-or-just">question I asked on Stack Overflow</a>. </p> <p> The code for this service is <a href="https://github.com/mbertolacci/lorem-rss">available on GitHub</a>. </p> <h2>API</h2> <p> Visit <a href="/feed">/feed</a>, with the following optional parameters: </p> <ul class="disc indent"> <li> <em>unit</em>: one of second, minute, day, month, or year </li> <li> <em>interval</em>: an integer to repeat the units at. For seconds and minutes this interval must evenly divide 60, for month it must evenly divide 12, and for day and year it can only be 1. </li> </ul> <h2>Examples</h2> <ul class="disc indent"> <li> The default, updates once a minute: <a href="/feed">/feed</a> </li> <li> Update every second instead of minute: <a href="/feed?unit=second">/feed?unit=second</a> </li> <li> Update every 30 seconds: <a href="/feed?unit=second&interval=30">/feed?unit=second&interval=30</a> </li> <li> Update once a day: <a href="/feed?unit=day">/feed?unit=day</a> </li> <li> Update every 6 months: <a href="/feed?unit=month&interval=6">/feed?unit=month&interval=6</a> </li> <li> Update once a year: <a href="/feed?unit=year">/feed?unit=year</a> </li> <li> <strong>Invalid example:</strong> update every 7 minutes (does not evenly divide 60): <a href="/feed?unit=minute&interval=7">/feed?unit=minute&interval=7</a> </li> </ul> <hr/> <p class="copyright"> <a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/3.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/Text" property="dct:title" rel="dct:type">Lorem RSS</span> (this page and the feeds generated) by <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName">Michael Bertolacci</span> are licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US">Creative Commons Attribution 3.0 Unported License</a>. </p> </div> </div> </body> </html> """ app.get '/feed', (request, response) -> if request.query.interval? interval = parseInt request.query.interval else interval = 1 if not interval response.send(500, "Interval must be an integer") return if interval <= 0 response.send(500, "Interval must be greater than 0") return unit = request.query.unit || 'minute' if not units[unit] response.send(500, "Unit must be one of #{_.keys(units).join(', ')}") return pubDate = getNearest(interval, unit) feed = new RSS({ title: "Lorem ipsum feed for an interval of #{interval} #{unit}s", description: 'This is a constantly updating lorem ipsum feed' site_url: 'http://example.com/', copyright: 'Michael Bertolacci, licensed under a Creative Commons Attribution 3.0 Unported License.', ttl: Math.ceil(moment.duration(interval, unit).asMinutes()), pubDate: pubDate.clone().toDate() }) pubDate = getNearest(interval, unit) for i in [0...10] feed.item { title: "Lorem ipsum #{pubDate.format()}", description: "Holi"+loremIpsum( random: seedRandom(pubDate.unix()) ) url: "http://example.com/test/#{pubDate.format('X')}" author: 'Delzon Perez', date: pubDate.clone().toDate() } pubDate = pubDate.subtract(interval, unit) etagString = feed.pubDate + interval + unit response.set 'Content-Type', 'application/rss+xml' response.set 'ETag', "\"#{crypto.createHash('md5').update(etagString).digest("hex");}\"" response.send feed.xml() port = process.env.PORT || 5000; app.listen port, () -> console.log("Listening on " + port);
221722
### The MIT License (MIT) Copyright (c) 2013 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### express = require 'express' RSS = require 'rss' moment = require 'moment' _ = require 'lodash' morgan = require 'morgan' loremIpsum = require 'lorem-ipsum' seedRandom = require 'seed-random' crypto = require 'crypto' app = express() app.use morgan('combined') units = { second: { nextUp: 'minute', mustDivide: 60 } minute: { nextUp: 'hour' mustDivide: 60 } hour: { nextUp: 'day' mustDivide: 24 } day: { nextUp: 'year' mustDivide: 1 } month: { nextUp: 'year' mustDivide: 12 } year: { mustDivide: 1 } } getNearest = (interval, unit) -> if interval == 1 return moment().utc().startOf(unit) else unitOptions = units[unit] if unitOptions.mustDivide % interval != 0 throw "When using #{unit}s the interval must divide #{unitOptions.mustDivide}" now = moment().utc() returnDate = now.clone().startOf(unitOptions.nextUp || unit) returnDate[unit](now[unit]() - now[unit]() % interval) return returnDate app.get '/', (request, response) -> response.send """ <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Lorem RSS</title> <meta name="description" content="Web service that generates lorem ipsum RSS feeds"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.2.3/css/normalize.min.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.2.3/css/foundation.min.css"> <style type="text/css"> ul.indent { position: relative; left: 20px; } </style> </head> <body> <div class="row"> <div class="large-12 columns"> <h1>Lorem RSS</h1> <p> Generates RSS feeds with content updated at regular intervals. I wrote this to answer a <a href="http://stackoverflow.com/questions/18202048/are-there-any-constantly-updating-rss-feed-services-to-use-for-testing-or-just">question I asked on Stack Overflow</a>. </p> <p> The code for this service is <a href="https://github.com/mbertolacci/lorem-rss">available on GitHub</a>. </p> <h2>API</h2> <p> Visit <a href="/feed">/feed</a>, with the following optional parameters: </p> <ul class="disc indent"> <li> <em>unit</em>: one of second, minute, day, month, or year </li> <li> <em>interval</em>: an integer to repeat the units at. For seconds and minutes this interval must evenly divide 60, for month it must evenly divide 12, and for day and year it can only be 1. </li> </ul> <h2>Examples</h2> <ul class="disc indent"> <li> The default, updates once a minute: <a href="/feed">/feed</a> </li> <li> Update every second instead of minute: <a href="/feed?unit=second">/feed?unit=second</a> </li> <li> Update every 30 seconds: <a href="/feed?unit=second&interval=30">/feed?unit=second&interval=30</a> </li> <li> Update once a day: <a href="/feed?unit=day">/feed?unit=day</a> </li> <li> Update every 6 months: <a href="/feed?unit=month&interval=6">/feed?unit=month&interval=6</a> </li> <li> Update once a year: <a href="/feed?unit=year">/feed?unit=year</a> </li> <li> <strong>Invalid example:</strong> update every 7 minutes (does not evenly divide 60): <a href="/feed?unit=minute&interval=7">/feed?unit=minute&interval=7</a> </li> </ul> <hr/> <p class="copyright"> <a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/3.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/Text" property="dct:title" rel="dct:type">Lorem RSS</span> (this page and the feeds generated) by <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName"><NAME></span> are licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US">Creative Commons Attribution 3.0 Unported License</a>. </p> </div> </div> </body> </html> """ app.get '/feed', (request, response) -> if request.query.interval? interval = parseInt request.query.interval else interval = 1 if not interval response.send(500, "Interval must be an integer") return if interval <= 0 response.send(500, "Interval must be greater than 0") return unit = request.query.unit || 'minute' if not units[unit] response.send(500, "Unit must be one of #{_.keys(units).join(', ')}") return pubDate = getNearest(interval, unit) feed = new RSS({ title: "Lorem ipsum feed for an interval of #{interval} #{unit}s", description: 'This is a constantly updating lorem ipsum feed' site_url: 'http://example.com/', copyright: '<NAME>, licensed under a Creative Commons Attribution 3.0 Unported License.', ttl: Math.ceil(moment.duration(interval, unit).asMinutes()), pubDate: pubDate.clone().toDate() }) pubDate = getNearest(interval, unit) for i in [0...10] feed.item { title: "Lorem ipsum #{pubDate.format()}", description: "Holi"+loremIpsum( random: seedRandom(pubDate.unix()) ) url: "http://example.com/test/#{pubDate.format('X')}" author: '<NAME>', date: pubDate.clone().toDate() } pubDate = pubDate.subtract(interval, unit) etagString = feed.pubDate + interval + unit response.set 'Content-Type', 'application/rss+xml' response.set 'ETag', "\"#{crypto.createHash('md5').update(etagString).digest("hex");}\"" response.send feed.xml() port = process.env.PORT || 5000; app.listen port, () -> console.log("Listening on " + port);
true
### The MIT License (MIT) Copyright (c) 2013 PI:NAME:<NAME>END_PI Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### express = require 'express' RSS = require 'rss' moment = require 'moment' _ = require 'lodash' morgan = require 'morgan' loremIpsum = require 'lorem-ipsum' seedRandom = require 'seed-random' crypto = require 'crypto' app = express() app.use morgan('combined') units = { second: { nextUp: 'minute', mustDivide: 60 } minute: { nextUp: 'hour' mustDivide: 60 } hour: { nextUp: 'day' mustDivide: 24 } day: { nextUp: 'year' mustDivide: 1 } month: { nextUp: 'year' mustDivide: 12 } year: { mustDivide: 1 } } getNearest = (interval, unit) -> if interval == 1 return moment().utc().startOf(unit) else unitOptions = units[unit] if unitOptions.mustDivide % interval != 0 throw "When using #{unit}s the interval must divide #{unitOptions.mustDivide}" now = moment().utc() returnDate = now.clone().startOf(unitOptions.nextUp || unit) returnDate[unit](now[unit]() - now[unit]() % interval) return returnDate app.get '/', (request, response) -> response.send """ <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Lorem RSS</title> <meta name="description" content="Web service that generates lorem ipsum RSS feeds"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.2.3/css/normalize.min.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.2.3/css/foundation.min.css"> <style type="text/css"> ul.indent { position: relative; left: 20px; } </style> </head> <body> <div class="row"> <div class="large-12 columns"> <h1>Lorem RSS</h1> <p> Generates RSS feeds with content updated at regular intervals. I wrote this to answer a <a href="http://stackoverflow.com/questions/18202048/are-there-any-constantly-updating-rss-feed-services-to-use-for-testing-or-just">question I asked on Stack Overflow</a>. </p> <p> The code for this service is <a href="https://github.com/mbertolacci/lorem-rss">available on GitHub</a>. </p> <h2>API</h2> <p> Visit <a href="/feed">/feed</a>, with the following optional parameters: </p> <ul class="disc indent"> <li> <em>unit</em>: one of second, minute, day, month, or year </li> <li> <em>interval</em>: an integer to repeat the units at. For seconds and minutes this interval must evenly divide 60, for month it must evenly divide 12, and for day and year it can only be 1. </li> </ul> <h2>Examples</h2> <ul class="disc indent"> <li> The default, updates once a minute: <a href="/feed">/feed</a> </li> <li> Update every second instead of minute: <a href="/feed?unit=second">/feed?unit=second</a> </li> <li> Update every 30 seconds: <a href="/feed?unit=second&interval=30">/feed?unit=second&interval=30</a> </li> <li> Update once a day: <a href="/feed?unit=day">/feed?unit=day</a> </li> <li> Update every 6 months: <a href="/feed?unit=month&interval=6">/feed?unit=month&interval=6</a> </li> <li> Update once a year: <a href="/feed?unit=year">/feed?unit=year</a> </li> <li> <strong>Invalid example:</strong> update every 7 minutes (does not evenly divide 60): <a href="/feed?unit=minute&interval=7">/feed?unit=minute&interval=7</a> </li> </ul> <hr/> <p class="copyright"> <a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/3.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/Text" property="dct:title" rel="dct:type">Lorem RSS</span> (this page and the feeds generated) by <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName">PI:NAME:<NAME>END_PI</span> are licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US">Creative Commons Attribution 3.0 Unported License</a>. </p> </div> </div> </body> </html> """ app.get '/feed', (request, response) -> if request.query.interval? interval = parseInt request.query.interval else interval = 1 if not interval response.send(500, "Interval must be an integer") return if interval <= 0 response.send(500, "Interval must be greater than 0") return unit = request.query.unit || 'minute' if not units[unit] response.send(500, "Unit must be one of #{_.keys(units).join(', ')}") return pubDate = getNearest(interval, unit) feed = new RSS({ title: "Lorem ipsum feed for an interval of #{interval} #{unit}s", description: 'This is a constantly updating lorem ipsum feed' site_url: 'http://example.com/', copyright: 'PI:NAME:<NAME>END_PI, licensed under a Creative Commons Attribution 3.0 Unported License.', ttl: Math.ceil(moment.duration(interval, unit).asMinutes()), pubDate: pubDate.clone().toDate() }) pubDate = getNearest(interval, unit) for i in [0...10] feed.item { title: "Lorem ipsum #{pubDate.format()}", description: "Holi"+loremIpsum( random: seedRandom(pubDate.unix()) ) url: "http://example.com/test/#{pubDate.format('X')}" author: 'PI:NAME:<NAME>END_PI', date: pubDate.clone().toDate() } pubDate = pubDate.subtract(interval, unit) etagString = feed.pubDate + interval + unit response.set 'Content-Type', 'application/rss+xml' response.set 'ETag', "\"#{crypto.createHash('md5').update(etagString).digest("hex");}\"" response.send feed.xml() port = process.env.PORT || 5000; app.listen port, () -> console.log("Listening on " + port);
[ { "context": " Component _.extend {}, @props,\n key: \"edit-group-#{key}\"\n onUpdate: @onUpdate\n DOM.", "end": 1929, "score": 0.9929641485214233, "start": 1916, "tag": "KEY", "value": "edit-group-#{" }, { "context": "end {}, @props,\n key: \"edit-group-#{key}\"\n onUpdate: @onUpdate\n DOM.h3 nu", "end": 1932, "score": 0.7767367362976074, "start": 1932, "tag": "KEY", "value": "" }, { "context": " props = _.extend {}, @props,\n key: \"group-#{@props.group._id}-#{identity._id}\"\n iden", "end": 2609, "score": 0.8820306062698364, "start": 2600, "tag": "KEY", "value": "group-#{@" }, { "context": "tend {}, @props,\n key: \"group-#{@props.group._id}-#{identity._id}\"\n identity: identity\n ContactC", "end": 2642, "score": 0.9491762518882751, "start": 2615, "tag": "KEY", "value": "group._id}-#{identity._id}\"" } ]
src/components/edit.coffee
brianshaler/kerplunk-group
0
_ = require 'lodash' React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass getInitialState: -> group: @props.group identities: @props.group.identities identityToAdd: null selectIdentityToAdd: (identity) -> @setState identityToAdd: identity addIdentity: (e) -> e.preventDefault() groupId = @props.group._id identityId = @state.identityToAdd._id url = "/admin/groups/#{groupId}/add/#{identityId}.json" @props.request.post url, {}, (err, data) => console.log err if err newState = identityToAdd: {} if data.group newState.group = data.group if data.group.identities newState.identities = data.group.identities @setState newState removeIdentity: (identityId) -> (e) => e.preventDefault() groupId = @props.group._id url = "/admin/groups/#{groupId}/remove/#{identityId}.json" @props.request.post url, {}, (err, data) => console.log err if err newState = {} if data.group newState.group = data.group if data.group.identities newState.identities = data.group.identities @setState newState onUpdate: (obj) -> @setState obj render: -> identityInputPath = 'kerplunk-identity-autocomplete:input' IdentityInputComponent = @props.getComponent identityInputPath identityConfig = @props.globals.public.identity cardComponentPath = identityConfig.contactCardComponent ? identityConfig.defaultContactCard ContactCard = @props.getComponent cardComponentPath DOM.section className: 'content' , DOM.h3 null, @props.group.name DOM.div null, _.map (@props.globals.public.editGroupComponents ? {}), (componentPath, key) => Component = @props.getComponent componentPath Component _.extend {}, @props, key: "edit-group-#{key}" onUpdate: @onUpdate DOM.h3 null, 'Add Contacts' IdentityInputComponent _.extend {}, @props, onSelect: @selectIdentityToAdd identity: @state.identityToAdd omit: _.map @state.identities, '_id' if @state.identityToAdd DOM.a href: '#' onClick: @addIdentity className: 'btn btn-success' , DOM.em className: 'glyphicon glyphicon-plus' ' Add' else null DOM.div null, DOM.h3 null, 'Members' _.map @state.identities, (identity) => props = _.extend {}, @props, key: "group-#{@props.group._id}-#{identity._id}" identity: identity ContactCard props, DOM.div null, DOM.a onClick: @removeIdentity identity._id href: '#' className: 'btn btn-danger btn-sm' , 'remove'
23816
_ = require 'lodash' React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass getInitialState: -> group: @props.group identities: @props.group.identities identityToAdd: null selectIdentityToAdd: (identity) -> @setState identityToAdd: identity addIdentity: (e) -> e.preventDefault() groupId = @props.group._id identityId = @state.identityToAdd._id url = "/admin/groups/#{groupId}/add/#{identityId}.json" @props.request.post url, {}, (err, data) => console.log err if err newState = identityToAdd: {} if data.group newState.group = data.group if data.group.identities newState.identities = data.group.identities @setState newState removeIdentity: (identityId) -> (e) => e.preventDefault() groupId = @props.group._id url = "/admin/groups/#{groupId}/remove/#{identityId}.json" @props.request.post url, {}, (err, data) => console.log err if err newState = {} if data.group newState.group = data.group if data.group.identities newState.identities = data.group.identities @setState newState onUpdate: (obj) -> @setState obj render: -> identityInputPath = 'kerplunk-identity-autocomplete:input' IdentityInputComponent = @props.getComponent identityInputPath identityConfig = @props.globals.public.identity cardComponentPath = identityConfig.contactCardComponent ? identityConfig.defaultContactCard ContactCard = @props.getComponent cardComponentPath DOM.section className: 'content' , DOM.h3 null, @props.group.name DOM.div null, _.map (@props.globals.public.editGroupComponents ? {}), (componentPath, key) => Component = @props.getComponent componentPath Component _.extend {}, @props, key: "<KEY>key<KEY>}" onUpdate: @onUpdate DOM.h3 null, 'Add Contacts' IdentityInputComponent _.extend {}, @props, onSelect: @selectIdentityToAdd identity: @state.identityToAdd omit: _.map @state.identities, '_id' if @state.identityToAdd DOM.a href: '#' onClick: @addIdentity className: 'btn btn-success' , DOM.em className: 'glyphicon glyphicon-plus' ' Add' else null DOM.div null, DOM.h3 null, 'Members' _.map @state.identities, (identity) => props = _.extend {}, @props, key: "<KEY>props.<KEY> identity: identity ContactCard props, DOM.div null, DOM.a onClick: @removeIdentity identity._id href: '#' className: 'btn btn-danger btn-sm' , 'remove'
true
_ = require 'lodash' React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass getInitialState: -> group: @props.group identities: @props.group.identities identityToAdd: null selectIdentityToAdd: (identity) -> @setState identityToAdd: identity addIdentity: (e) -> e.preventDefault() groupId = @props.group._id identityId = @state.identityToAdd._id url = "/admin/groups/#{groupId}/add/#{identityId}.json" @props.request.post url, {}, (err, data) => console.log err if err newState = identityToAdd: {} if data.group newState.group = data.group if data.group.identities newState.identities = data.group.identities @setState newState removeIdentity: (identityId) -> (e) => e.preventDefault() groupId = @props.group._id url = "/admin/groups/#{groupId}/remove/#{identityId}.json" @props.request.post url, {}, (err, data) => console.log err if err newState = {} if data.group newState.group = data.group if data.group.identities newState.identities = data.group.identities @setState newState onUpdate: (obj) -> @setState obj render: -> identityInputPath = 'kerplunk-identity-autocomplete:input' IdentityInputComponent = @props.getComponent identityInputPath identityConfig = @props.globals.public.identity cardComponentPath = identityConfig.contactCardComponent ? identityConfig.defaultContactCard ContactCard = @props.getComponent cardComponentPath DOM.section className: 'content' , DOM.h3 null, @props.group.name DOM.div null, _.map (@props.globals.public.editGroupComponents ? {}), (componentPath, key) => Component = @props.getComponent componentPath Component _.extend {}, @props, key: "PI:KEY:<KEY>END_PIkeyPI:KEY:<KEY>END_PI}" onUpdate: @onUpdate DOM.h3 null, 'Add Contacts' IdentityInputComponent _.extend {}, @props, onSelect: @selectIdentityToAdd identity: @state.identityToAdd omit: _.map @state.identities, '_id' if @state.identityToAdd DOM.a href: '#' onClick: @addIdentity className: 'btn btn-success' , DOM.em className: 'glyphicon glyphicon-plus' ' Add' else null DOM.div null, DOM.h3 null, 'Members' _.map @state.identities, (identity) => props = _.extend {}, @props, key: "PI:KEY:<KEY>END_PIprops.PI:KEY:<KEY>END_PI identity: identity ContactCard props, DOM.div null, DOM.a onClick: @removeIdentity identity._id href: '#' className: 'btn btn-danger btn-sm' , 'remove'
[ { "context": "e\n\n\tgetDisplay: =>\n\t\tnew LocaButton\n\t\t\tloca_key: \"example.tray.app.button\"\n\t\t\tonClick: =>\n\t\t\t\tCUI.alert(text: $$(\"example.t", "end": 153, "score": 0.9791451096534729, "start": 130, "tag": "KEY", "value": "example.tray.app.button" } ]
src/webfrontend/ExampleTrayApp.coffee
programmfabrik/easydb-example-plugin
0
class ExampleTrayApp extends TrayApp is_allowed: => # always allow this true getDisplay: => new LocaButton loca_key: "example.tray.app.button" onClick: => CUI.alert(text: $$("example.tray.app.thank_you.md"), markdown: true) ez5.session_ready -> ez5.tray.registerApp(new ExampleTrayApp())
65374
class ExampleTrayApp extends TrayApp is_allowed: => # always allow this true getDisplay: => new LocaButton loca_key: "<KEY>" onClick: => CUI.alert(text: $$("example.tray.app.thank_you.md"), markdown: true) ez5.session_ready -> ez5.tray.registerApp(new ExampleTrayApp())
true
class ExampleTrayApp extends TrayApp is_allowed: => # always allow this true getDisplay: => new LocaButton loca_key: "PI:KEY:<KEY>END_PI" onClick: => CUI.alert(text: $$("example.tray.app.thank_you.md"), markdown: true) ez5.session_ready -> ez5.tray.registerApp(new ExampleTrayApp())
[ { "context": "uth: (username, password) ->\n credentials = \"#{username}:#{password}\"\n basicCredentials = new Buffer(credentials", "end": 3870, "score": 0.9685224890708923, "start": 3845, "tag": "KEY", "value": "\"#{username}:#{password}\"" } ]
main.coffee
poupotte/request-json
0
FormData = require "form-data" fs = require "fs" url = require "url" http = require 'http' https = require 'https' mime = require "mime" # Merge two objects in one. Values from the second object win over the first # one. merge = (obj1, obj2) -> result = {} result[key] = obj1[key] for key of obj1 if obj2? result[key] = obj2[key] for key of obj2 result # Build parameters required by http lib from options set on the client # and extra options given for the request. buildOptions = (clientOptions, clientHeaders, host, path, requestOptions) -> # Check if there is something to merge before performing additional # operation if requestOptions isnt {} options = merge clientOptions, requestOptions # Check if there are headers to merge before performing additional # operation on headers if requestOptions? and requestOptions isnt {} and requestOptions.headers options.headers = merge clientHeaders, requestOptions.headers # If no additional headers are given, it uses the client headers directly. else options.headers = clientHeaders # Buuld host parameters from given URL. path = "/#{path}" if path[0] isnt '/' urlData = url.parse host options.host = urlData.host.split(':')[0] options.port = urlData.port options.path = path if urlData.protocol is 'https:' options.requestFactory = https options.rejectUnauthorized = false else options.requestFactory = http options # Parse body assuming the body is a json object. Send an error if the body # can't be parsed. parseBody = (error, response, body, callback, parse=true) -> if typeof body is "string" and body isnt "" and parse try parsed = JSON.parse body catch err error ?= new Error("Parsing error : #{err.message}, body= \n #{body}") parsed = body else parsed = body callback error, response, parsed # Generic command to play a simple request (withou streaming or form). playRequest = (opts, data, callback, parse=true) -> if typeof data is 'function' callback = data data = {} if data? opts.headers['content-size'] = data.length else delete opts.headers['content-type'] req = opts.requestFactory.request opts, (res) -> res.setEncoding 'utf8' body = '' res.on 'data', (chunk) -> body += chunk res.on 'end', -> parseBody null, res, body, callback, parse req.on 'error', (err) -> callback err req.write JSON.stringify data if data? req.end() # Function to make request json more modular. module.exports = newClient: (url, options = {}) -> new JsonClient url, options get: (opts, data, callback, parse) -> opts.method = "GET" playRequest opts, data, callback, parse del: (opts, data, callback, parse) -> opts.method = "DELETE" playRequest opts, data, callback, parse post: (opts, data, callback, parse) -> opts.method = "POST" playRequest opts, data, callback, parse put: (opts, data, callback, parse) -> opts.method = "PUT" playRequest opts, data, callback, parse patch: (opts, data, callback, parse) -> opts.method = "PATCH" playRequest opts, data, callback, parse # Small HTTP client for easy json interactions with Cozy backends. class JsonClient # Set default headers constructor: (@host, @options = {}) -> @headers = @options.headers ? {} @headers['accept'] = 'application/json' @headers['user-agent'] = "request-json/1.0" @headers['content-type'] = 'application/json' # Set basic authentication on each requests setBasicAuth: (username, password) -> credentials = "#{username}:#{password}" basicCredentials = new Buffer(credentials).toString('base64') @headers["authorization"] = "Basic #{basicCredentials}" # Add a token to request header. setToken: (token) -> @headers["x-auth-token"] = token # Send a GET request to path. Parse response body to obtain a JS object. get: (path, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.get opts, null, callback, parse # Send a POST request to path with given JSON as body. post: (path, data, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} if typeof data is 'function' parse = options if typeof options is 'boolean' callback = data data = {} options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.post opts, data, callback # Send a PUT request to path with given JSON as body. put: (path, data, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.put opts, data, callback, parse # Send a PATCH request to path with given JSON as body. patch: (path, data, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.patch opts, data, callback, parse # Send a DELETE request to path. del: (path, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.del opts, {}, callback, parse # Send a post request with file located at given path as attachment # (multipart form) sendFile: (path, files, data, callback, parse=true) -> callback = data if typeof(data) is "function" form = new FormData() # Append fields to form. unless typeof(data) is "function" for att of data form.append att, data[att] # files is a string so it is a file path if typeof files is "string" form.append "file", fs.createReadStream files # files is not a string and is not an array so it is a stream else if not Array.isArray files form.append "file", files # files is an array of strings and streams else index = 0 for file in files index++ if typeof file is "string" form.append "file#{index}", fs.createReadStream(file) else form.append "file#{index}", file form.submit url.resolve(@host, path), (err, res) -> res.setEncoding 'utf8' body = '' res.on 'data', (chunk) -> body += chunk res.on 'end', -> parseBody null, res, body, callback, parse # Send a put request with file located at given path as body. # Do not use form, file is sent directly putFile: (path, file, callback, parse=true) -> opts = buildOptions @options, @headers, @host, path, method: 'PUT' opts.headers['content-type'] = mime.lookup file # file is a string so it is a file path if typeof file is "string" fileStream = fs.createReadStream(file) # file is not a string so it should be a stream. else fileStream = file req = opts.requestFactory.request opts, (res) -> res.setEncoding 'utf8' body = '' res.on 'data', (chunk) -> body += chunk res.on 'end', -> parseBody null, res, body, callback, parse req.on 'error', (err) -> callback err reqStream = fileStream.pipe req {reqStream, fileStream} # Retrieve file located at *path* and save it as *filePath*. # Use a write stream for that. saveFile: (path, filePath, callback) -> options = {} opts = buildOptions @options, @headers, @host, path, options opts.option = "GET" req = opts.requestFactory.request opts, (res) -> writeStream = fs.createWriteStream filePath res.pipe writeStream writeStream.on 'finish', -> callback null, res req.on 'error', (err) -> callback err req.end() # Retrieve file located at *path* and return it as stream. saveFileAsStream: (path, callback) -> options = {} opts = buildOptions @options, @headers, @host, path, options opts.option = "GET" req = opts.requestFactory.request opts, (res) -> callback null, res req.on 'error', (err) -> callback err req.end() module.exports.JsonClient = JsonClient
220601
FormData = require "form-data" fs = require "fs" url = require "url" http = require 'http' https = require 'https' mime = require "mime" # Merge two objects in one. Values from the second object win over the first # one. merge = (obj1, obj2) -> result = {} result[key] = obj1[key] for key of obj1 if obj2? result[key] = obj2[key] for key of obj2 result # Build parameters required by http lib from options set on the client # and extra options given for the request. buildOptions = (clientOptions, clientHeaders, host, path, requestOptions) -> # Check if there is something to merge before performing additional # operation if requestOptions isnt {} options = merge clientOptions, requestOptions # Check if there are headers to merge before performing additional # operation on headers if requestOptions? and requestOptions isnt {} and requestOptions.headers options.headers = merge clientHeaders, requestOptions.headers # If no additional headers are given, it uses the client headers directly. else options.headers = clientHeaders # Buuld host parameters from given URL. path = "/#{path}" if path[0] isnt '/' urlData = url.parse host options.host = urlData.host.split(':')[0] options.port = urlData.port options.path = path if urlData.protocol is 'https:' options.requestFactory = https options.rejectUnauthorized = false else options.requestFactory = http options # Parse body assuming the body is a json object. Send an error if the body # can't be parsed. parseBody = (error, response, body, callback, parse=true) -> if typeof body is "string" and body isnt "" and parse try parsed = JSON.parse body catch err error ?= new Error("Parsing error : #{err.message}, body= \n #{body}") parsed = body else parsed = body callback error, response, parsed # Generic command to play a simple request (withou streaming or form). playRequest = (opts, data, callback, parse=true) -> if typeof data is 'function' callback = data data = {} if data? opts.headers['content-size'] = data.length else delete opts.headers['content-type'] req = opts.requestFactory.request opts, (res) -> res.setEncoding 'utf8' body = '' res.on 'data', (chunk) -> body += chunk res.on 'end', -> parseBody null, res, body, callback, parse req.on 'error', (err) -> callback err req.write JSON.stringify data if data? req.end() # Function to make request json more modular. module.exports = newClient: (url, options = {}) -> new JsonClient url, options get: (opts, data, callback, parse) -> opts.method = "GET" playRequest opts, data, callback, parse del: (opts, data, callback, parse) -> opts.method = "DELETE" playRequest opts, data, callback, parse post: (opts, data, callback, parse) -> opts.method = "POST" playRequest opts, data, callback, parse put: (opts, data, callback, parse) -> opts.method = "PUT" playRequest opts, data, callback, parse patch: (opts, data, callback, parse) -> opts.method = "PATCH" playRequest opts, data, callback, parse # Small HTTP client for easy json interactions with Cozy backends. class JsonClient # Set default headers constructor: (@host, @options = {}) -> @headers = @options.headers ? {} @headers['accept'] = 'application/json' @headers['user-agent'] = "request-json/1.0" @headers['content-type'] = 'application/json' # Set basic authentication on each requests setBasicAuth: (username, password) -> credentials = <KEY> basicCredentials = new Buffer(credentials).toString('base64') @headers["authorization"] = "Basic #{basicCredentials}" # Add a token to request header. setToken: (token) -> @headers["x-auth-token"] = token # Send a GET request to path. Parse response body to obtain a JS object. get: (path, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.get opts, null, callback, parse # Send a POST request to path with given JSON as body. post: (path, data, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} if typeof data is 'function' parse = options if typeof options is 'boolean' callback = data data = {} options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.post opts, data, callback # Send a PUT request to path with given JSON as body. put: (path, data, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.put opts, data, callback, parse # Send a PATCH request to path with given JSON as body. patch: (path, data, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.patch opts, data, callback, parse # Send a DELETE request to path. del: (path, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.del opts, {}, callback, parse # Send a post request with file located at given path as attachment # (multipart form) sendFile: (path, files, data, callback, parse=true) -> callback = data if typeof(data) is "function" form = new FormData() # Append fields to form. unless typeof(data) is "function" for att of data form.append att, data[att] # files is a string so it is a file path if typeof files is "string" form.append "file", fs.createReadStream files # files is not a string and is not an array so it is a stream else if not Array.isArray files form.append "file", files # files is an array of strings and streams else index = 0 for file in files index++ if typeof file is "string" form.append "file#{index}", fs.createReadStream(file) else form.append "file#{index}", file form.submit url.resolve(@host, path), (err, res) -> res.setEncoding 'utf8' body = '' res.on 'data', (chunk) -> body += chunk res.on 'end', -> parseBody null, res, body, callback, parse # Send a put request with file located at given path as body. # Do not use form, file is sent directly putFile: (path, file, callback, parse=true) -> opts = buildOptions @options, @headers, @host, path, method: 'PUT' opts.headers['content-type'] = mime.lookup file # file is a string so it is a file path if typeof file is "string" fileStream = fs.createReadStream(file) # file is not a string so it should be a stream. else fileStream = file req = opts.requestFactory.request opts, (res) -> res.setEncoding 'utf8' body = '' res.on 'data', (chunk) -> body += chunk res.on 'end', -> parseBody null, res, body, callback, parse req.on 'error', (err) -> callback err reqStream = fileStream.pipe req {reqStream, fileStream} # Retrieve file located at *path* and save it as *filePath*. # Use a write stream for that. saveFile: (path, filePath, callback) -> options = {} opts = buildOptions @options, @headers, @host, path, options opts.option = "GET" req = opts.requestFactory.request opts, (res) -> writeStream = fs.createWriteStream filePath res.pipe writeStream writeStream.on 'finish', -> callback null, res req.on 'error', (err) -> callback err req.end() # Retrieve file located at *path* and return it as stream. saveFileAsStream: (path, callback) -> options = {} opts = buildOptions @options, @headers, @host, path, options opts.option = "GET" req = opts.requestFactory.request opts, (res) -> callback null, res req.on 'error', (err) -> callback err req.end() module.exports.JsonClient = JsonClient
true
FormData = require "form-data" fs = require "fs" url = require "url" http = require 'http' https = require 'https' mime = require "mime" # Merge two objects in one. Values from the second object win over the first # one. merge = (obj1, obj2) -> result = {} result[key] = obj1[key] for key of obj1 if obj2? result[key] = obj2[key] for key of obj2 result # Build parameters required by http lib from options set on the client # and extra options given for the request. buildOptions = (clientOptions, clientHeaders, host, path, requestOptions) -> # Check if there is something to merge before performing additional # operation if requestOptions isnt {} options = merge clientOptions, requestOptions # Check if there are headers to merge before performing additional # operation on headers if requestOptions? and requestOptions isnt {} and requestOptions.headers options.headers = merge clientHeaders, requestOptions.headers # If no additional headers are given, it uses the client headers directly. else options.headers = clientHeaders # Buuld host parameters from given URL. path = "/#{path}" if path[0] isnt '/' urlData = url.parse host options.host = urlData.host.split(':')[0] options.port = urlData.port options.path = path if urlData.protocol is 'https:' options.requestFactory = https options.rejectUnauthorized = false else options.requestFactory = http options # Parse body assuming the body is a json object. Send an error if the body # can't be parsed. parseBody = (error, response, body, callback, parse=true) -> if typeof body is "string" and body isnt "" and parse try parsed = JSON.parse body catch err error ?= new Error("Parsing error : #{err.message}, body= \n #{body}") parsed = body else parsed = body callback error, response, parsed # Generic command to play a simple request (withou streaming or form). playRequest = (opts, data, callback, parse=true) -> if typeof data is 'function' callback = data data = {} if data? opts.headers['content-size'] = data.length else delete opts.headers['content-type'] req = opts.requestFactory.request opts, (res) -> res.setEncoding 'utf8' body = '' res.on 'data', (chunk) -> body += chunk res.on 'end', -> parseBody null, res, body, callback, parse req.on 'error', (err) -> callback err req.write JSON.stringify data if data? req.end() # Function to make request json more modular. module.exports = newClient: (url, options = {}) -> new JsonClient url, options get: (opts, data, callback, parse) -> opts.method = "GET" playRequest opts, data, callback, parse del: (opts, data, callback, parse) -> opts.method = "DELETE" playRequest opts, data, callback, parse post: (opts, data, callback, parse) -> opts.method = "POST" playRequest opts, data, callback, parse put: (opts, data, callback, parse) -> opts.method = "PUT" playRequest opts, data, callback, parse patch: (opts, data, callback, parse) -> opts.method = "PATCH" playRequest opts, data, callback, parse # Small HTTP client for easy json interactions with Cozy backends. class JsonClient # Set default headers constructor: (@host, @options = {}) -> @headers = @options.headers ? {} @headers['accept'] = 'application/json' @headers['user-agent'] = "request-json/1.0" @headers['content-type'] = 'application/json' # Set basic authentication on each requests setBasicAuth: (username, password) -> credentials = PI:KEY:<KEY>END_PI basicCredentials = new Buffer(credentials).toString('base64') @headers["authorization"] = "Basic #{basicCredentials}" # Add a token to request header. setToken: (token) -> @headers["x-auth-token"] = token # Send a GET request to path. Parse response body to obtain a JS object. get: (path, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.get opts, null, callback, parse # Send a POST request to path with given JSON as body. post: (path, data, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} if typeof data is 'function' parse = options if typeof options is 'boolean' callback = data data = {} options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.post opts, data, callback # Send a PUT request to path with given JSON as body. put: (path, data, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.put opts, data, callback, parse # Send a PATCH request to path with given JSON as body. patch: (path, data, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.patch opts, data, callback, parse # Send a DELETE request to path. del: (path, options, callback, parse=true) -> if typeof options is 'function' parse = callback if typeof callback is 'boolean' callback = options options = {} opts = buildOptions @options, @headers, @host, path, options module.exports.del opts, {}, callback, parse # Send a post request with file located at given path as attachment # (multipart form) sendFile: (path, files, data, callback, parse=true) -> callback = data if typeof(data) is "function" form = new FormData() # Append fields to form. unless typeof(data) is "function" for att of data form.append att, data[att] # files is a string so it is a file path if typeof files is "string" form.append "file", fs.createReadStream files # files is not a string and is not an array so it is a stream else if not Array.isArray files form.append "file", files # files is an array of strings and streams else index = 0 for file in files index++ if typeof file is "string" form.append "file#{index}", fs.createReadStream(file) else form.append "file#{index}", file form.submit url.resolve(@host, path), (err, res) -> res.setEncoding 'utf8' body = '' res.on 'data', (chunk) -> body += chunk res.on 'end', -> parseBody null, res, body, callback, parse # Send a put request with file located at given path as body. # Do not use form, file is sent directly putFile: (path, file, callback, parse=true) -> opts = buildOptions @options, @headers, @host, path, method: 'PUT' opts.headers['content-type'] = mime.lookup file # file is a string so it is a file path if typeof file is "string" fileStream = fs.createReadStream(file) # file is not a string so it should be a stream. else fileStream = file req = opts.requestFactory.request opts, (res) -> res.setEncoding 'utf8' body = '' res.on 'data', (chunk) -> body += chunk res.on 'end', -> parseBody null, res, body, callback, parse req.on 'error', (err) -> callback err reqStream = fileStream.pipe req {reqStream, fileStream} # Retrieve file located at *path* and save it as *filePath*. # Use a write stream for that. saveFile: (path, filePath, callback) -> options = {} opts = buildOptions @options, @headers, @host, path, options opts.option = "GET" req = opts.requestFactory.request opts, (res) -> writeStream = fs.createWriteStream filePath res.pipe writeStream writeStream.on 'finish', -> callback null, res req.on 'error', (err) -> callback err req.end() # Retrieve file located at *path* and return it as stream. saveFileAsStream: (path, callback) -> options = {} opts = buildOptions @options, @headers, @host, path, options opts.option = "GET" req = opts.requestFactory.request opts, (res) -> callback null, res req.on 'error', (err) -> callback err req.end() module.exports.JsonClient = JsonClient
[ { "context": "window.hello).toBeDefined()\n expect(hello? 'Boris').toEqual 'Hello, Boris'\n\n it 'loads helper', ->", "end": 120, "score": 0.8319947719573975, "start": 118, "tag": "NAME", "value": "is" }, { "context": "fined()\n expect(hello? 'Boris').toEqual 'Hello, Boris'\n\n it 'loads helper', ->\n expect(window.helpe", "end": 144, "score": 0.9150807857513428, "start": 139, "tag": "NAME", "value": "Boris" } ]
node_modules/grunt-contrib-testem/spec/basic/spec.coffee
dehuszar/resume-builder-fe
1
describe 'Environment', -> it 'loads vendored js', -> expect(window.hello).toBeDefined() expect(hello? 'Boris').toEqual 'Hello, Boris' it 'loads helper', -> expect(window.helper).toBeDefined() expect(helper?()).toEqual 'helper'
67644
describe 'Environment', -> it 'loads vendored js', -> expect(window.hello).toBeDefined() expect(hello? 'Bor<NAME>').toEqual 'Hello, <NAME>' it 'loads helper', -> expect(window.helper).toBeDefined() expect(helper?()).toEqual 'helper'
true
describe 'Environment', -> it 'loads vendored js', -> expect(window.hello).toBeDefined() expect(hello? 'BorPI:NAME:<NAME>END_PI').toEqual 'Hello, PI:NAME:<NAME>END_PI' it 'loads helper', -> expect(window.helper).toBeDefined() expect(helper?()).toEqual 'helper'
[ { "context": " email: email\n password: password\n timezone: timezone\n checkA", "end": 856, "score": 0.9980210661888123, "start": 848, "tag": "PASSWORD", "value": "password" }, { "context": " return new AuthError(\"Wrong password\", \"wrong_password\") if not auth.isPasswordValid(password)\n ", "end": 1212, "score": 0.9949686527252197, "start": 1198, "tag": "PASSWORD", "value": "wrong_password" } ]
src/server/auth/controller.coffee
robintibor/rizzoma
2
async = require('async') Conf = require('../conf').Conf AuthCouchProcessor = require('./couch_processor').AuthCouchProcessor UserCouchProcessor = require('../user/couch_processor').UserCouchProcessor WelcomeWaveBuilder = require('../wave/welcome_wave').WelcomeWaveBuilder MergeController = require('../user/merge_controller').MergeController authFactory = require('./factory').authFactory AuthError = require('./exceptions').AuthError EMPTY_EMAIL_ERROR = require('./exceptions').EMPTY_EMAIL_ERROR class AuthController constructor: () -> @_logger = Conf.getLogger('auth-controller') processPasswordAuth: (req, email, password, timezone, callback) -> ### Авторизация по паролю ### profile = provider: 'password' _json: email: email password: password timezone: timezone checkAuthProcessor = (authFromSource, auth) -> return new AuthError("User not found, please register", "user_not_found") if not auth return new AuthError("User not confirmed", "user_not_confirmed") if auth.getConfirmKey() return new AuthError("Wrong password", "wrong_password") if not auth.isPasswordValid(password) return null @_processAuth(req, profile, checkAuthProcessor, null, callback) processOAuth: (req, profile, callback) -> ### Авторизация через OAuth ### checkAuthProcessor = (authFromSource) -> return if !!authFromSource.getEmail() return new AuthError("Can't auth user without any email", EMPTY_EMAIL_ERROR) @_processAuth(req, profile, checkAuthProcessor, null, callback) _processAuth: (req, profile, checkAuthProcessor, options, callback) -> ### Обший процесс авторизации принимает checkAuthProcessor для различных типов проверок @param callback: function ### authFromSource = authFactory(profile.provider, profile._json) AuthCouchProcessor.getById(authFromSource.getId(), (err, auth) => return callback(err) if err and err.message != 'not_found' fail = checkAuthProcessor?(authFromSource, auth) return callback(null, false, fail) if fail @afterAuthActions(req, authFromSource, auth, options, callback) ) _updateAuthFromSource: (authFromSource, auth, callback) -> ### Обновляет модель авторизации данными из source модели Возвращает в колбэк обновленную модель и флажек изменилась она или нет ### return callback(null, authFromSource, true) if not auth authFromSource.setUserId(auth.getUserId()) authFromSource.setName(auth.getName()) if not authFromSource.getName() authFromSource.setUserCompilationParams(auth.getUserCompilationParams()) callback(null, authFromSource, auth.getHash() != authFromSource.getHash()) afterAuthActions: (req, authFromSource, auth, options={}, callback) -> ### Действия после успешной авторизации ### tasks = [ (callback) => @_updateAuthFromSource(authFromSource, auth, callback) (auth, isAuthChanged, callback) -> UserCouchProcessor.getOrCreateByAuth(auth, (err, user, isAuthUserIdChanged) -> return callback(err) if err auth.updateUser(user) callback(null, auth, user, isAuthChanged or isAuthUserIdChanged) ) (auth, user, isAuthChanged, callback) => @_useProperAlgorithm(auth, user, req, options, (err, processedUser) => @_logger.error('Error while updating authorized user', {err, user, auth}) if err # возникшие ошибки (не создался Welcome topic или не смерджились аккаунты) дальше не передаем, только логгируем. callback(null, auth, processedUser or user, isAuthChanged) ) (auth, user, isAuthChanged, onSaveDone) => action = (reloadedUser, callback) -> #Будем сохранять если обробатываемый пользователь новее того, с что в базе user._rev = reloadedUser._rev callback(null, user.lastVisit >= reloadedUser.lastVisit, user, false) UserCouchProcessor.saveResolvingConflicts(user, action, (err) => if err @_logger.error('Error while saving authorized user', {err, user, auth}) else @_logSucessAuth(req, auth, user) callback(err, user) ) return onSaveDone() if not isAuthChanged AuthCouchProcessor.save(auth, (err) => @_logger.error('Error while saving user auth', {err, user, auth}) if err onSaveDone() ) ] async.waterfall(tasks, (err) -> callback(err) if err ) _logSucessAuth: (req, auth, user) -> sidKey = Conf.getSessionConf().key #Логируем часть sid-а, а не значение полностью, на случай если кто-то получит доступ к нашим логам. sid = req.cookies[sidKey]?.substr(0, 10) logObject = ip: req.connection.remoteAddress or req.socket.remoteAddress or req.connection.socket?.remoteAddress sid: sid emails: user.normalizedEmails userId: user.id authId: auth.getId() authEmail: auth.getEmail() authAlternativeEmails: auth.getAlternativeEmails() @_logger.debug("User #{user.id} #{user.email} has logged in", logObject) _useProperAlgorithm: (auth, user, req, options, callback) -> ### Выбирает нужный алгоритм авторизации: первый раз пользователь пришел или заходил раньше. @param user: UserModel @param session: object @param callback: function ### session = req.session return @_processFirstAuth(auth, user, session, options, callback) if not user.firstVisit return @_processOrdinaryAuth(auth, user, session, options, callback) _processFirstAuth: (auth, user, session, options, callback) => ### Алгоритм авторизации нового пользователя (пользователь был сосдан ранее (импорт, ручное добавление в топик), но раньше не авторизовался). ### user.setFirstAuthCondition(session.referer, session.channel, session.landing) if options.disableNotification user.notification.clearSettings() else user.notification.setDefaultSettings() session.firstVisit = true return @_processOrdinaryAuth(auth, user, session, options, callback) if options.skipWelcomeTopic WelcomeWaveBuilder.getOrCreateWelcomeWaves(user, (err, waves, isFound) => if err @_logger.error("Error while creating welcome topic for user #{user.id}", err) else for wave in waves @_logger.debug("Created welcome topic #{wave.waveId} for user #{user.id}") delete wave.internalId session.welcomeWaves = waves session.welcomeTopicJustCreated = not isFound @_processOrdinaryAuth(auth, user, session, options, callback) ) _processOrdinaryAuth: (auth, user, session, options, callback) -> ### Алгоритм авторизации существующего пользователя с существующей авторизацией (самый обычный вариант). ### session.justLoggedIn = true user.setVisitCondition() emailsToMerge = user.getNotMyEmails(auth.getAlternativeEmails()) return callback(null, user) if not emailsToMerge.length @_logger.debug("Automatic merge were started user #{user.id} with #{emailsToMerge.join(', ')}") MergeController.mergeByEmails(user, emailsToMerge, callback, true) module.exports.AuthController = new AuthController()
59342
async = require('async') Conf = require('../conf').Conf AuthCouchProcessor = require('./couch_processor').AuthCouchProcessor UserCouchProcessor = require('../user/couch_processor').UserCouchProcessor WelcomeWaveBuilder = require('../wave/welcome_wave').WelcomeWaveBuilder MergeController = require('../user/merge_controller').MergeController authFactory = require('./factory').authFactory AuthError = require('./exceptions').AuthError EMPTY_EMAIL_ERROR = require('./exceptions').EMPTY_EMAIL_ERROR class AuthController constructor: () -> @_logger = Conf.getLogger('auth-controller') processPasswordAuth: (req, email, password, timezone, callback) -> ### Авторизация по паролю ### profile = provider: 'password' _json: email: email password: <PASSWORD> timezone: timezone checkAuthProcessor = (authFromSource, auth) -> return new AuthError("User not found, please register", "user_not_found") if not auth return new AuthError("User not confirmed", "user_not_confirmed") if auth.getConfirmKey() return new AuthError("Wrong password", "<PASSWORD>") if not auth.isPasswordValid(password) return null @_processAuth(req, profile, checkAuthProcessor, null, callback) processOAuth: (req, profile, callback) -> ### Авторизация через OAuth ### checkAuthProcessor = (authFromSource) -> return if !!authFromSource.getEmail() return new AuthError("Can't auth user without any email", EMPTY_EMAIL_ERROR) @_processAuth(req, profile, checkAuthProcessor, null, callback) _processAuth: (req, profile, checkAuthProcessor, options, callback) -> ### Обший процесс авторизации принимает checkAuthProcessor для различных типов проверок @param callback: function ### authFromSource = authFactory(profile.provider, profile._json) AuthCouchProcessor.getById(authFromSource.getId(), (err, auth) => return callback(err) if err and err.message != 'not_found' fail = checkAuthProcessor?(authFromSource, auth) return callback(null, false, fail) if fail @afterAuthActions(req, authFromSource, auth, options, callback) ) _updateAuthFromSource: (authFromSource, auth, callback) -> ### Обновляет модель авторизации данными из source модели Возвращает в колбэк обновленную модель и флажек изменилась она или нет ### return callback(null, authFromSource, true) if not auth authFromSource.setUserId(auth.getUserId()) authFromSource.setName(auth.getName()) if not authFromSource.getName() authFromSource.setUserCompilationParams(auth.getUserCompilationParams()) callback(null, authFromSource, auth.getHash() != authFromSource.getHash()) afterAuthActions: (req, authFromSource, auth, options={}, callback) -> ### Действия после успешной авторизации ### tasks = [ (callback) => @_updateAuthFromSource(authFromSource, auth, callback) (auth, isAuthChanged, callback) -> UserCouchProcessor.getOrCreateByAuth(auth, (err, user, isAuthUserIdChanged) -> return callback(err) if err auth.updateUser(user) callback(null, auth, user, isAuthChanged or isAuthUserIdChanged) ) (auth, user, isAuthChanged, callback) => @_useProperAlgorithm(auth, user, req, options, (err, processedUser) => @_logger.error('Error while updating authorized user', {err, user, auth}) if err # возникшие ошибки (не создался Welcome topic или не смерджились аккаунты) дальше не передаем, только логгируем. callback(null, auth, processedUser or user, isAuthChanged) ) (auth, user, isAuthChanged, onSaveDone) => action = (reloadedUser, callback) -> #Будем сохранять если обробатываемый пользователь новее того, с что в базе user._rev = reloadedUser._rev callback(null, user.lastVisit >= reloadedUser.lastVisit, user, false) UserCouchProcessor.saveResolvingConflicts(user, action, (err) => if err @_logger.error('Error while saving authorized user', {err, user, auth}) else @_logSucessAuth(req, auth, user) callback(err, user) ) return onSaveDone() if not isAuthChanged AuthCouchProcessor.save(auth, (err) => @_logger.error('Error while saving user auth', {err, user, auth}) if err onSaveDone() ) ] async.waterfall(tasks, (err) -> callback(err) if err ) _logSucessAuth: (req, auth, user) -> sidKey = Conf.getSessionConf().key #Логируем часть sid-а, а не значение полностью, на случай если кто-то получит доступ к нашим логам. sid = req.cookies[sidKey]?.substr(0, 10) logObject = ip: req.connection.remoteAddress or req.socket.remoteAddress or req.connection.socket?.remoteAddress sid: sid emails: user.normalizedEmails userId: user.id authId: auth.getId() authEmail: auth.getEmail() authAlternativeEmails: auth.getAlternativeEmails() @_logger.debug("User #{user.id} #{user.email} has logged in", logObject) _useProperAlgorithm: (auth, user, req, options, callback) -> ### Выбирает нужный алгоритм авторизации: первый раз пользователь пришел или заходил раньше. @param user: UserModel @param session: object @param callback: function ### session = req.session return @_processFirstAuth(auth, user, session, options, callback) if not user.firstVisit return @_processOrdinaryAuth(auth, user, session, options, callback) _processFirstAuth: (auth, user, session, options, callback) => ### Алгоритм авторизации нового пользователя (пользователь был сосдан ранее (импорт, ручное добавление в топик), но раньше не авторизовался). ### user.setFirstAuthCondition(session.referer, session.channel, session.landing) if options.disableNotification user.notification.clearSettings() else user.notification.setDefaultSettings() session.firstVisit = true return @_processOrdinaryAuth(auth, user, session, options, callback) if options.skipWelcomeTopic WelcomeWaveBuilder.getOrCreateWelcomeWaves(user, (err, waves, isFound) => if err @_logger.error("Error while creating welcome topic for user #{user.id}", err) else for wave in waves @_logger.debug("Created welcome topic #{wave.waveId} for user #{user.id}") delete wave.internalId session.welcomeWaves = waves session.welcomeTopicJustCreated = not isFound @_processOrdinaryAuth(auth, user, session, options, callback) ) _processOrdinaryAuth: (auth, user, session, options, callback) -> ### Алгоритм авторизации существующего пользователя с существующей авторизацией (самый обычный вариант). ### session.justLoggedIn = true user.setVisitCondition() emailsToMerge = user.getNotMyEmails(auth.getAlternativeEmails()) return callback(null, user) if not emailsToMerge.length @_logger.debug("Automatic merge were started user #{user.id} with #{emailsToMerge.join(', ')}") MergeController.mergeByEmails(user, emailsToMerge, callback, true) module.exports.AuthController = new AuthController()
true
async = require('async') Conf = require('../conf').Conf AuthCouchProcessor = require('./couch_processor').AuthCouchProcessor UserCouchProcessor = require('../user/couch_processor').UserCouchProcessor WelcomeWaveBuilder = require('../wave/welcome_wave').WelcomeWaveBuilder MergeController = require('../user/merge_controller').MergeController authFactory = require('./factory').authFactory AuthError = require('./exceptions').AuthError EMPTY_EMAIL_ERROR = require('./exceptions').EMPTY_EMAIL_ERROR class AuthController constructor: () -> @_logger = Conf.getLogger('auth-controller') processPasswordAuth: (req, email, password, timezone, callback) -> ### Авторизация по паролю ### profile = provider: 'password' _json: email: email password: PI:PASSWORD:<PASSWORD>END_PI timezone: timezone checkAuthProcessor = (authFromSource, auth) -> return new AuthError("User not found, please register", "user_not_found") if not auth return new AuthError("User not confirmed", "user_not_confirmed") if auth.getConfirmKey() return new AuthError("Wrong password", "PI:PASSWORD:<PASSWORD>END_PI") if not auth.isPasswordValid(password) return null @_processAuth(req, profile, checkAuthProcessor, null, callback) processOAuth: (req, profile, callback) -> ### Авторизация через OAuth ### checkAuthProcessor = (authFromSource) -> return if !!authFromSource.getEmail() return new AuthError("Can't auth user without any email", EMPTY_EMAIL_ERROR) @_processAuth(req, profile, checkAuthProcessor, null, callback) _processAuth: (req, profile, checkAuthProcessor, options, callback) -> ### Обший процесс авторизации принимает checkAuthProcessor для различных типов проверок @param callback: function ### authFromSource = authFactory(profile.provider, profile._json) AuthCouchProcessor.getById(authFromSource.getId(), (err, auth) => return callback(err) if err and err.message != 'not_found' fail = checkAuthProcessor?(authFromSource, auth) return callback(null, false, fail) if fail @afterAuthActions(req, authFromSource, auth, options, callback) ) _updateAuthFromSource: (authFromSource, auth, callback) -> ### Обновляет модель авторизации данными из source модели Возвращает в колбэк обновленную модель и флажек изменилась она или нет ### return callback(null, authFromSource, true) if not auth authFromSource.setUserId(auth.getUserId()) authFromSource.setName(auth.getName()) if not authFromSource.getName() authFromSource.setUserCompilationParams(auth.getUserCompilationParams()) callback(null, authFromSource, auth.getHash() != authFromSource.getHash()) afterAuthActions: (req, authFromSource, auth, options={}, callback) -> ### Действия после успешной авторизации ### tasks = [ (callback) => @_updateAuthFromSource(authFromSource, auth, callback) (auth, isAuthChanged, callback) -> UserCouchProcessor.getOrCreateByAuth(auth, (err, user, isAuthUserIdChanged) -> return callback(err) if err auth.updateUser(user) callback(null, auth, user, isAuthChanged or isAuthUserIdChanged) ) (auth, user, isAuthChanged, callback) => @_useProperAlgorithm(auth, user, req, options, (err, processedUser) => @_logger.error('Error while updating authorized user', {err, user, auth}) if err # возникшие ошибки (не создался Welcome topic или не смерджились аккаунты) дальше не передаем, только логгируем. callback(null, auth, processedUser or user, isAuthChanged) ) (auth, user, isAuthChanged, onSaveDone) => action = (reloadedUser, callback) -> #Будем сохранять если обробатываемый пользователь новее того, с что в базе user._rev = reloadedUser._rev callback(null, user.lastVisit >= reloadedUser.lastVisit, user, false) UserCouchProcessor.saveResolvingConflicts(user, action, (err) => if err @_logger.error('Error while saving authorized user', {err, user, auth}) else @_logSucessAuth(req, auth, user) callback(err, user) ) return onSaveDone() if not isAuthChanged AuthCouchProcessor.save(auth, (err) => @_logger.error('Error while saving user auth', {err, user, auth}) if err onSaveDone() ) ] async.waterfall(tasks, (err) -> callback(err) if err ) _logSucessAuth: (req, auth, user) -> sidKey = Conf.getSessionConf().key #Логируем часть sid-а, а не значение полностью, на случай если кто-то получит доступ к нашим логам. sid = req.cookies[sidKey]?.substr(0, 10) logObject = ip: req.connection.remoteAddress or req.socket.remoteAddress or req.connection.socket?.remoteAddress sid: sid emails: user.normalizedEmails userId: user.id authId: auth.getId() authEmail: auth.getEmail() authAlternativeEmails: auth.getAlternativeEmails() @_logger.debug("User #{user.id} #{user.email} has logged in", logObject) _useProperAlgorithm: (auth, user, req, options, callback) -> ### Выбирает нужный алгоритм авторизации: первый раз пользователь пришел или заходил раньше. @param user: UserModel @param session: object @param callback: function ### session = req.session return @_processFirstAuth(auth, user, session, options, callback) if not user.firstVisit return @_processOrdinaryAuth(auth, user, session, options, callback) _processFirstAuth: (auth, user, session, options, callback) => ### Алгоритм авторизации нового пользователя (пользователь был сосдан ранее (импорт, ручное добавление в топик), но раньше не авторизовался). ### user.setFirstAuthCondition(session.referer, session.channel, session.landing) if options.disableNotification user.notification.clearSettings() else user.notification.setDefaultSettings() session.firstVisit = true return @_processOrdinaryAuth(auth, user, session, options, callback) if options.skipWelcomeTopic WelcomeWaveBuilder.getOrCreateWelcomeWaves(user, (err, waves, isFound) => if err @_logger.error("Error while creating welcome topic for user #{user.id}", err) else for wave in waves @_logger.debug("Created welcome topic #{wave.waveId} for user #{user.id}") delete wave.internalId session.welcomeWaves = waves session.welcomeTopicJustCreated = not isFound @_processOrdinaryAuth(auth, user, session, options, callback) ) _processOrdinaryAuth: (auth, user, session, options, callback) -> ### Алгоритм авторизации существующего пользователя с существующей авторизацией (самый обычный вариант). ### session.justLoggedIn = true user.setVisitCondition() emailsToMerge = user.getNotMyEmails(auth.getAlternativeEmails()) return callback(null, user) if not emailsToMerge.length @_logger.debug("Automatic merge were started user #{user.id} with #{emailsToMerge.join(', ')}") MergeController.mergeByEmails(user, emailsToMerge, callback, true) module.exports.AuthController = new AuthController()
[ { "context": ".Batch)\n for j in [0...batchSize]\n key = \"row#{i}\"\n value = JSON.stringify\n index: i\n ", "end": 503, "score": 0.9987562894821167, "start": 495, "tag": "KEY", "value": "row#{i}\"" }, { "context": " = JSON.stringify\n index: i\n name: \"Tim\"\n age: 28\n batch.put key, value\n ", "end": 568, "score": 0.9981572031974792, "start": 565, "tag": "NAME", "value": "Tim" }, { "context": "nsole.log \"i = #{i}\" if i % 10000 == 0\n key = \"row#{i}\"\n db.get key, (err, value) ->\n throw err i", "end": 929, "score": 0.9578161239624023, "start": 921, "tag": "KEY", "value": "row#{i}\"" } ]
demo/write-read.coffee
kyledrake/node-leveldb
1
assert = require 'assert' leveldb = require '../lib' console.log 'Creating test database' path = '/tmp/wr.db' batchSize = 100 totalSize = 100000 leveldb.open path, create_if_missing: true, (err, db) -> assert.ifError err start = Date.now() i = 0 writeBenchStart = -> console.log 'Serializing and inserting 100,000 rows...' writeBench() writeBench = -> console.log "i = #{i}" if i % 10000 == 0 batch = new(leveldb.Batch) for j in [0...batchSize] key = "row#{i}" value = JSON.stringify index: i name: "Tim" age: 28 batch.put key, value ++i db.write batch, (err) -> throw err if err if i < totalSize then writeBench() else readBenchStart() readBenchStart = -> console.log 'Fetching and deserializing 100,000 rows...' readBench() readBench = -> --i console.log "i = #{i}" if i % 10000 == 0 key = "row#{i}" db.get key, (err, value) -> throw err if err value = JSON.parse value assert.equal value.index, i if i > 0 then readBench() else callback() callback = -> delta = Date.now() - start; console.log 'Completed in %d ms', delta db = null gc?() # explicit gc if enabled - useful for debugging memleaks writeBenchStart()
14266
assert = require 'assert' leveldb = require '../lib' console.log 'Creating test database' path = '/tmp/wr.db' batchSize = 100 totalSize = 100000 leveldb.open path, create_if_missing: true, (err, db) -> assert.ifError err start = Date.now() i = 0 writeBenchStart = -> console.log 'Serializing and inserting 100,000 rows...' writeBench() writeBench = -> console.log "i = #{i}" if i % 10000 == 0 batch = new(leveldb.Batch) for j in [0...batchSize] key = "<KEY> value = JSON.stringify index: i name: "<NAME>" age: 28 batch.put key, value ++i db.write batch, (err) -> throw err if err if i < totalSize then writeBench() else readBenchStart() readBenchStart = -> console.log 'Fetching and deserializing 100,000 rows...' readBench() readBench = -> --i console.log "i = #{i}" if i % 10000 == 0 key = "<KEY> db.get key, (err, value) -> throw err if err value = JSON.parse value assert.equal value.index, i if i > 0 then readBench() else callback() callback = -> delta = Date.now() - start; console.log 'Completed in %d ms', delta db = null gc?() # explicit gc if enabled - useful for debugging memleaks writeBenchStart()
true
assert = require 'assert' leveldb = require '../lib' console.log 'Creating test database' path = '/tmp/wr.db' batchSize = 100 totalSize = 100000 leveldb.open path, create_if_missing: true, (err, db) -> assert.ifError err start = Date.now() i = 0 writeBenchStart = -> console.log 'Serializing and inserting 100,000 rows...' writeBench() writeBench = -> console.log "i = #{i}" if i % 10000 == 0 batch = new(leveldb.Batch) for j in [0...batchSize] key = "PI:KEY:<KEY>END_PI value = JSON.stringify index: i name: "PI:NAME:<NAME>END_PI" age: 28 batch.put key, value ++i db.write batch, (err) -> throw err if err if i < totalSize then writeBench() else readBenchStart() readBenchStart = -> console.log 'Fetching and deserializing 100,000 rows...' readBench() readBench = -> --i console.log "i = #{i}" if i % 10000 == 0 key = "PI:KEY:<KEY>END_PI db.get key, (err, value) -> throw err if err value = JSON.parse value assert.equal value.index, i if i > 0 then readBench() else callback() callback = -> delta = Date.now() - start; console.log 'Completed in %d ms', delta db = null gc?() # explicit gc if enabled - useful for debugging memleaks writeBenchStart()
[ { "context": "me) \"top message\" \"bottom message\"\n#\n# Author:\n# lilybethshields\n# waynegraham\n\nUtil = require 'util'\n\nmemes =\n ", "end": 242, "score": 0.9992920160293579, "start": 227, "tag": "USERNAME", "value": "lilybethshields" }, { "context": "ottom message\"\n#\n# Author:\n# lilybethshields\n# waynegraham\n\nUtil = require 'util'\n\nmemes =\n \"afraid\": \"'Afr", "end": 258, "score": 0.9990631341934204, "start": 247, "tag": "USERNAME", "value": "waynegraham" }, { "context": "rs\",\n \"philosoraptor\": \"Philosoraptor\",\n \"sb\": \"Scumbag Brian\",\n \"ss\": \"Scumbag Steve\",\n \"fetch\": \"Stop Tryin", "end": 929, "score": 0.985146701335907, "start": 916, "tag": "NAME", "value": "Scumbag Brian" }, { "context": "Philosoraptor\",\n \"sb\": \"Scumbag Brian\",\n \"ss\": \"Scumbag Steve\",\n \"fetch\": \"Stop Trying to Make Fetch Happen\",\n", "end": 954, "score": 0.8983057737350464, "start": 941, "tag": "NAME", "value": "Scumbag Steve" } ]
node_modules/hubot-memes/src/memes.coffee
shashankredemption/shitpostbot
4
# Description: # Meme generator # # Dependencies: # None # # Configuration: # None # # Commands: # hubot meme list - List of memes and their codes # hubot meme me (meme) "top message" "bottom message" # # Author: # lilybethshields # waynegraham Util = require 'util' memes = "afraid": "'Afraid to Ask'", "blb": "Bad Luck Brian", "buzz": "X, X Everywhere", "wonka": "Condescending Wonka", "keanu": "Conspriracy Keanu", "live": "Do It Live!", "doge": "Doge", "ermg": "Ermahgerd", "fwp": "First World Problems", "fa": "Forever Alone", "fry": "Futurama Fry", "ggg": "Goog Guy Greg", "icanhas": "I can Has Cheezburger", "iw": "Insanity Wolf", "ll": "Laughing Lizard", "morpheus": "Matrix Morpheus", "mordor": "One Does Not Simply Walk into Mordor", "oprah": "Oprah You Get a Car", "remember": "Pepperidge Farm Remembers", "philosoraptor": "Philosoraptor", "sb": "Scumbag Brian", "ss": "Scumbag Steve", "fetch": "Stop Trying to Make Fetch Happen", "success": "Success Kid", "officespace": "That Would be Great", "interesting": "The Most Interesting Man in the World", "toohigh": "The Rent is Too Damn High", "xy": "X all the Y", "elf": "You Sit on a Throne of Lies", "chosen": "You Were the Chosen One!", "10guy": "[10] Guy" checkCode = (meme, memes) -> return meme of memes module.exports = (robot) -> meme_choices = (meme for _, meme of memes).sort().join('|') robot.respond /meme list/i, (msg) -> for code, meme of memes msg.send "#{code} - #{meme}" robot.respond /meme me (\w+) (\"[^"]+\") (\"[^"]+\")/i, (msg) -> meme = if checkCode(msg.match[1].toLowerCase(), memes) then msg.match[1].toLowerCase() else 'doge' top = msg.match[2].replace(/"/g, '').trim().replace(/\s+/g, '-') bottom = msg.match[3].replace(/"/g, '').trim().replace(/\s+/g, '-') msg.send "http://memegen.link/#{meme}/#{escape(top)}/#{escape(bottom)}.jpg"
182970
# Description: # Meme generator # # Dependencies: # None # # Configuration: # None # # Commands: # hubot meme list - List of memes and their codes # hubot meme me (meme) "top message" "bottom message" # # Author: # lilybethshields # waynegraham Util = require 'util' memes = "afraid": "'Afraid to Ask'", "blb": "Bad Luck Brian", "buzz": "X, X Everywhere", "wonka": "Condescending Wonka", "keanu": "Conspriracy Keanu", "live": "Do It Live!", "doge": "Doge", "ermg": "Ermahgerd", "fwp": "First World Problems", "fa": "Forever Alone", "fry": "Futurama Fry", "ggg": "Goog Guy Greg", "icanhas": "I can Has Cheezburger", "iw": "Insanity Wolf", "ll": "Laughing Lizard", "morpheus": "Matrix Morpheus", "mordor": "One Does Not Simply Walk into Mordor", "oprah": "Oprah You Get a Car", "remember": "Pepperidge Farm Remembers", "philosoraptor": "Philosoraptor", "sb": "<NAME>", "ss": "<NAME>", "fetch": "Stop Trying to Make Fetch Happen", "success": "Success Kid", "officespace": "That Would be Great", "interesting": "The Most Interesting Man in the World", "toohigh": "The Rent is Too Damn High", "xy": "X all the Y", "elf": "You Sit on a Throne of Lies", "chosen": "You Were the Chosen One!", "10guy": "[10] Guy" checkCode = (meme, memes) -> return meme of memes module.exports = (robot) -> meme_choices = (meme for _, meme of memes).sort().join('|') robot.respond /meme list/i, (msg) -> for code, meme of memes msg.send "#{code} - #{meme}" robot.respond /meme me (\w+) (\"[^"]+\") (\"[^"]+\")/i, (msg) -> meme = if checkCode(msg.match[1].toLowerCase(), memes) then msg.match[1].toLowerCase() else 'doge' top = msg.match[2].replace(/"/g, '').trim().replace(/\s+/g, '-') bottom = msg.match[3].replace(/"/g, '').trim().replace(/\s+/g, '-') msg.send "http://memegen.link/#{meme}/#{escape(top)}/#{escape(bottom)}.jpg"
true
# Description: # Meme generator # # Dependencies: # None # # Configuration: # None # # Commands: # hubot meme list - List of memes and their codes # hubot meme me (meme) "top message" "bottom message" # # Author: # lilybethshields # waynegraham Util = require 'util' memes = "afraid": "'Afraid to Ask'", "blb": "Bad Luck Brian", "buzz": "X, X Everywhere", "wonka": "Condescending Wonka", "keanu": "Conspriracy Keanu", "live": "Do It Live!", "doge": "Doge", "ermg": "Ermahgerd", "fwp": "First World Problems", "fa": "Forever Alone", "fry": "Futurama Fry", "ggg": "Goog Guy Greg", "icanhas": "I can Has Cheezburger", "iw": "Insanity Wolf", "ll": "Laughing Lizard", "morpheus": "Matrix Morpheus", "mordor": "One Does Not Simply Walk into Mordor", "oprah": "Oprah You Get a Car", "remember": "Pepperidge Farm Remembers", "philosoraptor": "Philosoraptor", "sb": "PI:NAME:<NAME>END_PI", "ss": "PI:NAME:<NAME>END_PI", "fetch": "Stop Trying to Make Fetch Happen", "success": "Success Kid", "officespace": "That Would be Great", "interesting": "The Most Interesting Man in the World", "toohigh": "The Rent is Too Damn High", "xy": "X all the Y", "elf": "You Sit on a Throne of Lies", "chosen": "You Were the Chosen One!", "10guy": "[10] Guy" checkCode = (meme, memes) -> return meme of memes module.exports = (robot) -> meme_choices = (meme for _, meme of memes).sort().join('|') robot.respond /meme list/i, (msg) -> for code, meme of memes msg.send "#{code} - #{meme}" robot.respond /meme me (\w+) (\"[^"]+\") (\"[^"]+\")/i, (msg) -> meme = if checkCode(msg.match[1].toLowerCase(), memes) then msg.match[1].toLowerCase() else 'doge' top = msg.match[2].replace(/"/g, '').trim().replace(/\s+/g, '-') bottom = msg.match[3].replace(/"/g, '').trim().replace(/\s+/g, '-') msg.send "http://memegen.link/#{meme}/#{escape(top)}/#{escape(bottom)}.jpg"
[ { "context": "cle: \"the \" }\n cards:\n mustard: { name: \"Colonel Mustard\", type: \"suspect\" }\n white: { name: \"Mr", "end": 930, "score": 0.9995312690734863, "start": 915, "tag": "NAME", "value": "Colonel Mustard" }, { "context": "rd\", type: \"suspect\" }\n white: { name: \"Mrs. White\", type: \"suspect\" }\n plum: { name", "end": 988, "score": 0.9966227412223816, "start": 978, "tag": "NAME", "value": "Mrs. White" }, { "context": " type: \"suspect\" }\n plum: { name: \"Professor Plum\", type: \"suspect\" }\n peacock: { name: \"M", "end": 1055, "score": 0.9993429183959961, "start": 1041, "tag": "NAME", "value": "Professor Plum" }, { "context": "m\", type: \"suspect\" }\n peacock: { name: \"Mrs. Peacock\", type: \"suspect\" }\n green: { name: ", "end": 1116, "score": 0.9989816546440125, "start": 1104, "tag": "NAME", "value": "Mrs. Peacock" }, { "context": ", type: \"suspect\" }\n green: { name: \"Mr. Green\", type: \"suspect\" }\n scarlet: { nam", "end": 1176, "score": 0.9908329844474792, "start": 1167, "tag": "NAME", "value": "Mr. Green" }, { "context": " type: \"suspect\" }\n scarlet: { name: \"Miss Scarlet\", type: \"suspect\" }\n revolver: { name: ", "end": 1242, "score": 0.9995983242988586, "start": 1230, "tag": "NAME", "value": "Miss Scarlet" }, { "context": ", type: \"suspect\" }\n revolver: { name: \"Revolver\", type: \"weapon\" }\n knife: { na", "end": 1301, "score": 0.8686612844467163, "start": 1293, "tag": "NAME", "value": "Revolver" }, { "context": " type: \"weapon\" }\n knife: { name: \"Knife\", type: \"weapon\" }\n rope: {", "end": 1361, "score": 0.6828857064247131, "start": 1356, "tag": "NAME", "value": "Knife" }, { "context": "pon\", \"room\" ]\n\nmaster_detective =\n name: \"Master Detective\"\n rulesId : \"master\"\n minPlayers: 3\n maxPlay", "end": 2313, "score": 0.9948844909667969, "start": 2297, "tag": "NAME", "value": "Master Detective" }, { "context": "le: \"the \" }\n cards :\n mustard: { name: \"Colonel Mustard\", type: \"suspect\" }\n white: { name: \"", "end": 2655, "score": 0.999674379825592, "start": 2640, "tag": "NAME", "value": "Colonel Mustard" }, { "context": "\", type: \"suspect\" }\n white: { name: \"Mrs. White\", type: \"suspect\" }\n plum: { na", "end": 2715, "score": 0.9963006973266602, "start": 2705, "tag": "NAME", "value": "Mrs. White" }, { "context": " type: \"suspect\" }\n plum: { name: \"Professor Plum\", type: \"suspect\" }\n peacock: { name: ", "end": 2784, "score": 0.9997107982635498, "start": 2770, "tag": "NAME", "value": "Professor Plum" }, { "context": ", type: \"suspect\" }\n peacock: { name: \"Mrs. Peacock\", type: \"suspect\" }\n green: { name", "end": 2847, "score": 0.9989166259765625, "start": 2835, "tag": "NAME", "value": "Mrs. Peacock" }, { "context": " type: \"suspect\" }\n green: { name: \"Mr. Green\", type: \"suspect\" }\n scarlet: { n", "end": 2909, "score": 0.9984355568885803, "start": 2900, "tag": "NAME", "value": "Mr. Green" }, { "context": " type: \"suspect\" }\n scarlet: { name: \"Miss Scarlet\", type: \"suspect\" }\n rose: { name", "end": 2977, "score": 0.9997929334640503, "start": 2965, "tag": "NAME", "value": "Miss Scarlet" }, { "context": " type: \"suspect\" }\n rose: { name: \"Madame Rose\", type: \"suspect\" }\n gray: { nam", "end": 3041, "score": 0.9998213052749634, "start": 3030, "tag": "NAME", "value": "Madame Rose" }, { "context": " type: \"suspect\" }\n gray: { name: \"Sergeant Gray\", type: \"suspect\" }\n brunette: { name:", "end": 3108, "score": 0.999841570854187, "start": 3095, "tag": "NAME", "value": "Sergeant Gray" }, { "context": " type: \"suspect\" }\n brunette: { name: \"Monsieur Brunette\", type: \"suspect\" }\n peach: { name: \"Mi", "end": 3177, "score": 0.9998184442520142, "start": 3160, "tag": "NAME", "value": "Monsieur Brunette" }, { "context": "te\", type: \"suspect\" }\n peach: { name: \"Miss Peach\", type: \"suspect\" }\n revolver: { na", "end": 3235, "score": 0.9997780919075012, "start": 3225, "tag": "NAME", "value": "Miss Peach" }, { "context": "cle: \"the \" }\n cards:\n pluto: { name: \"Pluto\", type: \"guest\" }\n daisy: { ", "end": 4990, "score": 0.9994775652885437, "start": 4985, "tag": "NAME", "value": "Pluto" }, { "context": " { name: \"Pluto\", type: \"guest\" }\n daisy: { name: \"Daisy Duck\", type: \"gue", "end": 5026, "score": 0.8540442585945129, "start": 5024, "tag": "NAME", "value": "da" }, { "context": " type: \"guest\" }\n daisy: { name: \"Daisy Duck\", type: \"guest\" }\n goofy: { name:", "end": 5057, "score": 0.999750018119812, "start": 5047, "tag": "NAME", "value": "Daisy Duck" }, { "context": " type: \"guest\" }\n goofy: { name: \"Goofy\", type: \"guest\" }\n donald: { ", "end": 5114, "score": 0.9996108412742615, "start": 5109, "tag": "NAME", "value": "Goofy" }, { "context": " { name: \"Goofy\", type: \"guest\" }\n donald: { name: \"Donald Duck\", type: \"guest\" ", "end": 5154, "score": 0.8247387409210205, "start": 5148, "tag": "NAME", "value": "donald" }, { "context": " type: \"guest\" }\n donald: { name: \"Donald Duck\", type: \"guest\" }\n minnie: { name: ", "end": 5182, "score": 0.9996986389160156, "start": 5171, "tag": "NAME", "value": "Donald Duck" }, { "context": ", type: \"guest\" }\n minnie: { name: \"Minnie Mouse\", type: \"guest\" }\n mickey: { name: \"", "end": 5245, "score": 0.9995209574699402, "start": 5233, "tag": "NAME", "value": "Minnie Mouse" }, { "context": "\", type: \"guest\" }\n mickey: { name: \"Mickey Mouse\", type: \"guest\" }\n prisoner: { name: \"", "end": 5307, "score": 0.9995343685150146, "start": 5295, "tag": "NAME", "value": "Mickey Mouse" }, { "context": "\", type: \"guest\" }\n prisoner: { name: \"Prisoner\", type: \"ghost\" }\n singer: { nam", "end": 5365, "score": 0.9981645345687866, "start": 5357, "tag": "NAME", "value": "Prisoner" }, { "context": " type: \"ghost\" }\n singer: { name: \"Opera Singer\", type: \"ghost\" }\n bride: { name: \"", "end": 5431, "score": 0.9996774792671204, "start": 5419, "tag": "NAME", "value": "Opera Singer" }, { "context": "\", type: \"ghost\" }\n bride: { name: \"Bride\", type: \"ghost\" }\n traveler: { ", "end": 5486, "score": 0.9950590133666992, "start": 5481, "tag": "NAME", "value": "Bride" }, { "context": " type: \"ghost\" }\n traveler: { name: \"Traveler\", type: \"ghost\" }\n mariner: { nam", "end": 5551, "score": 0.9786351323127747, "start": 5543, "tag": "NAME", "value": "Traveler" }, { "context": " type: \"ghost\" }\n mariner: { name: \"Mariner\", type: \"ghost\" }\n skeleton: { na", "end": 5612, "score": 0.9965678453445435, "start": 5605, "tag": "NAME", "value": "Mariner" }, { "context": " type: \"ghost\" }\n skeleton: { name: \"Candlestick\", type: \"ghost\" }\n graveyard: { name: ", "end": 5678, "score": 0.7969850897789001, "start": 5667, "tag": "NAME", "value": "Candlestick" }, { "context": " type: \"room\" }\n attic: { name: \"Attic\", type: \"room\" }\n mausoleum: { ", "end": 5920, "score": 0.9776519536972046, "start": 5915, "tag": "NAME", "value": "Attic" }, { "context": " type: \"room\" }\n mausoleum: { name: \"Mausoleum\", type: \"room\" }\n conservatory: { name", "end": 5986, "score": 0.9620409607887268, "start": 5977, "tag": "NAME", "value": "Mausoleum" }, { "context": " type: \"room\" }\n foyer: { name: \"Foyer\", type: \"room\" }\n chamber: { ", "end": 6168, "score": 0.9980608820915222, "start": 6163, "tag": "NAME", "value": "Foyer" }, { "context": "t\", \"guest\", \"room\" ]\n\nstar_wars =\n name: \"Star Wars\"\n rulesId: \"star_wars\"\n minPlayers: 3\n maxP", "end": 6345, "score": 0.904427707195282, "start": 6336, "tag": "NAME", "value": "Star Wars" }, { "context": "article: \"a \" }\n cards:\n alderaan: { name: \"Alderaan\", type: \"planet\" }\n bespin: ", "end": 6728, "score": 0.9989263415336609, "start": 6720, "tag": "NAME", "value": "Alderaan" }, { "context": " type: \"planet\" }\n bespin: { name: \"Bespin\", type: \"planet\" }\n dagobah: ", "end": 6793, "score": 0.9994328618049622, "start": 6787, "tag": "NAME", "value": "Bespin" }, { "context": " type: \"planet\" }\n dagobah: { name: \"Dagobah\", type: \"planet\" }\n endor: ", "end": 6861, "score": 0.9990535378456116, "start": 6854, "tag": "NAME", "value": "Dagobah" }, { "context": " type: \"planet\" }\n endor: { name: \"Endor\", type: \"planet\" }\n tattoine:", "end": 6926, "score": 0.9974777698516846, "start": 6921, "tag": "NAME", "value": "Endor" }, { "context": " type: \"planet\" }\n tattoine: { name: \"Tatooine\", type: \"planet\" }\n yavin: ", "end": 6996, "score": 0.999026358127594, "start": 6988, "tag": "NAME", "value": "Tatooine" }, { "context": " type: \"planet\" }\n yavin: { name: \"Yavin 4\", type: \"planet\" }\n millenium: ", "end": 7062, "score": 0.998825192451477, "start": 7055, "tag": "NAME", "value": "Yavin 4" }, { "context": " type: \"planet\" }\n millenium: { name: \"Millenium Falcon\", type: \"ship\" }\n xwing: { name: ", "end": 7138, "score": 0.9977504014968872, "start": 7122, "tag": "NAME", "value": "Millenium Falcon" }, { "context": ", type: \"ship\" }\n xwing: { name: \"X-Wing\", type: \"ship\" }\n ywing: ", "end": 7195, "score": 0.9968758225440979, "start": 7189, "tag": "NAME", "value": "X-Wing" }, { "context": " type: \"ship\" }\n ywing: { name: \"Y-Wing\", type: \"ship\" }\n tiefighter", "end": 7262, "score": 0.994295597076416, "start": 7256, "tag": "NAME", "value": "Y-Wing" }, { "context": " type: \"ship\" }\n tiefighter: { name: \"Tie Fighter\", type: \"ship\" }\n pod: { n", "end": 7334, "score": 0.9978764653205872, "start": 7323, "tag": "NAME", "value": "Tie Fighter" }, { "context": " type: \"ship\" }\n pod: { name: \"Escape Pod\", type: \"ship\" }\n tiebomber: { ", "end": 7400, "score": 0.771436870098114, "start": 7397, "tag": "NAME", "value": "Pod" }, { "context": " type: \"ship\" }\n tiebomber: { name: \"Tie Bomber\", type: \"ship\" }\n laser: { ", "end": 7467, "score": 0.9965413808822632, "start": 7457, "tag": "NAME", "value": "Tie Bomber" }, { "context": ", \"room\", \"ship\" ]\n\nharry_potter =\n name: \"Harry Potter\"\n rulesId: \"classic\"\n minPlayers: 3\n maxPla", "end": 8193, "score": 0.999804675579071, "start": 8181, "tag": "NAME", "value": "Harry Potter" }, { "context": "icle: \"the \" }\n cards:\n draco: { name: \"Draco Malfoy\", type: \"suspect\" }\n crabbe: ", "end": 8524, "score": 0.9998546838760376, "start": 8512, "tag": "NAME", "value": "Draco Malfoy" }, { "context": " type: \"suspect\" }\n crabbe: { name: \"Crabbe & Doyle\", type: \"suspect\" }\n lucius: {", "end": 8598, "score": 0.9991298317909241, "start": 8584, "tag": "NAME", "value": "Crabbe & Doyle" }, { "context": " type: \"suspect\" }\n lucius: { name: \"Lucius Malfoy\", type: \"suspect\" }\n delores: ", "end": 8669, "score": 0.9998565912246704, "start": 8656, "tag": "NAME", "value": "Lucius Malfoy" }, { "context": " type: \"suspect\" }\n delores: { name: \"Delores Umbridge\", type: \"suspect\" }\n peter: { n", "end": 8744, "score": 0.9998542070388794, "start": 8728, "tag": "NAME", "value": "Delores Umbridge" }, { "context": " type: \"suspect\" }\n peter: { name: \"Peter Pettigrew\", type: \"suspect\" }\n bellatrix: { ", "end": 8815, "score": 0.9998483657836914, "start": 8800, "tag": "NAME", "value": "Peter Pettigrew" }, { "context": " type: \"suspect\" }\n bellatrix: { name: \"Bellatrix LeStrange\", type: \"suspect\" }\n draught: { name", "end": 8891, "score": 0.9998552203178406, "start": 8872, "tag": "NAME", "value": "Bellatrix LeStrange" }, { "context": " type: \"item\" }\n portkey: { name: \"Portkey\", type: \"item\" }\n impedime", "end": 9093, "score": 0.9937945008277893, "start": 9086, "tag": "NAME", "value": "Portkey" }, { "context": " type: \"item\" }\n impedimenta: { name: \"Impedienta\", type: \"item\" }\n petrif", "end": 9162, "score": 0.795604407787323, "start": 9160, "tag": "NAME", "value": "ed" }, { "context": " type: \"item\" }\n petrifus: { name: \"Petrifus Totalus\", type: \"item\" }\n mandarke: { na", "end": 9244, "score": 0.9779868125915527, "start": 9228, "tag": "NAME", "value": "Petrifus Totalus" }, { "context": " type: \"item\" }\n mandarke: { name: \"Mandrake\", type: \"item\" }\n hall: ", "end": 9307, "score": 0.994936466217041, "start": 9299, "tag": "NAME", "value": "Mandrake" }, { "context": "nfigurations[@configurationId]}\n players={@playerIds}\n onDone={@recordHand}\n onClose={()", "end": 24015, "score": 0.7682719230651855, "start": 24006, "tag": "USERNAME", "value": "playerIds" }, { "context": "nfigurations[@configurationId]}\n players={@playerIds}\n onDone={@recordSuggestion}\n onClo", "end": 24280, "score": 0.7435153126716614, "start": 24271, "tag": "USERNAME", "value": "playerIds" }, { "context": "nfigurations[@configurationId]}\n players={@playerIds}\n onDone={@recordShown}\n onClose", "end": 24545, "score": 0.6846708655357361, "start": 24539, "tag": "USERNAME", "value": "player" }, { "context": "nfigurations[@configurationId]}\n players={@playerIds}\n onDone={@recordAccusation}\n onClo", "end": 24812, "score": 0.7372775077819824, "start": 24803, "tag": "USERNAME", "value": "playerIds" }, { "context": "nfigurations[@configurationId]}\n players={@playerIds}\n onDone={@recordCommlink}\n onCl", "end": 25084, "score": 0.6914141774177551, "start": 25078, "tag": "USERNAME", "value": "player" } ]
cs/App.coffee
jambolo/NotAClue
0
` import Solver from './Solver' import AccuseDialog from './AccuseDialog' import CommlinkDialog from './CommlinkDialog' import ConfirmDialog from './ConfirmDialog' import ExportDialog from './ExportDialog' import HandDialog from './HandDialog' import ImportDialog from './ImportDialog' import LogDialog from './LogDialog' import MainMenu from './MainMenu' import MainView from './MainView' import React, { Component } from 'react'; import SetupDialog from './SetupDialog' import ShowDialog from './ShowDialog' import SuggestDialog from './SuggestDialog' ` classic = name: "Classic" rulesId: "classic" minPlayers: 3 maxPlayers: 6 types: suspect: { title: "Suspects", preposition: "", article: "" } weapon: { title: "Weapons", preposition: "with ", article: "the " } room: { title: "Rooms", preposition: "in ", article: "the " } cards: mustard: { name: "Colonel Mustard", type: "suspect" } white: { name: "Mrs. White", type: "suspect" } plum: { name: "Professor Plum", type: "suspect" } peacock: { name: "Mrs. Peacock", type: "suspect" } green: { name: "Mr. Green", type: "suspect" } scarlet: { name: "Miss Scarlet", type: "suspect" } revolver: { name: "Revolver", type: "weapon" } knife: { name: "Knife", type: "weapon" } rope: { name: "Rope", type: "weapon" } pipe: { name: "Lead pipe", type: "weapon" } wrench: { name: "Wrench", type: "weapon" } candlestick: { name: "Candlestick", type: "weapon" } dining: { name: "Dining Room", type: "room" } conservatory: { name: "Conservatory", type: "room" } kitchen: { name: "Kitchen", type: "room" } study: { name: "Study", type: "room" } library: { name: "Library", type: "room" } billiard: { name: "Billiards Room", type: "room" } lounge: { name: "Lounge", type: "room" } ballroom: { name: "Ballroom", type: "room" } hall: { name: "Hall", type: "room" } suggestionOrder: [ "suspect", "weapon", "room" ] master_detective = name: "Master Detective" rulesId : "master" minPlayers: 3 maxPlayers: 10 types : suspect: { title: "Suspects", preposition: "", article: "" } weapon: { title: "Weapons", preposition: "with ", article: "the " } room: { title: "Rooms", preposition: "in ", article: "the " } cards : mustard: { name: "Colonel Mustard", type: "suspect" } white: { name: "Mrs. White", type: "suspect" } plum: { name: "Professor Plum", type: "suspect" } peacock: { name: "Mrs. Peacock", type: "suspect" } green: { name: "Mr. Green", type: "suspect" } scarlet: { name: "Miss Scarlet", type: "suspect" } rose: { name: "Madame Rose", type: "suspect" } gray: { name: "Sergeant Gray", type: "suspect" } brunette: { name: "Monsieur Brunette", type: "suspect" } peach: { name: "Miss Peach", type: "suspect" } revolver: { name: "Revolver", type: "weapon" } knife: { name: "Knife", type: "weapon" } rope: { name: "Rope", type: "weapon" } pipe: { name: "Pipe", type: "weapon" } wrench: { name: "Wrench", type: "weapon" } candlestick: { name: "Candlestick", type: "weapon" } poison: { name: "Poison", type: "weapon" } horseshoe: { name: "Horseshoe", type: "weapon" } dining: { name: "Dining Room", type: "room" } conservatory: { name: "Conservatory", type: "room" } kitchen: { name: "Kitchen", type: "room" } studio: { name: "Studio", type: "room" } library: { name: "Library", type: "room" } billiard: { name: "Billiard Room", type: "room" } courtyard: { name: "Courtyard", type: "room" } gazebo: { name: "Gazebo", type: "room" } drawing: { name: "Drawing Room", type: "room" } carriage: { name: "Carriage House", type: "room" } trophy: { name: "Trophy Room", type: "room" } fountain: { name: "Fountain", type: "room" } suggestionOrder: [ "suspect", "weapon", "room" ] haunted_mansion = name: "Haunted Mansion" rulesId: "classic" minPlayers: 3 maxPlayers: 6 types: guest: { title: "Guests", preposition: "haunted ", article: "" } ghost: { title: "Ghosts", preposition: "", article: "the " } room: { title: "Rooms", preposition: "in ", article: "the " } cards: pluto: { name: "Pluto", type: "guest" } daisy: { name: "Daisy Duck", type: "guest" } goofy: { name: "Goofy", type: "guest" } donald: { name: "Donald Duck", type: "guest" } minnie: { name: "Minnie Mouse", type: "guest" } mickey: { name: "Mickey Mouse", type: "guest" } prisoner: { name: "Prisoner", type: "ghost" } singer: { name: "Opera Singer", type: "ghost" } bride: { name: "Bride", type: "ghost" } traveler: { name: "Traveler", type: "ghost" } mariner: { name: "Mariner", type: "ghost" } skeleton: { name: "Candlestick", type: "ghost" } graveyard: { name: "Graveyard", type: "room" } seance: { name: "Seance Room", type: "room" } ballroom: { name: "Ballroom", type: "room" } attic: { name: "Attic", type: "room" } mausoleum: { name: "Mausoleum", type: "room" } conservatory: { name: "Conservatory", type: "room" } library: { name: "Library", type: "room" } foyer: { name: "Foyer", type: "room" } chamber: { name: "Portrait Chamber", type: "room" } suggestionOrder: [ "ghost", "guest", "room" ] star_wars = name: "Star Wars" rulesId: "star_wars" minPlayers: 3 maxPlayers: 6 types: planet: { title: "Planets", preposition: "Darth Vader is targeting ", article: "" } room: { title: "Rooms", preposition: ", the plans are in ", article: "the " } ship: { title: "Ships", preposition: ", and we can escape in ", article: "a " } cards: alderaan: { name: "Alderaan", type: "planet" } bespin: { name: "Bespin", type: "planet" } dagobah: { name: "Dagobah", type: "planet" } endor: { name: "Endor", type: "planet" } tattoine: { name: "Tatooine", type: "planet" } yavin: { name: "Yavin 4", type: "planet" } millenium: { name: "Millenium Falcon", type: "ship" } xwing: { name: "X-Wing", type: "ship" } ywing: { name: "Y-Wing", type: "ship" } tiefighter: { name: "Tie Fighter", type: "ship" } pod: { name: "Escape Pod", type: "ship" } tiebomber: { name: "Tie Bomber", type: "ship" } laser: { name: "Laser Control Room", type: "room" } overbridge: { name: "Overbridge", type: "room" } docking: { name: "Docking Bay", type: "room" } red: { name: "Red Control Room", type: "room" } war: { name: "War Room", type: "room" } detention: { name: "Detention Block", type: "room" } throne: { name: "Throne Room", type: "room" } trash: { name: "Trash Compactor", type: "room" } tractor: { name: "Tractor Beam Generator", type: "room" } suggestionOrder: [ "planet", "room", "ship" ] harry_potter = name: "Harry Potter" rulesId: "classic" minPlayers: 3 maxPlayers: 6 types: suspect: { title: "Suspects", preposition: "", article: "" } item: { title: "Items", preposition: "with ", article: "a " } room: { title: "Rooms", preposition: "in ", article: "the " } cards: draco: { name: "Draco Malfoy", type: "suspect" } crabbe: { name: "Crabbe & Doyle", type: "suspect" } lucius: { name: "Lucius Malfoy", type: "suspect" } delores: { name: "Delores Umbridge", type: "suspect" } peter: { name: "Peter Pettigrew", type: "suspect" } bellatrix: { name: "Bellatrix LeStrange", type: "suspect" } draught: { name: "Sleeping Draught", type: "item" } cabinet: { name: "Vanishing Cabinet", type: "item" } portkey: { name: "Portkey", type: "item" } impedimenta: { name: "Impedienta", type: "item" } petrifus: { name: "Petrifus Totalus", type: "item" } mandarke: { name: "Mandrake", type: "item" } hall: { name: "Great Hall", type: "room" } hospital: { name: "Hospital Wing", type: "room" } requirement: { name: "Room of Requirement", type: "room" } potions: { name: "Potions ClassRoom", type: "room" } trophy: { name: "Trophy Room", type: "room" } divination: { name: "Divination Classroom", type: "room" } owlry: { name: "Owlry", type: "room" } library: { name: "Library", type: "room" } defense: { name: "Defense Against Dark Arts", type: "room" } suggestionOrder: [ "suspect", "item", "room" ] configurations = classic: classic master_detective: master_detective haunted_mansion: haunted_mansion star_wars: star_wars harry_potter: harry_potter class App extends Component constructor: (props) -> super props @solver = null @accusationId = 1 @commlinkId = 1 @suggestionId = 1 @playerIds = [] @configurationId = "master_detective" @log = [] @state = mainMenuAnchor: null newGameDialogOpen: false importDialogOpen: false logDialogOpen: false exportDialogOpen: false confirmDialog: open: false title: '' question: '' yesAction: null noAction: null handDialogOpen: false suggestDialogOpen: false showDialogOpen: false accuseDialogOpen: false commlinkDialogOpen: false return setUpNewGame: (configurationId, playerIds) => @accusationId = 1 @commlinkId = 1 @suggestionId = 1 @playerIds = playerIds @configurationId = configurationId @log = [] @recordSetup configurationId, playerIds return importLog: (imported) => parsedLog = null try parsedLog = JSON.parse(imported) catch e console.log(JSON.stringify(e, 2)) @showConfirmDialog( "Import Error", "The input is not valid JSON." ) return if not parsedLog? or parsedLog not instanceof Array or not parsedLog[0]? or not parsedLog[0].setup? @showConfirmDialog( "Import Error", "The first entry in the log is not a \"setup\" entry." ) return setup = parsedLog[0].setup # Parse the setup entry if not setup.variation? or not setup.players? @showConfirmDialog( "Import Error", "The setup entry must have a \"variation\" property and a \"players\" property." ) return { variation, players } = setup if not configurations[variation]? @showConfirmDialog( "Import Error", "The variation \"#{variation}\" is not supported. The following variations are supported: #{Object.keys(configurations)}" ) return configuration = configurations[variation] if players not instanceof Array or players.length < configuration.minPlayers or players.length > configuration.maxPlayers @showConfirmDialog( "Import Error", "This variation requires #{configuration.minPlayers} to #{configuration.maxPlayers} players." ) return if "ANSWER" in players or "Nobody" in players @showConfirmDialog( "Import Error", "The uses of the names \"ANSWER\" and \"Nobody\" are reserved." ) return configuration = configurations[variation] # Process the setup @setUpNewGame variation, players # Player and card lists for reporting errors playerList = "#{players}" cardList = "#{Object.keys(configuration.cards)}" # Process each entry that follows for entry in parsedLog[1..] # Hand entry if entry.hand? hand = entry.hand if not hand.player? or not hand.cards? @showConfirmDialog( "Import Error", "The hand entry must have a \"player\" property and a \"cards\" property." ) return { player, cards } = hand if player not in players @showConfirmDialog( "Import Error", "\"#{player}\" is not in the list of players. Valid players are #{playerList}" ) return if cards not instanceof Array @showConfirmDialog( "Import Error", "The hand.cards property must be an array of cards." ) return for card in cards if not configuration.cards[card]? @showConfirmDialog( "Import Error", "\"#{card}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return @recordHand player, cards # Suggest entry else if entry.suggest? suggestion = entry.suggest if not suggestion.suggester? or not suggestion.cards? or not suggestion.showed? @showConfirmDialog( "Import Error", "The suggest entry must have a \"suggester\" property, a \"cards\" property, and a \"showed\" property." ) return { suggester, cards, showed } = suggestion if suggester not in players @showConfirmDialog( "Import Error", "\"#{suggester}\" is not in the list of players. Valid players are #{playerList}" ) return if cards not instanceof Array @showConfirmDialog( "Import Error", "The suggest.cards property must be an array of cards." ) return for c in cards if not configuration.cards[c]? @showConfirmDialog( "Import Error", "\"#{c}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return if showed not instanceof Array @showConfirmDialog( "Import Error", "The suggest.showed property must be an array of players." ) return for s in showed if s not in players @showConfirmDialog( "Import Error", "\"#{s}\" is not in the list of players. Valid players are #{playerList}" ) return @recordSuggestion suggester, cards, showed # Show entry else if entry.show? show = entry.show if not show.player? or not show.card? @showConfirmDialog( "Import Error", "The show entry must have a \"player\" property, and a \"card\" property." ) return { player, card } = show if player not in players @showConfirmDialog( "Import Error", "\"#{player}\" is not in the list of players. Valid players are #{playerList}" ) return if not configuration.cards[card]? @showConfirmDialog( "Import Error", "\"#{card}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return @recordShown player, card # Accuse entry else if entry.accuse? accusation = entry.accuse console.log JSON.stringify(accusation) console.log "" if not accusation.accuser? or not accusation.cards? or not accusation.correct? @showConfirmDialog( "Import Error", "The accuse entry must have an \"accuser\" property, a \"cards\" property, and a \"correct\" property." ) return { accuser, cards, correct } = accusation if accuser not in players @showConfirmDialog( "Import Error", "\"#{accuser}\" is not in the player list. Valid players are #{playerList}" ) return if cards not instanceof Array @showConfirmDialog( "Import Error", "The accuse.cards property must be an array of cards." ) return for c in cards if not configuration.cards[c]? @showConfirmDialog( "Import Error", "\"#{c}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return if typeof(correct) != typeof(true) @showConfirmDialog( "Import Error", "The accuse.correct property must be true or false." ) return @recordAccusation accuser, cards, correct # Commlink entry (if Star Wars edition) else if entry.commlink? and setup.variation is "star_wars" commlink = entry.commlink if not commlink.caller? or not commlink.receiver? or not commlink.cards? or not commlink.showed? @showConfirmDialog( "Import Error", "The commlink entry must have a \"caller\" property, a \"receiver\" property, a \"cards\" property, and a \"showed\" property." ) return { caller, receiver, cards, showed } = commlink if caller not in players @showConfirmDialog( "Import Error", "\"#{caller}\" is not in the player list. Valid players are #{playerList}" ) return if receiver not in players @showConfirmDialog( "Import Error", "\"#{receiver}\" is not in the player list. Valid players are #{playerList}" ) return if cards not instanceof Array @showConfirmDialog( "Import Error", "The commlink.cards property must be an array of cards." ) return for c in cards if not configuration.cards[c]? @showConfirmDialog( "Import Error", "\"#{c}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return if typeof(showed) != typeof(true) @showConfirmDialog( "Import Error", "The commlink.showed property must be true or false." ) return @recordCommlink caller, receiver, cards, showed # Otherwise, unknown entry else @showConfirmDialog( "Import Error", "Unsupported imported log entry: #{JSON.stringify(entry)}." ) return return # Component launchers showMainMenu: (anchor) => @setState { mainMenuAnchor: anchor } return showNewGameDialog: => @setState { newGameDialogOpen: true } return showImportDialog: => @setState { importDialogOpen: true } return showLog: => @setState { logDialogOpen: true } return showExportDialog: => @setState { exportDialogOpen: true } return showConfirmDialog: (title, question, yesAction, noAction) => @setState confirmDialog: open: true title: title question: question yesAction: yesAction noAction: noAction return showHandDialog: => @setState { handDialogOpen: true } return showSuggestDialog: => @setState { suggestDialogOpen: true } return showShowDialog: => @setState { showDialogOpen: true } return showAccuseDialog: => @setState { accuseDialogOpen: true } return showCommlinkDialog: => @setState { commlinkDialogOpen: true } return # Solver state updaters recordSetup: (configurationId, playerIds) => @solver = new Solver(configurations[configurationId], playerIds) @log.push setup: variation: configurationId players: playerIds recordHand: (playerId, cardIds) => if @solver? @solver.hand playerId, cardIds @log.push hand: player: playerId cards: cardIds return recordSuggestion: (suggesterId, cardIds, showedIds) => if @solver? id = @suggestionId++ @solver.suggest suggesterId, cardIds, showedIds, id @log.push suggest: id: id suggester: suggesterId cards: cardIds showed: showedIds return recordShown: (playerId, cardId) => if @solver? @solver.show playerId, cardId @log.push show: player: playerId card: cardId return recordAccusation: (accuserId, cardIds, correct) => if @solver? id = @accusationId++ @solver.accuse accuserId, cardIds, correct, id @log.push accuse: id: id accuser: accuserId cards: cardIds correct: correct return recordCommlink: (callerId, receiverId, cardIds, showed) => if @solver? id = @commlinkId++ @solver.commlink callerId, receiverId, cardIds, showed, id @log.push commlink: id: id caller: callerId receiver: receiverId cards: cardIds showed: showed return render: -> <div className="App"> <MainView configurationId={@configurationId} solver={@solver} onMenu={@showMainMenu} app={this} /> <MainMenu anchor={@state.mainMenuAnchor} started={@solver?} onClose={() => @setState({ mainMenuAnchor: null })} app={this} /> <SetupDialog open={@state.newGameDialogOpen} configurations={configurations} onDone={@setUpNewGame} onClose={() => @setState({ newGameDialogOpen: false })} app={this} /> <ImportDialog open={@state.importDialogOpen} configurations={configurations} onDone={@importLog} onClose={() => @setState({ importDialogOpen: false })} app={this} /> <LogDialog open={@state.logDialogOpen} log={@log} configurations={configurations} onClose={() => @setState({ logDialogOpen: false })} app={this} /> <ExportDialog open={@state.exportDialogOpen} log={@log} onClose={() => @setState({ exportDialogOpen: false })} app={this} /> <ConfirmDialog open={@state.confirmDialog.open} title={@state.confirmDialog.title} question={@state.confirmDialog.question} yesAction={@state.confirmDialog.yesAction} noAction={@state.confirmDialog.noAction} onClose={@handleConfirmDialogClose} app={this} /> <HandDialog open={@state.handDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordHand} onClose={() => @setState({ handDialogOpen: false })} app={this} /> <SuggestDialog open={@state.suggestDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordSuggestion} onClose={() => @setState({ suggestDialogOpen: false })} app={this} /> <ShowDialog open={@state.showDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordShown} onClose={() => @setState({ showDialogOpen: false })} app={this} /> <AccuseDialog open={@state.accuseDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordAccusation} onClose={() => @setState({ accuseDialogOpen: false })} app={this} /> <CommlinkDialog open={@state.commlinkDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordCommlink} onClose={() => @setState({ commlinkDialogOpen: false })} app={this} /> </div> # Callbacks handleConfirmDialogClose: => @setState { confirmDialog: open: false title: "" question: "" yesAction: null noAction: null } return export default App
141058
` import Solver from './Solver' import AccuseDialog from './AccuseDialog' import CommlinkDialog from './CommlinkDialog' import ConfirmDialog from './ConfirmDialog' import ExportDialog from './ExportDialog' import HandDialog from './HandDialog' import ImportDialog from './ImportDialog' import LogDialog from './LogDialog' import MainMenu from './MainMenu' import MainView from './MainView' import React, { Component } from 'react'; import SetupDialog from './SetupDialog' import ShowDialog from './ShowDialog' import SuggestDialog from './SuggestDialog' ` classic = name: "Classic" rulesId: "classic" minPlayers: 3 maxPlayers: 6 types: suspect: { title: "Suspects", preposition: "", article: "" } weapon: { title: "Weapons", preposition: "with ", article: "the " } room: { title: "Rooms", preposition: "in ", article: "the " } cards: mustard: { name: "<NAME>", type: "suspect" } white: { name: "<NAME>", type: "suspect" } plum: { name: "<NAME>", type: "suspect" } peacock: { name: "<NAME>", type: "suspect" } green: { name: "<NAME>", type: "suspect" } scarlet: { name: "<NAME>", type: "suspect" } revolver: { name: "<NAME>", type: "weapon" } knife: { name: "<NAME>", type: "weapon" } rope: { name: "Rope", type: "weapon" } pipe: { name: "Lead pipe", type: "weapon" } wrench: { name: "Wrench", type: "weapon" } candlestick: { name: "Candlestick", type: "weapon" } dining: { name: "Dining Room", type: "room" } conservatory: { name: "Conservatory", type: "room" } kitchen: { name: "Kitchen", type: "room" } study: { name: "Study", type: "room" } library: { name: "Library", type: "room" } billiard: { name: "Billiards Room", type: "room" } lounge: { name: "Lounge", type: "room" } ballroom: { name: "Ballroom", type: "room" } hall: { name: "Hall", type: "room" } suggestionOrder: [ "suspect", "weapon", "room" ] master_detective = name: "<NAME>" rulesId : "master" minPlayers: 3 maxPlayers: 10 types : suspect: { title: "Suspects", preposition: "", article: "" } weapon: { title: "Weapons", preposition: "with ", article: "the " } room: { title: "Rooms", preposition: "in ", article: "the " } cards : mustard: { name: "<NAME>", type: "suspect" } white: { name: "<NAME>", type: "suspect" } plum: { name: "<NAME>", type: "suspect" } peacock: { name: "<NAME>", type: "suspect" } green: { name: "<NAME>", type: "suspect" } scarlet: { name: "<NAME>", type: "suspect" } rose: { name: "<NAME>", type: "suspect" } gray: { name: "<NAME>", type: "suspect" } brunette: { name: "<NAME>", type: "suspect" } peach: { name: "<NAME>", type: "suspect" } revolver: { name: "Revolver", type: "weapon" } knife: { name: "Knife", type: "weapon" } rope: { name: "Rope", type: "weapon" } pipe: { name: "Pipe", type: "weapon" } wrench: { name: "Wrench", type: "weapon" } candlestick: { name: "Candlestick", type: "weapon" } poison: { name: "Poison", type: "weapon" } horseshoe: { name: "Horseshoe", type: "weapon" } dining: { name: "Dining Room", type: "room" } conservatory: { name: "Conservatory", type: "room" } kitchen: { name: "Kitchen", type: "room" } studio: { name: "Studio", type: "room" } library: { name: "Library", type: "room" } billiard: { name: "Billiard Room", type: "room" } courtyard: { name: "Courtyard", type: "room" } gazebo: { name: "Gazebo", type: "room" } drawing: { name: "Drawing Room", type: "room" } carriage: { name: "Carriage House", type: "room" } trophy: { name: "Trophy Room", type: "room" } fountain: { name: "Fountain", type: "room" } suggestionOrder: [ "suspect", "weapon", "room" ] haunted_mansion = name: "Haunted Mansion" rulesId: "classic" minPlayers: 3 maxPlayers: 6 types: guest: { title: "Guests", preposition: "haunted ", article: "" } ghost: { title: "Ghosts", preposition: "", article: "the " } room: { title: "Rooms", preposition: "in ", article: "the " } cards: pluto: { name: "<NAME>", type: "guest" } <NAME>isy: { name: "<NAME>", type: "guest" } goofy: { name: "<NAME>", type: "guest" } <NAME>: { name: "<NAME>", type: "guest" } minnie: { name: "<NAME>", type: "guest" } mickey: { name: "<NAME>", type: "guest" } prisoner: { name: "<NAME>", type: "ghost" } singer: { name: "<NAME>", type: "ghost" } bride: { name: "<NAME>", type: "ghost" } traveler: { name: "<NAME>", type: "ghost" } mariner: { name: "<NAME>", type: "ghost" } skeleton: { name: "<NAME>", type: "ghost" } graveyard: { name: "Graveyard", type: "room" } seance: { name: "Seance Room", type: "room" } ballroom: { name: "Ballroom", type: "room" } attic: { name: "<NAME>", type: "room" } mausoleum: { name: "<NAME>", type: "room" } conservatory: { name: "Conservatory", type: "room" } library: { name: "Library", type: "room" } foyer: { name: "<NAME>", type: "room" } chamber: { name: "Portrait Chamber", type: "room" } suggestionOrder: [ "ghost", "guest", "room" ] star_wars = name: "<NAME>" rulesId: "star_wars" minPlayers: 3 maxPlayers: 6 types: planet: { title: "Planets", preposition: "Darth Vader is targeting ", article: "" } room: { title: "Rooms", preposition: ", the plans are in ", article: "the " } ship: { title: "Ships", preposition: ", and we can escape in ", article: "a " } cards: alderaan: { name: "<NAME>", type: "planet" } bespin: { name: "<NAME>", type: "planet" } dagobah: { name: "<NAME>", type: "planet" } endor: { name: "<NAME>", type: "planet" } tattoine: { name: "<NAME>", type: "planet" } yavin: { name: "<NAME>", type: "planet" } millenium: { name: "<NAME>", type: "ship" } xwing: { name: "<NAME>", type: "ship" } ywing: { name: "<NAME>", type: "ship" } tiefighter: { name: "<NAME>", type: "ship" } pod: { name: "Escape <NAME>", type: "ship" } tiebomber: { name: "<NAME>", type: "ship" } laser: { name: "Laser Control Room", type: "room" } overbridge: { name: "Overbridge", type: "room" } docking: { name: "Docking Bay", type: "room" } red: { name: "Red Control Room", type: "room" } war: { name: "War Room", type: "room" } detention: { name: "Detention Block", type: "room" } throne: { name: "Throne Room", type: "room" } trash: { name: "Trash Compactor", type: "room" } tractor: { name: "Tractor Beam Generator", type: "room" } suggestionOrder: [ "planet", "room", "ship" ] harry_potter = name: "<NAME>" rulesId: "classic" minPlayers: 3 maxPlayers: 6 types: suspect: { title: "Suspects", preposition: "", article: "" } item: { title: "Items", preposition: "with ", article: "a " } room: { title: "Rooms", preposition: "in ", article: "the " } cards: draco: { name: "<NAME>", type: "suspect" } crabbe: { name: "<NAME>", type: "suspect" } lucius: { name: "<NAME>", type: "suspect" } delores: { name: "<NAME>", type: "suspect" } peter: { name: "<NAME>", type: "suspect" } bellatrix: { name: "<NAME>", type: "suspect" } draught: { name: "Sleeping Draught", type: "item" } cabinet: { name: "Vanishing Cabinet", type: "item" } portkey: { name: "<NAME>", type: "item" } impedimenta: { name: "Imp<NAME>ienta", type: "item" } petrifus: { name: "<NAME>", type: "item" } mandarke: { name: "<NAME>", type: "item" } hall: { name: "Great Hall", type: "room" } hospital: { name: "Hospital Wing", type: "room" } requirement: { name: "Room of Requirement", type: "room" } potions: { name: "Potions ClassRoom", type: "room" } trophy: { name: "Trophy Room", type: "room" } divination: { name: "Divination Classroom", type: "room" } owlry: { name: "Owlry", type: "room" } library: { name: "Library", type: "room" } defense: { name: "Defense Against Dark Arts", type: "room" } suggestionOrder: [ "suspect", "item", "room" ] configurations = classic: classic master_detective: master_detective haunted_mansion: haunted_mansion star_wars: star_wars harry_potter: harry_potter class App extends Component constructor: (props) -> super props @solver = null @accusationId = 1 @commlinkId = 1 @suggestionId = 1 @playerIds = [] @configurationId = "master_detective" @log = [] @state = mainMenuAnchor: null newGameDialogOpen: false importDialogOpen: false logDialogOpen: false exportDialogOpen: false confirmDialog: open: false title: '' question: '' yesAction: null noAction: null handDialogOpen: false suggestDialogOpen: false showDialogOpen: false accuseDialogOpen: false commlinkDialogOpen: false return setUpNewGame: (configurationId, playerIds) => @accusationId = 1 @commlinkId = 1 @suggestionId = 1 @playerIds = playerIds @configurationId = configurationId @log = [] @recordSetup configurationId, playerIds return importLog: (imported) => parsedLog = null try parsedLog = JSON.parse(imported) catch e console.log(JSON.stringify(e, 2)) @showConfirmDialog( "Import Error", "The input is not valid JSON." ) return if not parsedLog? or parsedLog not instanceof Array or not parsedLog[0]? or not parsedLog[0].setup? @showConfirmDialog( "Import Error", "The first entry in the log is not a \"setup\" entry." ) return setup = parsedLog[0].setup # Parse the setup entry if not setup.variation? or not setup.players? @showConfirmDialog( "Import Error", "The setup entry must have a \"variation\" property and a \"players\" property." ) return { variation, players } = setup if not configurations[variation]? @showConfirmDialog( "Import Error", "The variation \"#{variation}\" is not supported. The following variations are supported: #{Object.keys(configurations)}" ) return configuration = configurations[variation] if players not instanceof Array or players.length < configuration.minPlayers or players.length > configuration.maxPlayers @showConfirmDialog( "Import Error", "This variation requires #{configuration.minPlayers} to #{configuration.maxPlayers} players." ) return if "ANSWER" in players or "Nobody" in players @showConfirmDialog( "Import Error", "The uses of the names \"ANSWER\" and \"Nobody\" are reserved." ) return configuration = configurations[variation] # Process the setup @setUpNewGame variation, players # Player and card lists for reporting errors playerList = "#{players}" cardList = "#{Object.keys(configuration.cards)}" # Process each entry that follows for entry in parsedLog[1..] # Hand entry if entry.hand? hand = entry.hand if not hand.player? or not hand.cards? @showConfirmDialog( "Import Error", "The hand entry must have a \"player\" property and a \"cards\" property." ) return { player, cards } = hand if player not in players @showConfirmDialog( "Import Error", "\"#{player}\" is not in the list of players. Valid players are #{playerList}" ) return if cards not instanceof Array @showConfirmDialog( "Import Error", "The hand.cards property must be an array of cards." ) return for card in cards if not configuration.cards[card]? @showConfirmDialog( "Import Error", "\"#{card}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return @recordHand player, cards # Suggest entry else if entry.suggest? suggestion = entry.suggest if not suggestion.suggester? or not suggestion.cards? or not suggestion.showed? @showConfirmDialog( "Import Error", "The suggest entry must have a \"suggester\" property, a \"cards\" property, and a \"showed\" property." ) return { suggester, cards, showed } = suggestion if suggester not in players @showConfirmDialog( "Import Error", "\"#{suggester}\" is not in the list of players. Valid players are #{playerList}" ) return if cards not instanceof Array @showConfirmDialog( "Import Error", "The suggest.cards property must be an array of cards." ) return for c in cards if not configuration.cards[c]? @showConfirmDialog( "Import Error", "\"#{c}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return if showed not instanceof Array @showConfirmDialog( "Import Error", "The suggest.showed property must be an array of players." ) return for s in showed if s not in players @showConfirmDialog( "Import Error", "\"#{s}\" is not in the list of players. Valid players are #{playerList}" ) return @recordSuggestion suggester, cards, showed # Show entry else if entry.show? show = entry.show if not show.player? or not show.card? @showConfirmDialog( "Import Error", "The show entry must have a \"player\" property, and a \"card\" property." ) return { player, card } = show if player not in players @showConfirmDialog( "Import Error", "\"#{player}\" is not in the list of players. Valid players are #{playerList}" ) return if not configuration.cards[card]? @showConfirmDialog( "Import Error", "\"#{card}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return @recordShown player, card # Accuse entry else if entry.accuse? accusation = entry.accuse console.log JSON.stringify(accusation) console.log "" if not accusation.accuser? or not accusation.cards? or not accusation.correct? @showConfirmDialog( "Import Error", "The accuse entry must have an \"accuser\" property, a \"cards\" property, and a \"correct\" property." ) return { accuser, cards, correct } = accusation if accuser not in players @showConfirmDialog( "Import Error", "\"#{accuser}\" is not in the player list. Valid players are #{playerList}" ) return if cards not instanceof Array @showConfirmDialog( "Import Error", "The accuse.cards property must be an array of cards." ) return for c in cards if not configuration.cards[c]? @showConfirmDialog( "Import Error", "\"#{c}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return if typeof(correct) != typeof(true) @showConfirmDialog( "Import Error", "The accuse.correct property must be true or false." ) return @recordAccusation accuser, cards, correct # Commlink entry (if Star Wars edition) else if entry.commlink? and setup.variation is "star_wars" commlink = entry.commlink if not commlink.caller? or not commlink.receiver? or not commlink.cards? or not commlink.showed? @showConfirmDialog( "Import Error", "The commlink entry must have a \"caller\" property, a \"receiver\" property, a \"cards\" property, and a \"showed\" property." ) return { caller, receiver, cards, showed } = commlink if caller not in players @showConfirmDialog( "Import Error", "\"#{caller}\" is not in the player list. Valid players are #{playerList}" ) return if receiver not in players @showConfirmDialog( "Import Error", "\"#{receiver}\" is not in the player list. Valid players are #{playerList}" ) return if cards not instanceof Array @showConfirmDialog( "Import Error", "The commlink.cards property must be an array of cards." ) return for c in cards if not configuration.cards[c]? @showConfirmDialog( "Import Error", "\"#{c}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return if typeof(showed) != typeof(true) @showConfirmDialog( "Import Error", "The commlink.showed property must be true or false." ) return @recordCommlink caller, receiver, cards, showed # Otherwise, unknown entry else @showConfirmDialog( "Import Error", "Unsupported imported log entry: #{JSON.stringify(entry)}." ) return return # Component launchers showMainMenu: (anchor) => @setState { mainMenuAnchor: anchor } return showNewGameDialog: => @setState { newGameDialogOpen: true } return showImportDialog: => @setState { importDialogOpen: true } return showLog: => @setState { logDialogOpen: true } return showExportDialog: => @setState { exportDialogOpen: true } return showConfirmDialog: (title, question, yesAction, noAction) => @setState confirmDialog: open: true title: title question: question yesAction: yesAction noAction: noAction return showHandDialog: => @setState { handDialogOpen: true } return showSuggestDialog: => @setState { suggestDialogOpen: true } return showShowDialog: => @setState { showDialogOpen: true } return showAccuseDialog: => @setState { accuseDialogOpen: true } return showCommlinkDialog: => @setState { commlinkDialogOpen: true } return # Solver state updaters recordSetup: (configurationId, playerIds) => @solver = new Solver(configurations[configurationId], playerIds) @log.push setup: variation: configurationId players: playerIds recordHand: (playerId, cardIds) => if @solver? @solver.hand playerId, cardIds @log.push hand: player: playerId cards: cardIds return recordSuggestion: (suggesterId, cardIds, showedIds) => if @solver? id = @suggestionId++ @solver.suggest suggesterId, cardIds, showedIds, id @log.push suggest: id: id suggester: suggesterId cards: cardIds showed: showedIds return recordShown: (playerId, cardId) => if @solver? @solver.show playerId, cardId @log.push show: player: playerId card: cardId return recordAccusation: (accuserId, cardIds, correct) => if @solver? id = @accusationId++ @solver.accuse accuserId, cardIds, correct, id @log.push accuse: id: id accuser: accuserId cards: cardIds correct: correct return recordCommlink: (callerId, receiverId, cardIds, showed) => if @solver? id = @commlinkId++ @solver.commlink callerId, receiverId, cardIds, showed, id @log.push commlink: id: id caller: callerId receiver: receiverId cards: cardIds showed: showed return render: -> <div className="App"> <MainView configurationId={@configurationId} solver={@solver} onMenu={@showMainMenu} app={this} /> <MainMenu anchor={@state.mainMenuAnchor} started={@solver?} onClose={() => @setState({ mainMenuAnchor: null })} app={this} /> <SetupDialog open={@state.newGameDialogOpen} configurations={configurations} onDone={@setUpNewGame} onClose={() => @setState({ newGameDialogOpen: false })} app={this} /> <ImportDialog open={@state.importDialogOpen} configurations={configurations} onDone={@importLog} onClose={() => @setState({ importDialogOpen: false })} app={this} /> <LogDialog open={@state.logDialogOpen} log={@log} configurations={configurations} onClose={() => @setState({ logDialogOpen: false })} app={this} /> <ExportDialog open={@state.exportDialogOpen} log={@log} onClose={() => @setState({ exportDialogOpen: false })} app={this} /> <ConfirmDialog open={@state.confirmDialog.open} title={@state.confirmDialog.title} question={@state.confirmDialog.question} yesAction={@state.confirmDialog.yesAction} noAction={@state.confirmDialog.noAction} onClose={@handleConfirmDialogClose} app={this} /> <HandDialog open={@state.handDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordHand} onClose={() => @setState({ handDialogOpen: false })} app={this} /> <SuggestDialog open={@state.suggestDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordSuggestion} onClose={() => @setState({ suggestDialogOpen: false })} app={this} /> <ShowDialog open={@state.showDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordShown} onClose={() => @setState({ showDialogOpen: false })} app={this} /> <AccuseDialog open={@state.accuseDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordAccusation} onClose={() => @setState({ accuseDialogOpen: false })} app={this} /> <CommlinkDialog open={@state.commlinkDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordCommlink} onClose={() => @setState({ commlinkDialogOpen: false })} app={this} /> </div> # Callbacks handleConfirmDialogClose: => @setState { confirmDialog: open: false title: "" question: "" yesAction: null noAction: null } return export default App
true
` import Solver from './Solver' import AccuseDialog from './AccuseDialog' import CommlinkDialog from './CommlinkDialog' import ConfirmDialog from './ConfirmDialog' import ExportDialog from './ExportDialog' import HandDialog from './HandDialog' import ImportDialog from './ImportDialog' import LogDialog from './LogDialog' import MainMenu from './MainMenu' import MainView from './MainView' import React, { Component } from 'react'; import SetupDialog from './SetupDialog' import ShowDialog from './ShowDialog' import SuggestDialog from './SuggestDialog' ` classic = name: "Classic" rulesId: "classic" minPlayers: 3 maxPlayers: 6 types: suspect: { title: "Suspects", preposition: "", article: "" } weapon: { title: "Weapons", preposition: "with ", article: "the " } room: { title: "Rooms", preposition: "in ", article: "the " } cards: mustard: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } white: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } plum: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } peacock: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } green: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } scarlet: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } revolver: { name: "PI:NAME:<NAME>END_PI", type: "weapon" } knife: { name: "PI:NAME:<NAME>END_PI", type: "weapon" } rope: { name: "Rope", type: "weapon" } pipe: { name: "Lead pipe", type: "weapon" } wrench: { name: "Wrench", type: "weapon" } candlestick: { name: "Candlestick", type: "weapon" } dining: { name: "Dining Room", type: "room" } conservatory: { name: "Conservatory", type: "room" } kitchen: { name: "Kitchen", type: "room" } study: { name: "Study", type: "room" } library: { name: "Library", type: "room" } billiard: { name: "Billiards Room", type: "room" } lounge: { name: "Lounge", type: "room" } ballroom: { name: "Ballroom", type: "room" } hall: { name: "Hall", type: "room" } suggestionOrder: [ "suspect", "weapon", "room" ] master_detective = name: "PI:NAME:<NAME>END_PI" rulesId : "master" minPlayers: 3 maxPlayers: 10 types : suspect: { title: "Suspects", preposition: "", article: "" } weapon: { title: "Weapons", preposition: "with ", article: "the " } room: { title: "Rooms", preposition: "in ", article: "the " } cards : mustard: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } white: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } plum: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } peacock: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } green: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } scarlet: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } rose: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } gray: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } brunette: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } peach: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } revolver: { name: "Revolver", type: "weapon" } knife: { name: "Knife", type: "weapon" } rope: { name: "Rope", type: "weapon" } pipe: { name: "Pipe", type: "weapon" } wrench: { name: "Wrench", type: "weapon" } candlestick: { name: "Candlestick", type: "weapon" } poison: { name: "Poison", type: "weapon" } horseshoe: { name: "Horseshoe", type: "weapon" } dining: { name: "Dining Room", type: "room" } conservatory: { name: "Conservatory", type: "room" } kitchen: { name: "Kitchen", type: "room" } studio: { name: "Studio", type: "room" } library: { name: "Library", type: "room" } billiard: { name: "Billiard Room", type: "room" } courtyard: { name: "Courtyard", type: "room" } gazebo: { name: "Gazebo", type: "room" } drawing: { name: "Drawing Room", type: "room" } carriage: { name: "Carriage House", type: "room" } trophy: { name: "Trophy Room", type: "room" } fountain: { name: "Fountain", type: "room" } suggestionOrder: [ "suspect", "weapon", "room" ] haunted_mansion = name: "Haunted Mansion" rulesId: "classic" minPlayers: 3 maxPlayers: 6 types: guest: { title: "Guests", preposition: "haunted ", article: "" } ghost: { title: "Ghosts", preposition: "", article: "the " } room: { title: "Rooms", preposition: "in ", article: "the " } cards: pluto: { name: "PI:NAME:<NAME>END_PI", type: "guest" } PI:NAME:<NAME>END_PIisy: { name: "PI:NAME:<NAME>END_PI", type: "guest" } goofy: { name: "PI:NAME:<NAME>END_PI", type: "guest" } PI:NAME:<NAME>END_PI: { name: "PI:NAME:<NAME>END_PI", type: "guest" } minnie: { name: "PI:NAME:<NAME>END_PI", type: "guest" } mickey: { name: "PI:NAME:<NAME>END_PI", type: "guest" } prisoner: { name: "PI:NAME:<NAME>END_PI", type: "ghost" } singer: { name: "PI:NAME:<NAME>END_PI", type: "ghost" } bride: { name: "PI:NAME:<NAME>END_PI", type: "ghost" } traveler: { name: "PI:NAME:<NAME>END_PI", type: "ghost" } mariner: { name: "PI:NAME:<NAME>END_PI", type: "ghost" } skeleton: { name: "PI:NAME:<NAME>END_PI", type: "ghost" } graveyard: { name: "Graveyard", type: "room" } seance: { name: "Seance Room", type: "room" } ballroom: { name: "Ballroom", type: "room" } attic: { name: "PI:NAME:<NAME>END_PI", type: "room" } mausoleum: { name: "PI:NAME:<NAME>END_PI", type: "room" } conservatory: { name: "Conservatory", type: "room" } library: { name: "Library", type: "room" } foyer: { name: "PI:NAME:<NAME>END_PI", type: "room" } chamber: { name: "Portrait Chamber", type: "room" } suggestionOrder: [ "ghost", "guest", "room" ] star_wars = name: "PI:NAME:<NAME>END_PI" rulesId: "star_wars" minPlayers: 3 maxPlayers: 6 types: planet: { title: "Planets", preposition: "Darth Vader is targeting ", article: "" } room: { title: "Rooms", preposition: ", the plans are in ", article: "the " } ship: { title: "Ships", preposition: ", and we can escape in ", article: "a " } cards: alderaan: { name: "PI:NAME:<NAME>END_PI", type: "planet" } bespin: { name: "PI:NAME:<NAME>END_PI", type: "planet" } dagobah: { name: "PI:NAME:<NAME>END_PI", type: "planet" } endor: { name: "PI:NAME:<NAME>END_PI", type: "planet" } tattoine: { name: "PI:NAME:<NAME>END_PI", type: "planet" } yavin: { name: "PI:NAME:<NAME>END_PI", type: "planet" } millenium: { name: "PI:NAME:<NAME>END_PI", type: "ship" } xwing: { name: "PI:NAME:<NAME>END_PI", type: "ship" } ywing: { name: "PI:NAME:<NAME>END_PI", type: "ship" } tiefighter: { name: "PI:NAME:<NAME>END_PI", type: "ship" } pod: { name: "Escape PI:NAME:<NAME>END_PI", type: "ship" } tiebomber: { name: "PI:NAME:<NAME>END_PI", type: "ship" } laser: { name: "Laser Control Room", type: "room" } overbridge: { name: "Overbridge", type: "room" } docking: { name: "Docking Bay", type: "room" } red: { name: "Red Control Room", type: "room" } war: { name: "War Room", type: "room" } detention: { name: "Detention Block", type: "room" } throne: { name: "Throne Room", type: "room" } trash: { name: "Trash Compactor", type: "room" } tractor: { name: "Tractor Beam Generator", type: "room" } suggestionOrder: [ "planet", "room", "ship" ] harry_potter = name: "PI:NAME:<NAME>END_PI" rulesId: "classic" minPlayers: 3 maxPlayers: 6 types: suspect: { title: "Suspects", preposition: "", article: "" } item: { title: "Items", preposition: "with ", article: "a " } room: { title: "Rooms", preposition: "in ", article: "the " } cards: draco: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } crabbe: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } lucius: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } delores: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } peter: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } bellatrix: { name: "PI:NAME:<NAME>END_PI", type: "suspect" } draught: { name: "Sleeping Draught", type: "item" } cabinet: { name: "Vanishing Cabinet", type: "item" } portkey: { name: "PI:NAME:<NAME>END_PI", type: "item" } impedimenta: { name: "ImpPI:NAME:<NAME>END_PIienta", type: "item" } petrifus: { name: "PI:NAME:<NAME>END_PI", type: "item" } mandarke: { name: "PI:NAME:<NAME>END_PI", type: "item" } hall: { name: "Great Hall", type: "room" } hospital: { name: "Hospital Wing", type: "room" } requirement: { name: "Room of Requirement", type: "room" } potions: { name: "Potions ClassRoom", type: "room" } trophy: { name: "Trophy Room", type: "room" } divination: { name: "Divination Classroom", type: "room" } owlry: { name: "Owlry", type: "room" } library: { name: "Library", type: "room" } defense: { name: "Defense Against Dark Arts", type: "room" } suggestionOrder: [ "suspect", "item", "room" ] configurations = classic: classic master_detective: master_detective haunted_mansion: haunted_mansion star_wars: star_wars harry_potter: harry_potter class App extends Component constructor: (props) -> super props @solver = null @accusationId = 1 @commlinkId = 1 @suggestionId = 1 @playerIds = [] @configurationId = "master_detective" @log = [] @state = mainMenuAnchor: null newGameDialogOpen: false importDialogOpen: false logDialogOpen: false exportDialogOpen: false confirmDialog: open: false title: '' question: '' yesAction: null noAction: null handDialogOpen: false suggestDialogOpen: false showDialogOpen: false accuseDialogOpen: false commlinkDialogOpen: false return setUpNewGame: (configurationId, playerIds) => @accusationId = 1 @commlinkId = 1 @suggestionId = 1 @playerIds = playerIds @configurationId = configurationId @log = [] @recordSetup configurationId, playerIds return importLog: (imported) => parsedLog = null try parsedLog = JSON.parse(imported) catch e console.log(JSON.stringify(e, 2)) @showConfirmDialog( "Import Error", "The input is not valid JSON." ) return if not parsedLog? or parsedLog not instanceof Array or not parsedLog[0]? or not parsedLog[0].setup? @showConfirmDialog( "Import Error", "The first entry in the log is not a \"setup\" entry." ) return setup = parsedLog[0].setup # Parse the setup entry if not setup.variation? or not setup.players? @showConfirmDialog( "Import Error", "The setup entry must have a \"variation\" property and a \"players\" property." ) return { variation, players } = setup if not configurations[variation]? @showConfirmDialog( "Import Error", "The variation \"#{variation}\" is not supported. The following variations are supported: #{Object.keys(configurations)}" ) return configuration = configurations[variation] if players not instanceof Array or players.length < configuration.minPlayers or players.length > configuration.maxPlayers @showConfirmDialog( "Import Error", "This variation requires #{configuration.minPlayers} to #{configuration.maxPlayers} players." ) return if "ANSWER" in players or "Nobody" in players @showConfirmDialog( "Import Error", "The uses of the names \"ANSWER\" and \"Nobody\" are reserved." ) return configuration = configurations[variation] # Process the setup @setUpNewGame variation, players # Player and card lists for reporting errors playerList = "#{players}" cardList = "#{Object.keys(configuration.cards)}" # Process each entry that follows for entry in parsedLog[1..] # Hand entry if entry.hand? hand = entry.hand if not hand.player? or not hand.cards? @showConfirmDialog( "Import Error", "The hand entry must have a \"player\" property and a \"cards\" property." ) return { player, cards } = hand if player not in players @showConfirmDialog( "Import Error", "\"#{player}\" is not in the list of players. Valid players are #{playerList}" ) return if cards not instanceof Array @showConfirmDialog( "Import Error", "The hand.cards property must be an array of cards." ) return for card in cards if not configuration.cards[card]? @showConfirmDialog( "Import Error", "\"#{card}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return @recordHand player, cards # Suggest entry else if entry.suggest? suggestion = entry.suggest if not suggestion.suggester? or not suggestion.cards? or not suggestion.showed? @showConfirmDialog( "Import Error", "The suggest entry must have a \"suggester\" property, a \"cards\" property, and a \"showed\" property." ) return { suggester, cards, showed } = suggestion if suggester not in players @showConfirmDialog( "Import Error", "\"#{suggester}\" is not in the list of players. Valid players are #{playerList}" ) return if cards not instanceof Array @showConfirmDialog( "Import Error", "The suggest.cards property must be an array of cards." ) return for c in cards if not configuration.cards[c]? @showConfirmDialog( "Import Error", "\"#{c}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return if showed not instanceof Array @showConfirmDialog( "Import Error", "The suggest.showed property must be an array of players." ) return for s in showed if s not in players @showConfirmDialog( "Import Error", "\"#{s}\" is not in the list of players. Valid players are #{playerList}" ) return @recordSuggestion suggester, cards, showed # Show entry else if entry.show? show = entry.show if not show.player? or not show.card? @showConfirmDialog( "Import Error", "The show entry must have a \"player\" property, and a \"card\" property." ) return { player, card } = show if player not in players @showConfirmDialog( "Import Error", "\"#{player}\" is not in the list of players. Valid players are #{playerList}" ) return if not configuration.cards[card]? @showConfirmDialog( "Import Error", "\"#{card}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return @recordShown player, card # Accuse entry else if entry.accuse? accusation = entry.accuse console.log JSON.stringify(accusation) console.log "" if not accusation.accuser? or not accusation.cards? or not accusation.correct? @showConfirmDialog( "Import Error", "The accuse entry must have an \"accuser\" property, a \"cards\" property, and a \"correct\" property." ) return { accuser, cards, correct } = accusation if accuser not in players @showConfirmDialog( "Import Error", "\"#{accuser}\" is not in the player list. Valid players are #{playerList}" ) return if cards not instanceof Array @showConfirmDialog( "Import Error", "The accuse.cards property must be an array of cards." ) return for c in cards if not configuration.cards[c]? @showConfirmDialog( "Import Error", "\"#{c}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return if typeof(correct) != typeof(true) @showConfirmDialog( "Import Error", "The accuse.correct property must be true or false." ) return @recordAccusation accuser, cards, correct # Commlink entry (if Star Wars edition) else if entry.commlink? and setup.variation is "star_wars" commlink = entry.commlink if not commlink.caller? or not commlink.receiver? or not commlink.cards? or not commlink.showed? @showConfirmDialog( "Import Error", "The commlink entry must have a \"caller\" property, a \"receiver\" property, a \"cards\" property, and a \"showed\" property." ) return { caller, receiver, cards, showed } = commlink if caller not in players @showConfirmDialog( "Import Error", "\"#{caller}\" is not in the player list. Valid players are #{playerList}" ) return if receiver not in players @showConfirmDialog( "Import Error", "\"#{receiver}\" is not in the player list. Valid players are #{playerList}" ) return if cards not instanceof Array @showConfirmDialog( "Import Error", "The commlink.cards property must be an array of cards." ) return for c in cards if not configuration.cards[c]? @showConfirmDialog( "Import Error", "\"#{c}\" is not in a valid card for this variation. Valid cards are #{cardList}" ) return if typeof(showed) != typeof(true) @showConfirmDialog( "Import Error", "The commlink.showed property must be true or false." ) return @recordCommlink caller, receiver, cards, showed # Otherwise, unknown entry else @showConfirmDialog( "Import Error", "Unsupported imported log entry: #{JSON.stringify(entry)}." ) return return # Component launchers showMainMenu: (anchor) => @setState { mainMenuAnchor: anchor } return showNewGameDialog: => @setState { newGameDialogOpen: true } return showImportDialog: => @setState { importDialogOpen: true } return showLog: => @setState { logDialogOpen: true } return showExportDialog: => @setState { exportDialogOpen: true } return showConfirmDialog: (title, question, yesAction, noAction) => @setState confirmDialog: open: true title: title question: question yesAction: yesAction noAction: noAction return showHandDialog: => @setState { handDialogOpen: true } return showSuggestDialog: => @setState { suggestDialogOpen: true } return showShowDialog: => @setState { showDialogOpen: true } return showAccuseDialog: => @setState { accuseDialogOpen: true } return showCommlinkDialog: => @setState { commlinkDialogOpen: true } return # Solver state updaters recordSetup: (configurationId, playerIds) => @solver = new Solver(configurations[configurationId], playerIds) @log.push setup: variation: configurationId players: playerIds recordHand: (playerId, cardIds) => if @solver? @solver.hand playerId, cardIds @log.push hand: player: playerId cards: cardIds return recordSuggestion: (suggesterId, cardIds, showedIds) => if @solver? id = @suggestionId++ @solver.suggest suggesterId, cardIds, showedIds, id @log.push suggest: id: id suggester: suggesterId cards: cardIds showed: showedIds return recordShown: (playerId, cardId) => if @solver? @solver.show playerId, cardId @log.push show: player: playerId card: cardId return recordAccusation: (accuserId, cardIds, correct) => if @solver? id = @accusationId++ @solver.accuse accuserId, cardIds, correct, id @log.push accuse: id: id accuser: accuserId cards: cardIds correct: correct return recordCommlink: (callerId, receiverId, cardIds, showed) => if @solver? id = @commlinkId++ @solver.commlink callerId, receiverId, cardIds, showed, id @log.push commlink: id: id caller: callerId receiver: receiverId cards: cardIds showed: showed return render: -> <div className="App"> <MainView configurationId={@configurationId} solver={@solver} onMenu={@showMainMenu} app={this} /> <MainMenu anchor={@state.mainMenuAnchor} started={@solver?} onClose={() => @setState({ mainMenuAnchor: null })} app={this} /> <SetupDialog open={@state.newGameDialogOpen} configurations={configurations} onDone={@setUpNewGame} onClose={() => @setState({ newGameDialogOpen: false })} app={this} /> <ImportDialog open={@state.importDialogOpen} configurations={configurations} onDone={@importLog} onClose={() => @setState({ importDialogOpen: false })} app={this} /> <LogDialog open={@state.logDialogOpen} log={@log} configurations={configurations} onClose={() => @setState({ logDialogOpen: false })} app={this} /> <ExportDialog open={@state.exportDialogOpen} log={@log} onClose={() => @setState({ exportDialogOpen: false })} app={this} /> <ConfirmDialog open={@state.confirmDialog.open} title={@state.confirmDialog.title} question={@state.confirmDialog.question} yesAction={@state.confirmDialog.yesAction} noAction={@state.confirmDialog.noAction} onClose={@handleConfirmDialogClose} app={this} /> <HandDialog open={@state.handDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordHand} onClose={() => @setState({ handDialogOpen: false })} app={this} /> <SuggestDialog open={@state.suggestDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordSuggestion} onClose={() => @setState({ suggestDialogOpen: false })} app={this} /> <ShowDialog open={@state.showDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordShown} onClose={() => @setState({ showDialogOpen: false })} app={this} /> <AccuseDialog open={@state.accuseDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordAccusation} onClose={() => @setState({ accuseDialogOpen: false })} app={this} /> <CommlinkDialog open={@state.commlinkDialogOpen} configuration={configurations[@configurationId]} players={@playerIds} onDone={@recordCommlink} onClose={() => @setState({ commlinkDialogOpen: false })} app={this} /> </div> # Callbacks handleConfirmDialogClose: => @setState { confirmDialog: open: false title: "" question: "" yesAction: null noAction: null } return export default App
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9992899298667908, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-net-pipe-connect-errors.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. fs = require("fs") net = require("net") path = require("path") assert = require("assert") common = require("../common") notSocketErrorFired = false noEntErrorFired = false accessErrorFired = false # Test if ENOTSOCK is fired when trying to connect to a file which is not # a socket. emptyTxt = undefined if process.platform is "win32" # on Win, common.PIPE will be a named pipe, so we use an existing empty # file instead emptyTxt = path.join(common.fixturesDir, "empty.txt") else # use common.PIPE to ensure we stay within POSIX socket path length # restrictions, even on CI cleanup = -> try fs.unlinkSync emptyTxt catch e throw e unless e.code is "ENOENT" return emptyTxt = common.PIPE + ".txt" process.on "exit", cleanup cleanup() fs.writeFileSync emptyTxt, "" notSocketClient = net.createConnection(emptyTxt, -> assert.ok false return ) notSocketClient.on "error", (err) -> assert err.code is "ENOTSOCK" or err.code is "ECONNREFUSED" notSocketErrorFired = true return # Trying to connect to not-existing socket should result in ENOENT error noEntSocketClient = net.createConnection("no-ent-file", -> assert.ok false return ) noEntSocketClient.on "error", (err) -> assert.equal err.code, "ENOENT" noEntErrorFired = true return # On Windows or when running as root, a chmod has no effect on named pipes if process.platform isnt "win32" and process.getuid() isnt 0 # Trying to connect to a socket one has no access to should result in EACCES accessServer = net.createServer(-> assert.ok false return ) accessServer.listen common.PIPE, -> fs.chmodSync common.PIPE, 0 accessClient = net.createConnection(common.PIPE, -> assert.ok false return ) accessClient.on "error", (err) -> assert.equal err.code, "EACCES" accessErrorFired = true accessServer.close() return return # Assert that all error events were fired process.on "exit", -> assert.ok notSocketErrorFired assert.ok noEntErrorFired assert.ok accessErrorFired if process.platform isnt "win32" and process.getuid() isnt 0 return
172399
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. fs = require("fs") net = require("net") path = require("path") assert = require("assert") common = require("../common") notSocketErrorFired = false noEntErrorFired = false accessErrorFired = false # Test if ENOTSOCK is fired when trying to connect to a file which is not # a socket. emptyTxt = undefined if process.platform is "win32" # on Win, common.PIPE will be a named pipe, so we use an existing empty # file instead emptyTxt = path.join(common.fixturesDir, "empty.txt") else # use common.PIPE to ensure we stay within POSIX socket path length # restrictions, even on CI cleanup = -> try fs.unlinkSync emptyTxt catch e throw e unless e.code is "ENOENT" return emptyTxt = common.PIPE + ".txt" process.on "exit", cleanup cleanup() fs.writeFileSync emptyTxt, "" notSocketClient = net.createConnection(emptyTxt, -> assert.ok false return ) notSocketClient.on "error", (err) -> assert err.code is "ENOTSOCK" or err.code is "ECONNREFUSED" notSocketErrorFired = true return # Trying to connect to not-existing socket should result in ENOENT error noEntSocketClient = net.createConnection("no-ent-file", -> assert.ok false return ) noEntSocketClient.on "error", (err) -> assert.equal err.code, "ENOENT" noEntErrorFired = true return # On Windows or when running as root, a chmod has no effect on named pipes if process.platform isnt "win32" and process.getuid() isnt 0 # Trying to connect to a socket one has no access to should result in EACCES accessServer = net.createServer(-> assert.ok false return ) accessServer.listen common.PIPE, -> fs.chmodSync common.PIPE, 0 accessClient = net.createConnection(common.PIPE, -> assert.ok false return ) accessClient.on "error", (err) -> assert.equal err.code, "EACCES" accessErrorFired = true accessServer.close() return return # Assert that all error events were fired process.on "exit", -> assert.ok notSocketErrorFired assert.ok noEntErrorFired assert.ok accessErrorFired if process.platform isnt "win32" and process.getuid() isnt 0 return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. fs = require("fs") net = require("net") path = require("path") assert = require("assert") common = require("../common") notSocketErrorFired = false noEntErrorFired = false accessErrorFired = false # Test if ENOTSOCK is fired when trying to connect to a file which is not # a socket. emptyTxt = undefined if process.platform is "win32" # on Win, common.PIPE will be a named pipe, so we use an existing empty # file instead emptyTxt = path.join(common.fixturesDir, "empty.txt") else # use common.PIPE to ensure we stay within POSIX socket path length # restrictions, even on CI cleanup = -> try fs.unlinkSync emptyTxt catch e throw e unless e.code is "ENOENT" return emptyTxt = common.PIPE + ".txt" process.on "exit", cleanup cleanup() fs.writeFileSync emptyTxt, "" notSocketClient = net.createConnection(emptyTxt, -> assert.ok false return ) notSocketClient.on "error", (err) -> assert err.code is "ENOTSOCK" or err.code is "ECONNREFUSED" notSocketErrorFired = true return # Trying to connect to not-existing socket should result in ENOENT error noEntSocketClient = net.createConnection("no-ent-file", -> assert.ok false return ) noEntSocketClient.on "error", (err) -> assert.equal err.code, "ENOENT" noEntErrorFired = true return # On Windows or when running as root, a chmod has no effect on named pipes if process.platform isnt "win32" and process.getuid() isnt 0 # Trying to connect to a socket one has no access to should result in EACCES accessServer = net.createServer(-> assert.ok false return ) accessServer.listen common.PIPE, -> fs.chmodSync common.PIPE, 0 accessClient = net.createConnection(common.PIPE, -> assert.ok false return ) accessClient.on "error", (err) -> assert.equal err.code, "EACCES" accessErrorFired = true accessServer.close() return return # Assert that all error events were fired process.on "exit", -> assert.ok notSocketErrorFired assert.ok noEntErrorFired assert.ok accessErrorFired if process.platform isnt "win32" and process.getuid() isnt 0 return
[ { "context": "send a form's data via AJAX regularly.\n\n Copyright Javi <elretirao@elretirao.net>\n This plugin is free so", "end": 106, "score": 0.9992444515228271, "start": 102, "tag": "NAME", "value": "Javi" }, { "context": "form's data via AJAX regularly.\n\n Copyright Javi <elretirao@elretirao.net>\n This plugin is free software. See http://docs.j", "end": 131, "score": 0.9999369978904724, "start": 108, "tag": "EMAIL", "value": "elretirao@elretirao.net" } ]
app/assets/javascripts/jquery.autosave_form.js.coffee
javierv/41cero10asesores
0
### Autosave form is a wrapper for jQuery.form to send a form's data via AJAX regularly. Copyright Javi <elretirao@elretirao.net> This plugin is free software. See http://docs.jquery.com/License for conditions. ### jQuery.fn.autosaveForm = (options) -> defaults = interval: 120000 jQuery.extend(defaults, options) this.each -> form = this setInterval( -> jQuery(form).ajaxSubmit(defaults), defaults.interval )
197124
### Autosave form is a wrapper for jQuery.form to send a form's data via AJAX regularly. Copyright <NAME> <<EMAIL>> This plugin is free software. See http://docs.jquery.com/License for conditions. ### jQuery.fn.autosaveForm = (options) -> defaults = interval: 120000 jQuery.extend(defaults, options) this.each -> form = this setInterval( -> jQuery(form).ajaxSubmit(defaults), defaults.interval )
true
### Autosave form is a wrapper for jQuery.form to send a form's data via AJAX regularly. Copyright PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> This plugin is free software. See http://docs.jquery.com/License for conditions. ### jQuery.fn.autosaveForm = (options) -> defaults = interval: 120000 jQuery.extend(defaults, options) this.each -> form = this setInterval( -> jQuery(form).ajaxSubmit(defaults), defaults.interval )
[ { "context": " 1\n\tslug: 'fincm3'\n\taliases: [ 'fincm3' ]\n\tname: 'Balena Fin (CM3)'\n\tarch: 'armv7hf'\n\tstate: 'released'\n\n\tinst", "end": 682, "score": 0.9264607429504395, "start": 672, "tag": "NAME", "value": "Balena Fin" } ]
fincm3.coffee
mfiumara/balena-raspberrypi
0
deviceTypesCommon = require '@resin.io/device-types/common' { networkOptions, commonImg, instructions } = deviceTypesCommon FIN_DEBUG = "While not having the Fin board powered, connect your system to the board's DBG/PRG port via a micro-USB cable.." FIN_POWER = "Power on the Fin by attaching power to either the Barrel or the Phoenix connector." FIN_WRITE = "Write the OS to the internal MMC storage device. We recommend using <a href=http://www.etcher.io/>Etcher</a>." FIN_POWEROFF = "When flashing is complete, power off the board by detaching the power and unplug the DGB micro-USB cable." module.exports = version: 1 slug: 'fincm3' aliases: [ 'fincm3' ] name: 'Balena Fin (CM3)' arch: 'armv7hf' state: 'released' instructions: [ FIN_DEBUG FIN_POWER FIN_WRITE FIN_POWEROFF instructions.CONNECT_AND_BOOT ] gettingStartedLink: windows: 'https://docs.resin.io/fincm3/nodejs/getting-started/#adding-your-first-device' osx: 'https://docs.resin.io/fincm3/nodejs/getting-started/#adding-your-first-device' linux: 'https://docs.resin.io/fincm3/nodejs/getting-started/#adding-your-first-device' supportsBlink: true options: [ networkOptions.group ] yocto: machine: 'fincm3' image: 'resin-image' fstype: 'resinos-img' version: 'yocto-warrior' deployArtifact: 'resin-image-fincm3.resinos-img' compressed: true configuration: config: partition: primary: 1 path: '/config.json' initialization: commonImg.initialization
166248
deviceTypesCommon = require '@resin.io/device-types/common' { networkOptions, commonImg, instructions } = deviceTypesCommon FIN_DEBUG = "While not having the Fin board powered, connect your system to the board's DBG/PRG port via a micro-USB cable.." FIN_POWER = "Power on the Fin by attaching power to either the Barrel or the Phoenix connector." FIN_WRITE = "Write the OS to the internal MMC storage device. We recommend using <a href=http://www.etcher.io/>Etcher</a>." FIN_POWEROFF = "When flashing is complete, power off the board by detaching the power and unplug the DGB micro-USB cable." module.exports = version: 1 slug: 'fincm3' aliases: [ 'fincm3' ] name: '<NAME> (CM3)' arch: 'armv7hf' state: 'released' instructions: [ FIN_DEBUG FIN_POWER FIN_WRITE FIN_POWEROFF instructions.CONNECT_AND_BOOT ] gettingStartedLink: windows: 'https://docs.resin.io/fincm3/nodejs/getting-started/#adding-your-first-device' osx: 'https://docs.resin.io/fincm3/nodejs/getting-started/#adding-your-first-device' linux: 'https://docs.resin.io/fincm3/nodejs/getting-started/#adding-your-first-device' supportsBlink: true options: [ networkOptions.group ] yocto: machine: 'fincm3' image: 'resin-image' fstype: 'resinos-img' version: 'yocto-warrior' deployArtifact: 'resin-image-fincm3.resinos-img' compressed: true configuration: config: partition: primary: 1 path: '/config.json' initialization: commonImg.initialization
true
deviceTypesCommon = require '@resin.io/device-types/common' { networkOptions, commonImg, instructions } = deviceTypesCommon FIN_DEBUG = "While not having the Fin board powered, connect your system to the board's DBG/PRG port via a micro-USB cable.." FIN_POWER = "Power on the Fin by attaching power to either the Barrel or the Phoenix connector." FIN_WRITE = "Write the OS to the internal MMC storage device. We recommend using <a href=http://www.etcher.io/>Etcher</a>." FIN_POWEROFF = "When flashing is complete, power off the board by detaching the power and unplug the DGB micro-USB cable." module.exports = version: 1 slug: 'fincm3' aliases: [ 'fincm3' ] name: 'PI:NAME:<NAME>END_PI (CM3)' arch: 'armv7hf' state: 'released' instructions: [ FIN_DEBUG FIN_POWER FIN_WRITE FIN_POWEROFF instructions.CONNECT_AND_BOOT ] gettingStartedLink: windows: 'https://docs.resin.io/fincm3/nodejs/getting-started/#adding-your-first-device' osx: 'https://docs.resin.io/fincm3/nodejs/getting-started/#adding-your-first-device' linux: 'https://docs.resin.io/fincm3/nodejs/getting-started/#adding-your-first-device' supportsBlink: true options: [ networkOptions.group ] yocto: machine: 'fincm3' image: 'resin-image' fstype: 'resinos-img' version: 'yocto-warrior' deployArtifact: 'resin-image-fincm3.resinos-img' compressed: true configuration: config: partition: primary: 1 path: '/config.json' initialization: commonImg.initialization
[ { "context": "s file is part of the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyrig", "end": 74, "score": 0.9998857378959656, "start": 61, "tag": "NAME", "value": "Jessym Reziga" }, { "context": "f the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyright and license informa", "end": 96, "score": 0.9999335408210754, "start": 76, "tag": "EMAIL", "value": "jessym@konsserto.com" }, { "context": "container accessible on an application\n#\n# @author Jessym Reziga <jessym@konsserto.com>\nclass ServiceContainer\n\n\n ", "end": 662, "score": 0.9998910427093506, "start": 649, "tag": "NAME", "value": "Jessym Reziga" }, { "context": "ible on an application\n#\n# @author Jessym Reziga <jessym@konsserto.com>\nclass ServiceContainer\n\n\n # Class constructor\n ", "end": 684, "score": 0.9999335408210754, "start": 664, "tag": "EMAIL", "value": "jessym@konsserto.com" } ]
node_modules/konsserto/lib/src/Konsserto/Component/DependencyInjection/ServiceContainer.coffee
konsserto/konsserto
2
### * This file is part of the Konsserto package. * * (c) Jessym Reziga <jessym@konsserto.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### filesystem = use('fs') GLOBAL_SERVICES = use('/app/config/services') KERNEL_SERVICES = use('@Konsserto/Component/DependencyInjection/services/services') ServiceDefinition = use('@Konsserto/Component/DependencyInjection/ServiceDefinition') ServiceInstance = use('@Konsserto/Component/DependencyInjection/ServiceInstance') # ServiceContainer injects services in a container accessible on an application # # @author Jessym Reziga <jessym@konsserto.com> class ServiceContainer # Class constructor # @param {Kernel} kernel The kernel of Konsserto constructor: (@kernel) -> @services = {} @loaded = {} @set('Kernel', @kernel) @set('Container', this) @setupKernel() @setupGlobalAndBundles() console.log '[Container] DI Services OK' # Setting up the Kernel configurations setupKernel: () -> @addServiceInstance(KERNEL_SERVICES, 'konsserto') @updateForInjectors() # Setting up the global and bundles configurations setupGlobalAndBundles: () -> # /app/config/services.js @addServiceInstance(GLOBAL_SERVICES, 'global') # /src/bundles/.../config/services.js bundles = @get('Application').getBundles() for bundleName,bundle of bundles if filesystem.existsSync(bundle.getConfigPath() + '/services.js') services = use(bundle.getConfigNamespace() + '/services') @addServiceInstance(services) @updateForInjectors() # Create the services instance a unique time # @param [Object] services Liste of the services to create and instanciate only one time # @param {String} type Type of the service (like global), default is null addServiceInstance: (services, type = null) -> for service in services serviceDefinition = new ServiceDefinition(service, type) serviceInstance = new ServiceInstance(serviceDefinition) @services[serviceDefinition.getName()] = serviceInstance # Compile the service passed in parameter # @param {ServiceInstance} service The service instance to compile compile: (service) -> for serviceArgument in service.getDefinition().getServiceArgumentsOnly() @compile(@getServiceInstance(serviceArgument.getValue())) if (!service.instanceExists()) service.evaluateInstance(this) # Check if old services (with args) need dependencies from latest registered services /!\ For Kernel purpose only ! updateForInjectors: () => for name, service of @services @compile(service) # @param {ServiceDefinition} serviceDefinition The service definition to instanciate # Inject a service manually => Need to updateForInjectors after /!\ For Kernel purpose only ! inject: (serviceDefinition, value) => serviceInstance = new ServiceInstance(serviceDefinition) serviceInstance.setInstance(value) @services[serviceDefinition.getName()] = serviceInstance # Get service by name # @param {String} name The name of the service to return # @param {Boolean} debug Should I use debug mode ? default is true # @return {Object} The service concerned get: (name, debug = true) => formatName = name.toLowerCase() if @has(formatName) return @services[formatName].getInstance() if debug throw new Error('Can\'t get the service : ' + name) return null # Check if a service exists # @param {String} name The name of the service to check # @return {Boolean} True if exists, false in the other cases has: (name) => formatName = name.toLowerCase() if @services[formatName]? return true return false # Get the service definition # @param {String} name The name of the service to find # @return {ServiceDefinition} The service definition or null getServiceDefinition: (name) => formatName = name.toLowerCase() if @has(formatName) return @getServiceInstance(formatName).getDefinition() return null # Get the service instance # @param {String} name The name of the service to find # @return {ServiceInstance} The service instance or null getServiceInstance: (name) => formatName = name.toLowerCase() if @has(formatName) return @services[formatName] return null # Set a service instance # @param {String} name The name of the service # @param {Object} value The value to inject in the ServiceDefinition # @param [Object] args The args to inject in the ServiceDefinition set: (name, value, args = []) -> if @has(name) throw new Error('The service ' + name + ' is already registered in container') service = value.constructor if service._fromUsed? && service._fromUsed.charAt(0) == '@' serviceDefinition = new ServiceDefinition({ name: name, _class: service._fromUsed, args: args }, 'kernel') @inject(serviceDefinition, value) else throw new Error('The definition of service ' + name + ' is not a Konsserto Service') module.exports = ServiceContainer
81121
### * This file is part of the Konsserto package. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### filesystem = use('fs') GLOBAL_SERVICES = use('/app/config/services') KERNEL_SERVICES = use('@Konsserto/Component/DependencyInjection/services/services') ServiceDefinition = use('@Konsserto/Component/DependencyInjection/ServiceDefinition') ServiceInstance = use('@Konsserto/Component/DependencyInjection/ServiceInstance') # ServiceContainer injects services in a container accessible on an application # # @author <NAME> <<EMAIL>> class ServiceContainer # Class constructor # @param {Kernel} kernel The kernel of Konsserto constructor: (@kernel) -> @services = {} @loaded = {} @set('Kernel', @kernel) @set('Container', this) @setupKernel() @setupGlobalAndBundles() console.log '[Container] DI Services OK' # Setting up the Kernel configurations setupKernel: () -> @addServiceInstance(KERNEL_SERVICES, 'konsserto') @updateForInjectors() # Setting up the global and bundles configurations setupGlobalAndBundles: () -> # /app/config/services.js @addServiceInstance(GLOBAL_SERVICES, 'global') # /src/bundles/.../config/services.js bundles = @get('Application').getBundles() for bundleName,bundle of bundles if filesystem.existsSync(bundle.getConfigPath() + '/services.js') services = use(bundle.getConfigNamespace() + '/services') @addServiceInstance(services) @updateForInjectors() # Create the services instance a unique time # @param [Object] services Liste of the services to create and instanciate only one time # @param {String} type Type of the service (like global), default is null addServiceInstance: (services, type = null) -> for service in services serviceDefinition = new ServiceDefinition(service, type) serviceInstance = new ServiceInstance(serviceDefinition) @services[serviceDefinition.getName()] = serviceInstance # Compile the service passed in parameter # @param {ServiceInstance} service The service instance to compile compile: (service) -> for serviceArgument in service.getDefinition().getServiceArgumentsOnly() @compile(@getServiceInstance(serviceArgument.getValue())) if (!service.instanceExists()) service.evaluateInstance(this) # Check if old services (with args) need dependencies from latest registered services /!\ For Kernel purpose only ! updateForInjectors: () => for name, service of @services @compile(service) # @param {ServiceDefinition} serviceDefinition The service definition to instanciate # Inject a service manually => Need to updateForInjectors after /!\ For Kernel purpose only ! inject: (serviceDefinition, value) => serviceInstance = new ServiceInstance(serviceDefinition) serviceInstance.setInstance(value) @services[serviceDefinition.getName()] = serviceInstance # Get service by name # @param {String} name The name of the service to return # @param {Boolean} debug Should I use debug mode ? default is true # @return {Object} The service concerned get: (name, debug = true) => formatName = name.toLowerCase() if @has(formatName) return @services[formatName].getInstance() if debug throw new Error('Can\'t get the service : ' + name) return null # Check if a service exists # @param {String} name The name of the service to check # @return {Boolean} True if exists, false in the other cases has: (name) => formatName = name.toLowerCase() if @services[formatName]? return true return false # Get the service definition # @param {String} name The name of the service to find # @return {ServiceDefinition} The service definition or null getServiceDefinition: (name) => formatName = name.toLowerCase() if @has(formatName) return @getServiceInstance(formatName).getDefinition() return null # Get the service instance # @param {String} name The name of the service to find # @return {ServiceInstance} The service instance or null getServiceInstance: (name) => formatName = name.toLowerCase() if @has(formatName) return @services[formatName] return null # Set a service instance # @param {String} name The name of the service # @param {Object} value The value to inject in the ServiceDefinition # @param [Object] args The args to inject in the ServiceDefinition set: (name, value, args = []) -> if @has(name) throw new Error('The service ' + name + ' is already registered in container') service = value.constructor if service._fromUsed? && service._fromUsed.charAt(0) == '@' serviceDefinition = new ServiceDefinition({ name: name, _class: service._fromUsed, args: args }, 'kernel') @inject(serviceDefinition, value) else throw new Error('The definition of service ' + name + ' is not a Konsserto Service') module.exports = ServiceContainer
true
### * This file is part of the Konsserto package. * * (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### filesystem = use('fs') GLOBAL_SERVICES = use('/app/config/services') KERNEL_SERVICES = use('@Konsserto/Component/DependencyInjection/services/services') ServiceDefinition = use('@Konsserto/Component/DependencyInjection/ServiceDefinition') ServiceInstance = use('@Konsserto/Component/DependencyInjection/ServiceInstance') # ServiceContainer injects services in a container accessible on an application # # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> class ServiceContainer # Class constructor # @param {Kernel} kernel The kernel of Konsserto constructor: (@kernel) -> @services = {} @loaded = {} @set('Kernel', @kernel) @set('Container', this) @setupKernel() @setupGlobalAndBundles() console.log '[Container] DI Services OK' # Setting up the Kernel configurations setupKernel: () -> @addServiceInstance(KERNEL_SERVICES, 'konsserto') @updateForInjectors() # Setting up the global and bundles configurations setupGlobalAndBundles: () -> # /app/config/services.js @addServiceInstance(GLOBAL_SERVICES, 'global') # /src/bundles/.../config/services.js bundles = @get('Application').getBundles() for bundleName,bundle of bundles if filesystem.existsSync(bundle.getConfigPath() + '/services.js') services = use(bundle.getConfigNamespace() + '/services') @addServiceInstance(services) @updateForInjectors() # Create the services instance a unique time # @param [Object] services Liste of the services to create and instanciate only one time # @param {String} type Type of the service (like global), default is null addServiceInstance: (services, type = null) -> for service in services serviceDefinition = new ServiceDefinition(service, type) serviceInstance = new ServiceInstance(serviceDefinition) @services[serviceDefinition.getName()] = serviceInstance # Compile the service passed in parameter # @param {ServiceInstance} service The service instance to compile compile: (service) -> for serviceArgument in service.getDefinition().getServiceArgumentsOnly() @compile(@getServiceInstance(serviceArgument.getValue())) if (!service.instanceExists()) service.evaluateInstance(this) # Check if old services (with args) need dependencies from latest registered services /!\ For Kernel purpose only ! updateForInjectors: () => for name, service of @services @compile(service) # @param {ServiceDefinition} serviceDefinition The service definition to instanciate # Inject a service manually => Need to updateForInjectors after /!\ For Kernel purpose only ! inject: (serviceDefinition, value) => serviceInstance = new ServiceInstance(serviceDefinition) serviceInstance.setInstance(value) @services[serviceDefinition.getName()] = serviceInstance # Get service by name # @param {String} name The name of the service to return # @param {Boolean} debug Should I use debug mode ? default is true # @return {Object} The service concerned get: (name, debug = true) => formatName = name.toLowerCase() if @has(formatName) return @services[formatName].getInstance() if debug throw new Error('Can\'t get the service : ' + name) return null # Check if a service exists # @param {String} name The name of the service to check # @return {Boolean} True if exists, false in the other cases has: (name) => formatName = name.toLowerCase() if @services[formatName]? return true return false # Get the service definition # @param {String} name The name of the service to find # @return {ServiceDefinition} The service definition or null getServiceDefinition: (name) => formatName = name.toLowerCase() if @has(formatName) return @getServiceInstance(formatName).getDefinition() return null # Get the service instance # @param {String} name The name of the service to find # @return {ServiceInstance} The service instance or null getServiceInstance: (name) => formatName = name.toLowerCase() if @has(formatName) return @services[formatName] return null # Set a service instance # @param {String} name The name of the service # @param {Object} value The value to inject in the ServiceDefinition # @param [Object] args The args to inject in the ServiceDefinition set: (name, value, args = []) -> if @has(name) throw new Error('The service ' + name + ' is already registered in container') service = value.constructor if service._fromUsed? && service._fromUsed.charAt(0) == '@' serviceDefinition = new ServiceDefinition({ name: name, _class: service._fromUsed, args: args }, 'kernel') @inject(serviceDefinition, value) else throw new Error('The definition of service ' + name + ' is not a Konsserto Service') module.exports = ServiceContainer
[ { "context": " [{\n id: '1'\n key: 'f1'\n value: { type: 'link' }\n ", "end": 584, "score": 0.7747559547424316, "start": 582, "tag": "KEY", "value": "f1" }, { "context": "{\n id: 'f1'\n key: 'f1'\n value: { type: 'file', linkNotFo", "end": 2032, "score": 0.7900975346565247, "start": 2031, "tag": "KEY", "value": "1" }, { "context": "[{\n id: 'b1'\n key: 'f1'\n value: { type: 'link' }\n ", "end": 2544, "score": 0.8325690031051636, "start": 2542, "tag": "KEY", "value": "f1" }, { "context": "{\n id: 'b2'\n key: 'f1'\n value: { type: 'link' }\n ", "end": 2651, "score": 0.8785806894302368, "start": 2650, "tag": "KEY", "value": "1" }, { "context": "{\n id: 'b3'\n key: 'f1'\n value: { type: 'link' }\n ", "end": 2758, "score": 0.7226182818412781, "start": 2757, "tag": "KEY", "value": "1" }, { "context": "{\n id: 'f1'\n key: 'f1'\n value: { type: 'file', linkNotFo", "end": 2878, "score": 0.9184215068817139, "start": 2877, "tag": "KEY", "value": "1" }, { "context": "{\n id: 'f1'\n key: 'f1'\n value: { type: 'file', linkNotFo", "end": 3463, "score": 0.768765926361084, "start": 3462, "tag": "KEY", "value": "1" }, { "context": "{\n id: 'b1'\n key: 'f2'\n value: { type: 'link' }\n ", "end": 3588, "score": 0.9091596603393555, "start": 3587, "tag": "KEY", "value": "2" }, { "context": " {\n id: 'f1'\n key: 'f1'\n value: { type: 'file', linkNotFo", "end": 4264, "score": 0.8471921682357788, "start": 4262, "tag": "KEY", "value": "f1" }, { "context": "{\n id: 'b2'\n key: 'f2'\n value: { type: 'link' }\n ", "end": 4497, "score": 0.854863703250885, "start": 4496, "tag": "KEY", "value": "2" }, { "context": "{\n id: 'f2'\n key: 'f2'\n value: { type: 'file', linkNotFo", "end": 4605, "score": 0.804680585861206, "start": 4604, "tag": "KEY", "value": "2" }, { "context": "{\n id: 'f1'\n key: 'f1'\n value: { type: 'file', linkNotFo", "end": 4922, "score": 0.8967686891555786, "start": 4921, "tag": "KEY", "value": "1" }, { "context": "{\n id: 'f2'\n key: 'f2'\n value: { type: 'file', linkNotFo", "end": 5048, "score": 0.9513372182846069, "start": 5047, "tag": "KEY", "value": "2" }, { "context": "{\n id: 'b3'\n key: 'f5'\n value: { type: 'link' }\n ", "end": 5174, "score": 0.889864444732666, "start": 5173, "tag": "KEY", "value": "5" }, { "context": "{\n id: 'b4'\n key: 'f6'\n value: { type: 'link' }\n ", "end": 5282, "score": 0.9488058686256409, "start": 5281, "tag": "KEY", "value": "6" }, { "context": "{\n id: 'f7'\n key: 'f7'\n value: { type: 'file', linkNotFo", "end": 5389, "score": 0.9317869544029236, "start": 5388, "tag": "KEY", "value": "7" }, { "context": "{\n id: 'b5'\n key: 'f7'\n value: { type: 'link' }\n ", "end": 5516, "score": 0.9438842535018921, "start": 5515, "tag": "KEY", "value": "7" }, { "context": "{\n id: 'f8'\n key: 'f8'\n value: { type: 'file', linkNotFo", "end": 5624, "score": 0.9588544964790344, "start": 5623, "tag": "KEY", "value": "8" }, { "context": "{\n id: 'b3'\n key: 'f8'\n value: { type: 'link' }\n ", "end": 5750, "score": 0.9332177042961121, "start": 5749, "tag": "KEY", "value": "8" }, { "context": "{\n id: 'b4'\n key: 'f9'\n value: { type: 'link' }\n ", "end": 5858, "score": 0.9577256441116333, "start": 5857, "tag": "KEY", "value": "9" }, { "context": " id: 'b666'\n key: 'f1'\n value: { type: 'link' }\n ", "end": 6374, "score": 0.7512125968933105, "start": 6373, "tag": "KEY", "value": "1" }, { "context": ": 'link' }\n }, {\n id: 'b777'\n key: 'f4'\n value", "end": 7623, "score": 0.5540837049484253, "start": 7621, "tag": "USERNAME", "value": "77" }, { "context": "{\n id: 'b4'\n key: 'f6'\n value: { type: 'link' }\n ", "end": 8443, "score": 0.6268491148948669, "start": 8442, "tag": "KEY", "value": "6" }, { "context": "{\n id: 'b3'\n key: 'f9'\n value: { type: 'link' }\n ", "end": 8803, "score": 0.9620274305343628, "start": 8802, "tag": "KEY", "value": "9" }, { "context": "{\n id: 'f9'\n key: 'f9'\n value: { type: 'file', linkNotFo", "end": 8911, "score": 0.8417384624481201, "start": 8910, "tag": "KEY", "value": "9" }, { "context": " id: 'b666'\n key: 'f1'\n value: { type: 'link' }\n ", "end": 9592, "score": 0.8554221391677856, "start": 9591, "tag": "KEY", "value": "1" }, { "context": ": 'link' }\n }, {\n id: 'b777'\n key: 'f1'\n value:", "end": 9676, "score": 0.6577356457710266, "start": 9673, "tag": "USERNAME", "value": "777" }, { "context": " id: 'b777'\n key: 'f1'\n value: { type: 'link' }\n ", "end": 9702, "score": 0.6939269304275513, "start": 9701, "tag": "KEY", "value": "1" }, { "context": " id: 'b666'\n key: 'f2'\n value: { type: 'link' }\n ", "end": 9939, "score": 0.8746107220649719, "start": 9938, "tag": "KEY", "value": "2" }, { "context": ": 'link' }\n }, {\n id: 'b777'\n key: 'f2'\n value", "end": 10022, "score": 0.6180785894393921, "start": 10020, "tag": "USERNAME", "value": "77" }, { "context": " id: 'b777'\n key: 'f2'\n value: { type: 'link' }\n ", "end": 10049, "score": 0.7494110465049744, "start": 10048, "tag": "KEY", "value": "2" }, { "context": "{\n id: 'f3'\n key: 'f3'\n value: { type: 'file', linkNotFo", "end": 10283, "score": 0.6626448035240173, "start": 10282, "tag": "KEY", "value": "3" }, { "context": "\n id: 'b666'\n key: 'f3'\n value: { type: 'link' }\n ", "end": 10411, "score": 0.7806227207183838, "start": 10409, "tag": "KEY", "value": "f3" }, { "context": ": 'link' }\n }, {\n id: 'b777'\n key: 'f3'\n value", "end": 10494, "score": 0.5478724241256714, "start": 10492, "tag": "USERNAME", "value": "77" }, { "context": "\n id: 'b777'\n key: 'f3'\n value: { type: 'link' }\n ", "end": 10521, "score": 0.758967399597168, "start": 10519, "tag": "KEY", "value": "f3" }, { "context": " id: 'b666'\n key: 'f4'\n value: { type: 'link' }\n ", "end": 10758, "score": 0.9214432239532471, "start": 10757, "tag": "KEY", "value": "4" }, { "context": " id: 'b777'\n key: 'f4'\n value: { type: 'link' }\n ", "end": 10868, "score": 0.7463850975036621, "start": 10867, "tag": "KEY", "value": "4" }, { "context": "{\n id: 'b3'\n key: 'f5'\n value: { type: 'link' }\n ", "end": 10976, "score": 0.5441656112670898, "start": 10975, "tag": "KEY", "value": "5" }, { "context": "{\n id: 'b8'\n key: 'f5'\n value: { type: 'link' }\n ", "end": 11211, "score": 0.528895914554596, "start": 11210, "tag": "KEY", "value": "5" }, { "context": " {\n id: 'f6'\n key: 'f6'\n value: { type: 'file', linkNotFo", "end": 12916, "score": 0.7889313697814941, "start": 12914, "tag": "KEY", "value": "f6" }, { "context": "{\n id: 'b8'\n key: 'f6'\n value: { type: 'link' }\n ", "end": 13042, "score": 0.9718825817108154, "start": 13041, "tag": "KEY", "value": "6" }, { "context": "{\n id: 'f7'\n key: 'f7'\n value: { type: 'file', linkNotFo", "end": 13150, "score": 0.9764490127563477, "start": 13149, "tag": "KEY", "value": "7" }, { "context": "{\n id: 'b4'\n key: 'f7'\n value: { type: 'link' }\n ", "end": 13276, "score": 0.9652231931686401, "start": 13275, "tag": "KEY", "value": "7" }, { "context": "{\n id: 'b4'\n key: 'f8'\n value: { type: 'link' }\n ", "end": 13384, "score": 0.9270621538162231, "start": 13383, "tag": "KEY", "value": "8" }, { "context": "{\n id: 'f8'\n key: 'f8'\n value: { type: 'file', linkNotFo", "end": 13492, "score": 0.9606677889823914, "start": 13491, "tag": "KEY", "value": "8" }, { "context": "{\n id: 'f9'\n key: 'f9'\n value: { type: 'file', linkNotFo", "end": 13618, "score": 0.8909780383110046, "start": 13617, "tag": "KEY", "value": "9" }, { "context": "{\n id: 'b3'\n key: 'f9'\n value: { type: 'link' }\n ", "end": 13744, "score": 0.8886876106262207, "start": 13743, "tag": "KEY", "value": "9" } ]
src/tests/server/file/test_file_cleaner.coffee
LaPingvino/rizzoma
88
sinon = require('sinon-plus') testCase = require('nodeunit').testCase FileCleaner = require('../../../server/file/file_cleaner').FileCleaner dataprovider = require('dataprovider') module.exports = FileCleanerTest: testCase setUp: (callback) -> @fileCleaner = new FileCleaner callback() testGetFilesForProcessing0: (test) -> test.deepEqual([], @fileCleaner._getFilesForProcessing([])) test.done() testGetFilesForProcessing1: (test) -> files = [{ id: '1' key: 'f1' value: { type: 'link' } },{ id: 'f2' key: 'f2' value: { type: 'link' } }] test.deepEqual([], @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing2: (test) -> files = [{ id: 'b1' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: yes } }] res = [{ fileId: 'f1' found: yes }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing3: (test) -> files = [{ id: 'b1' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: no } }] res = [] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing4: (test) -> files = [{ id: 'b1' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: no } },{ id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: no } }] res = [{ fileId: 'f2' found: no }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing5: (test) -> files = [{ id: 'b1' key: 'f1' value: { type: 'link' } },{ id: 'b2' key: 'f1' value: { type: 'link' } },{ id: 'b3' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: yes } },{ id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: no } }] res = [{ fileId: 'f1' found: yes },{ fileId: 'f2' found: no }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing6: (test) -> files = [{ id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: no } },{ id: 'b1' key: 'f2' value: { type: 'link' } },{ id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: yes } }] res = [{ fileId: 'f1' found: no }, { fileId: 'f2' found: yes }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing7: (test) -> files = [{ id: 'b1' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: no } },{ id: 'b1' key: 'f2' value: { type: 'link' } }, { id: 'b2' key: 'f2' value: { type: 'link' } }, { id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: no } }] res = [] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing8: (test) -> files = [{ id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: no } }, { id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'f5' value: { type: 'link' } }, { id: 'b4' key: 'f6' value: { type: 'link' } },{ id: 'f7' key: 'f7' value: { type: 'file', linkNotFound: yes } }, { id: 'b5' key: 'f7' value: { type: 'link' } }, { id: 'f8' key: 'f8' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'f8' value: { type: 'link' } }, { id: 'b4' key: 'f9' value: { type: 'link' } }] res = [{ fileId: 'f1' found: no }, { fileId: 'f2' found: no }, { fileId: 'f7' found: yes }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing9: (test) -> files = [{ id: 'b666' key: 'f1' value: { type: 'link' } }, { id: 'b777' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: yes } }, { id: 'b666' key: 'f2' value: { type: 'link' } }, { id: 'b777' key: 'f2' value: { type: 'link' } }, { id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: no } }, { id: 'f3' key: 'f3' value: { type: 'file', linkNotFound: no } }, { id: 'b666' key: 'f3' value: { type: 'link' } }, { id: 'b777' key: 'f3' value: { type: 'link' } }, { id: 'f4' key: 'f4' value: { type: 'file', linkNotFound: yes } }, { id: 'b666' key: 'f4' value: { type: 'link' } }, { id: 'b777' key: 'f4' value: { type: 'link' } }, { id: 'b3' key: 'f5' value: { type: 'link' } }, { id: 'f5' key: 'f5' value: { type: 'file', linkNotFound: yes } }, { id: 'b8' key: 'f5' value: { type: 'link' } }, { id: 'b3' key: 'f6' value: { type: 'link' } }, { id: 'f6' key: 'f6' value: { type: 'file', linkNotFound: no } }, { id: 'b8' key: 'f6' value: { type: 'link' } }, { id: 'b4' key: 'f6' value: { type: 'link' } },{ id: 'f7' key: 'f7' value: { type: 'file', linkNotFound: yes } }, { id: 'f8' key: 'f8' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'f9' value: { type: 'link' } }, { id: 'f9' key: 'f9' value: { type: 'file', linkNotFound: no } }] res = [{ fileId: 'f1' found: yes }, { fileId: 'f4' found: yes }, { fileId: 'f5' found: yes }, { fileId: 'f7' found: no }, { fileId: 'f8' found: no }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing10: (test) -> files = [{ id: 'b666' key: 'f1' value: { type: 'link' } }, { id: 'b777' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: yes } }, { id: 'b666' key: 'f2' value: { type: 'link' } }, { id: 'b777' key: 'f2' value: { type: 'link' } }, { id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: no } }, { id: 'f3' key: 'f3' value: { type: 'file', linkNotFound: no } }, { id: 'b666' key: 'f3' value: { type: 'link' } }, { id: 'b777' key: 'f3' value: { type: 'link' } }, { id: 'f4' key: 'f4' value: { type: 'file', linkNotFound: yes } }, { id: 'b666' key: 'f4' value: { type: 'link' } }, { id: 'b777' key: 'f4' value: { type: 'link' } }, { id: 'b3' key: 'f5' value: { type: 'link' } }, { id: 'f5' key: 'f5' value: { type: 'file', linkNotFound: yes } }, { id: 'b8' key: 'f5' value: { type: 'link' } }, { id: 'b3' key: 'f6' value: { type: 'link' } }, { id: 'f6' key: 'f6' value: { type: 'file', linkNotFound: no } }, { id: 'b8' key: 'f6' value: { type: 'link' } }, { id: 'b4' key: 'f6' value: { type: 'link' } },{ id: 'f7' key: 'f7' value: { type: 'file', linkNotFound: yes } }, { id: 'f8' key: 'f8' value: { type: 'file', linkNotFound: no } }, { id: 'f9' key: 'f9' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'f9' value: { type: 'link' } }] res = [{ fileId: 'f1' found: yes }, { fileId: 'f4' found: yes }, { fileId: 'f5' found: yes }, { fileId: 'f7' found: no }, { fileId: 'f8' found: no }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing11: (test) -> files = [{ id: 'b3' key: 'f6' value: { type: 'link' } }, { id: 'f6' key: 'f6' value: { type: 'file', linkNotFound: no } }, { id: 'b8' key: 'f6' value: { type: 'link' } }, { id: 'f7' key: 'f7' value: { type: 'file', linkNotFound: no } }, { id: 'b4' key: 'f7' value: { type: 'link' } }, { id: 'b4' key: 'f8' value: { type: 'link' } }, { id: 'f8' key: 'f8' value: { type: 'file', linkNotFound: no } }, { id: 'f9' key: 'f9' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'f9' value: { type: 'link' } }] res = [] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done()
3267
sinon = require('sinon-plus') testCase = require('nodeunit').testCase FileCleaner = require('../../../server/file/file_cleaner').FileCleaner dataprovider = require('dataprovider') module.exports = FileCleanerTest: testCase setUp: (callback) -> @fileCleaner = new FileCleaner callback() testGetFilesForProcessing0: (test) -> test.deepEqual([], @fileCleaner._getFilesForProcessing([])) test.done() testGetFilesForProcessing1: (test) -> files = [{ id: '1' key: '<KEY>' value: { type: 'link' } },{ id: 'f2' key: 'f2' value: { type: 'link' } }] test.deepEqual([], @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing2: (test) -> files = [{ id: 'b1' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: yes } }] res = [{ fileId: 'f1' found: yes }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing3: (test) -> files = [{ id: 'b1' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: no } }] res = [] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing4: (test) -> files = [{ id: 'b1' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'f<KEY>' value: { type: 'file', linkNotFound: no } },{ id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: no } }] res = [{ fileId: 'f2' found: no }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing5: (test) -> files = [{ id: 'b1' key: '<KEY>' value: { type: 'link' } },{ id: 'b2' key: 'f<KEY>' value: { type: 'link' } },{ id: 'b3' key: 'f<KEY>' value: { type: 'link' } }, { id: 'f1' key: 'f<KEY>' value: { type: 'file', linkNotFound: yes } },{ id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: no } }] res = [{ fileId: 'f1' found: yes },{ fileId: 'f2' found: no }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing6: (test) -> files = [{ id: 'f1' key: 'f<KEY>' value: { type: 'file', linkNotFound: no } },{ id: 'b1' key: 'f<KEY>' value: { type: 'link' } },{ id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: yes } }] res = [{ fileId: 'f1' found: no }, { fileId: 'f2' found: yes }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing7: (test) -> files = [{ id: 'b1' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: '<KEY>' value: { type: 'file', linkNotFound: no } },{ id: 'b1' key: 'f2' value: { type: 'link' } }, { id: 'b2' key: 'f<KEY>' value: { type: 'link' } }, { id: 'f2' key: 'f<KEY>' value: { type: 'file', linkNotFound: no } }] res = [] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing8: (test) -> files = [{ id: 'f1' key: 'f<KEY>' value: { type: 'file', linkNotFound: no } }, { id: 'f2' key: 'f<KEY>' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'f<KEY>' value: { type: 'link' } }, { id: 'b4' key: 'f<KEY>' value: { type: 'link' } },{ id: 'f7' key: 'f<KEY>' value: { type: 'file', linkNotFound: yes } }, { id: 'b5' key: 'f<KEY>' value: { type: 'link' } }, { id: 'f8' key: 'f<KEY>' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'f<KEY>' value: { type: 'link' } }, { id: 'b4' key: 'f<KEY>' value: { type: 'link' } }] res = [{ fileId: 'f1' found: no }, { fileId: 'f2' found: no }, { fileId: 'f7' found: yes }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing9: (test) -> files = [{ id: 'b666' key: 'f<KEY>' value: { type: 'link' } }, { id: 'b777' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: yes } }, { id: 'b666' key: 'f2' value: { type: 'link' } }, { id: 'b777' key: 'f2' value: { type: 'link' } }, { id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: no } }, { id: 'f3' key: 'f3' value: { type: 'file', linkNotFound: no } }, { id: 'b666' key: 'f3' value: { type: 'link' } }, { id: 'b777' key: 'f3' value: { type: 'link' } }, { id: 'f4' key: 'f4' value: { type: 'file', linkNotFound: yes } }, { id: 'b666' key: 'f4' value: { type: 'link' } }, { id: 'b777' key: 'f4' value: { type: 'link' } }, { id: 'b3' key: 'f5' value: { type: 'link' } }, { id: 'f5' key: 'f5' value: { type: 'file', linkNotFound: yes } }, { id: 'b8' key: 'f5' value: { type: 'link' } }, { id: 'b3' key: 'f6' value: { type: 'link' } }, { id: 'f6' key: 'f6' value: { type: 'file', linkNotFound: no } }, { id: 'b8' key: 'f6' value: { type: 'link' } }, { id: 'b4' key: 'f<KEY>' value: { type: 'link' } },{ id: 'f7' key: 'f7' value: { type: 'file', linkNotFound: yes } }, { id: 'f8' key: 'f8' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'f<KEY>' value: { type: 'link' } }, { id: 'f9' key: 'f<KEY>' value: { type: 'file', linkNotFound: no } }] res = [{ fileId: 'f1' found: yes }, { fileId: 'f4' found: yes }, { fileId: 'f5' found: yes }, { fileId: 'f7' found: no }, { fileId: 'f8' found: no }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing10: (test) -> files = [{ id: 'b666' key: 'f<KEY>' value: { type: 'link' } }, { id: 'b777' key: 'f<KEY>' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: yes } }, { id: 'b666' key: 'f<KEY>' value: { type: 'link' } }, { id: 'b777' key: 'f<KEY>' value: { type: 'link' } }, { id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: no } }, { id: 'f3' key: 'f<KEY>' value: { type: 'file', linkNotFound: no } }, { id: 'b666' key: '<KEY>' value: { type: 'link' } }, { id: 'b777' key: '<KEY>' value: { type: 'link' } }, { id: 'f4' key: 'f4' value: { type: 'file', linkNotFound: yes } }, { id: 'b666' key: 'f<KEY>' value: { type: 'link' } }, { id: 'b777' key: 'f<KEY>' value: { type: 'link' } }, { id: 'b3' key: 'f<KEY>' value: { type: 'link' } }, { id: 'f5' key: 'f5' value: { type: 'file', linkNotFound: yes } }, { id: 'b8' key: 'f<KEY>' value: { type: 'link' } }, { id: 'b3' key: 'f6' value: { type: 'link' } }, { id: 'f6' key: 'f6' value: { type: 'file', linkNotFound: no } }, { id: 'b8' key: 'f6' value: { type: 'link' } }, { id: 'b4' key: 'f6' value: { type: 'link' } },{ id: 'f7' key: 'f7' value: { type: 'file', linkNotFound: yes } }, { id: 'f8' key: 'f8' value: { type: 'file', linkNotFound: no } }, { id: 'f9' key: 'f9' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'f9' value: { type: 'link' } }] res = [{ fileId: 'f1' found: yes }, { fileId: 'f4' found: yes }, { fileId: 'f5' found: yes }, { fileId: 'f7' found: no }, { fileId: 'f8' found: no }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing11: (test) -> files = [{ id: 'b3' key: 'f6' value: { type: 'link' } }, { id: 'f6' key: '<KEY>' value: { type: 'file', linkNotFound: no } }, { id: 'b8' key: 'f<KEY>' value: { type: 'link' } }, { id: 'f7' key: 'f<KEY>' value: { type: 'file', linkNotFound: no } }, { id: 'b4' key: 'f<KEY>' value: { type: 'link' } }, { id: 'b4' key: 'f<KEY>' value: { type: 'link' } }, { id: 'f8' key: 'f<KEY>' value: { type: 'file', linkNotFound: no } }, { id: 'f9' key: 'f<KEY>' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'f<KEY>' value: { type: 'link' } }] res = [] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done()
true
sinon = require('sinon-plus') testCase = require('nodeunit').testCase FileCleaner = require('../../../server/file/file_cleaner').FileCleaner dataprovider = require('dataprovider') module.exports = FileCleanerTest: testCase setUp: (callback) -> @fileCleaner = new FileCleaner callback() testGetFilesForProcessing0: (test) -> test.deepEqual([], @fileCleaner._getFilesForProcessing([])) test.done() testGetFilesForProcessing1: (test) -> files = [{ id: '1' key: 'PI:KEY:<KEY>END_PI' value: { type: 'link' } },{ id: 'f2' key: 'f2' value: { type: 'link' } }] test.deepEqual([], @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing2: (test) -> files = [{ id: 'b1' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: yes } }] res = [{ fileId: 'f1' found: yes }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing3: (test) -> files = [{ id: 'b1' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: no } }] res = [] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing4: (test) -> files = [{ id: 'b1' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: no } },{ id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: no } }] res = [{ fileId: 'f2' found: no }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing5: (test) -> files = [{ id: 'b1' key: 'PI:KEY:<KEY>END_PI' value: { type: 'link' } },{ id: 'b2' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } },{ id: 'b3' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'f1' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: yes } },{ id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: no } }] res = [{ fileId: 'f1' found: yes },{ fileId: 'f2' found: no }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing6: (test) -> files = [{ id: 'f1' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: no } },{ id: 'b1' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } },{ id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: yes } }] res = [{ fileId: 'f1' found: no }, { fileId: 'f2' found: yes }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing7: (test) -> files = [{ id: 'b1' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'PI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: no } },{ id: 'b1' key: 'f2' value: { type: 'link' } }, { id: 'b2' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'f2' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: no } }] res = [] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing8: (test) -> files = [{ id: 'f1' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: no } }, { id: 'f2' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'b4' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } },{ id: 'f7' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: yes } }, { id: 'b5' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'f8' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'b4' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }] res = [{ fileId: 'f1' found: no }, { fileId: 'f2' found: no }, { fileId: 'f7' found: yes }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing9: (test) -> files = [{ id: 'b666' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'b777' key: 'f1' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: yes } }, { id: 'b666' key: 'f2' value: { type: 'link' } }, { id: 'b777' key: 'f2' value: { type: 'link' } }, { id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: no } }, { id: 'f3' key: 'f3' value: { type: 'file', linkNotFound: no } }, { id: 'b666' key: 'f3' value: { type: 'link' } }, { id: 'b777' key: 'f3' value: { type: 'link' } }, { id: 'f4' key: 'f4' value: { type: 'file', linkNotFound: yes } }, { id: 'b666' key: 'f4' value: { type: 'link' } }, { id: 'b777' key: 'f4' value: { type: 'link' } }, { id: 'b3' key: 'f5' value: { type: 'link' } }, { id: 'f5' key: 'f5' value: { type: 'file', linkNotFound: yes } }, { id: 'b8' key: 'f5' value: { type: 'link' } }, { id: 'b3' key: 'f6' value: { type: 'link' } }, { id: 'f6' key: 'f6' value: { type: 'file', linkNotFound: no } }, { id: 'b8' key: 'f6' value: { type: 'link' } }, { id: 'b4' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } },{ id: 'f7' key: 'f7' value: { type: 'file', linkNotFound: yes } }, { id: 'f8' key: 'f8' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'f9' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: no } }] res = [{ fileId: 'f1' found: yes }, { fileId: 'f4' found: yes }, { fileId: 'f5' found: yes }, { fileId: 'f7' found: no }, { fileId: 'f8' found: no }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing10: (test) -> files = [{ id: 'b666' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'b777' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'f1' key: 'f1' value: { type: 'file', linkNotFound: yes } }, { id: 'b666' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'b777' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'f2' key: 'f2' value: { type: 'file', linkNotFound: no } }, { id: 'f3' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: no } }, { id: 'b666' key: 'PI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'b777' key: 'PI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'f4' key: 'f4' value: { type: 'file', linkNotFound: yes } }, { id: 'b666' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'b777' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'b3' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'f5' key: 'f5' value: { type: 'file', linkNotFound: yes } }, { id: 'b8' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'b3' key: 'f6' value: { type: 'link' } }, { id: 'f6' key: 'f6' value: { type: 'file', linkNotFound: no } }, { id: 'b8' key: 'f6' value: { type: 'link' } }, { id: 'b4' key: 'f6' value: { type: 'link' } },{ id: 'f7' key: 'f7' value: { type: 'file', linkNotFound: yes } }, { id: 'f8' key: 'f8' value: { type: 'file', linkNotFound: no } }, { id: 'f9' key: 'f9' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'f9' value: { type: 'link' } }] res = [{ fileId: 'f1' found: yes }, { fileId: 'f4' found: yes }, { fileId: 'f5' found: yes }, { fileId: 'f7' found: no }, { fileId: 'f8' found: no }] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done() testGetFilesForProcessing11: (test) -> files = [{ id: 'b3' key: 'f6' value: { type: 'link' } }, { id: 'f6' key: 'PI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: no } }, { id: 'b8' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'f7' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: no } }, { id: 'b4' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'b4' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }, { id: 'f8' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: no } }, { id: 'f9' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'file', linkNotFound: no } }, { id: 'b3' key: 'fPI:KEY:<KEY>END_PI' value: { type: 'link' } }] res = [] test.deepEqual(res, @fileCleaner._getFilesForProcessing(files)) test.done()
[ { "context": "setCardSetId(CardSet.Coreshatter)\n\t\t\tcard.name = \"Hideatsu the Ebon Ox\"\n\t\t\tcard.setDescription(\"Trial: Summon 7 minions ", "end": 4312, "score": 0.9913462400436401, "start": 4292, "tag": "NAME", "value": "Hideatsu the Ebon Ox" }, { "context": "ard.factionId = Factions.Faction2\n\t\t\tcard.name = \"Bakezori\"\n\t\t\tcard.setDescription(\"Whenever this minion is ", "end": 6216, "score": 0.990871012210846, "start": 6208, "tag": "NAME", "value": "Bakezori" }, { "context": "d = Cards.Artifact.BackstabGloves\n\t\t\tcard.name = \"Horned Mask\"\n\t\t\tcard.setDescription(\"Your General gains +1 At", "end": 9083, "score": 0.997819721698761, "start": 9072, "tag": "NAME", "value": "Horned Mask" }, { "context": "ard.factionId = Factions.Faction2\n\t\t\tcard.name = \"Kaido Expert\"\n\t\t\tcard.setDescription(\"Backstab: (1).\\nWhenever", "end": 10377, "score": 0.9960298538208008, "start": 10365, "tag": "NAME", "value": "Kaido Expert" }, { "context": "ard.factionId = Factions.Faction2\n\t\t\tcard.name = \"Massacre Artist\"\n\t\t\tcard.setDescription(\"Backstab: (2).\\nAfter th", "end": 11692, "score": 0.999117374420166, "start": 11677, "tag": "NAME", "value": "Massacre Artist" }, { "context": "ard.factionId = Factions.Faction2\n\t\t\tcard.name = \"Orizuru\"\n\t\t\tcard.setDescription(\"Flying\")\n\t\t\tcard.atk = 3", "end": 13268, "score": 0.9959462285041809, "start": 13261, "tag": "NAME", "value": "Orizuru" }, { "context": "ard.factionId = Factions.Faction2\n\t\t\tcard.name = \"Xenkai Cannoneer\"\n\t\t\tcard.setDescription(\"Ranged\\nWhenever you sum", "end": 14438, "score": 0.9998639225959778, "start": 14422, "tag": "NAME", "value": "Xenkai Cannoneer" }, { "context": "ard.factionId = Factions.Faction2\n\t\t\tcard.name = \"Coalfist\"\n\t\t\tcard.setDescription(\"Intensify: Give a random", "end": 15795, "score": 0.9291378855705261, "start": 15787, "tag": "NAME", "value": "Coalfist" }, { "context": "ard.id = Cards.Spell.HollowVortex\n\t\t\tcard.name = \"Kensho Vortex\"\n\t\t\tcard.setDescription(\"Costs 1 less for each sp", "end": 17227, "score": 0.9992288947105408, "start": 17214, "tag": "NAME", "value": "Kensho Vortex" }, { "context": "EndTurn = 1\n\t\t\tcustomContextObject.appliedName = \"Kensho Unleashed\"\n\t\t\tcustomContextObject.appliedDescript", "end": 17631, "score": 0.8626748323440552, "start": 17625, "tag": "NAME", "value": "Kensho" }, { "context": "\t\tcard.id = Cards.Spell.PandaJail\n\t\t\tcard.name = \"Pandatentiary\"\n\t\t\tcard.setDescription(\"Surround the enemy Gener", "end": 18598, "score": 0.9983717799186707, "start": 18585, "tag": "NAME", "value": "Pandatentiary" }, { "context": " = Cards.Spell.GreaterPhoenixFire\n\t\t\tcard.name = \"Phoenix Barrage\"\n\t\t\tcard.setDescription(\"Deal 3 damage to anythin", "end": 19388, "score": 0.9929361939430237, "start": 19373, "tag": "NAME", "value": "Phoenix Barrage" }, { "context": ".id = Cards.Spell.BootyProjection\n\t\t\tcard.name = \"Second Self\"\n\t\t\tcard.setDescription(\"Put an EXACT copy of a f", "end": 20226, "score": 0.9636508226394653, "start": 20215, "tag": "NAME", "value": "Second Self" } ]
app/sdk/cards/factory/coreshatter/faction2.coffee
willroberts/duelyst
5
# do not add this file to a package # it is specifically parsed by the package generation script _ = require 'underscore' moment = require 'moment' Logger = require 'app/common/logger' CONFIG = require('app/common/config') RSX = require('app/data/resources') Card = require 'app/sdk/cards/card' Cards = require 'app/sdk/cards/cardsLookupComplete' CardType = require 'app/sdk/cards/cardType' Factions = require 'app/sdk/cards/factionsLookup' FactionFactory = require 'app/sdk/cards/factionFactory' Races = require 'app/sdk/cards/racesLookup' Rarity = require 'app/sdk/cards/rarityLookup' Unit = require 'app/sdk/entities/unit' CardSet = require 'app/sdk/cards/cardSetLookup' Artifact = require 'app/sdk/artifacts/artifact' SpellFilterType = require 'app/sdk/spells/spellFilterType' SpellDejaVu = require 'app/sdk/spells/spellDejaVu' SpellDamage = require 'app/sdk/spells/spellDamage' SpellSummonHighestCostMinion = require 'app/sdk/spells/spellSummonHighestCostMinion' SpellPandaJail = require 'app/sdk/spells/spellPandaJail' SpellCopyMinionToHand = require 'app/sdk/spells/spellCopyMinionToHand' SpellIntensifyDealDamage = require 'app/sdk/spells/spellIntensifyDealDamage' SpellDamageAndPutCardInHand = require 'app/sdk/spells/spellDamageAndPutCardInHand' SpellApplyPlayerModifiers = require 'app/sdk/spells/spellApplyPlayerModifiers' Modifier = require 'app/sdk/modifiers/modifier' ModifierRanged = require 'app/sdk/modifiers/modifierRanged' ModifierManaCostChange = require 'app/sdk/modifiers/modifierManaCostChange' ModifierMyMoveWatchAnyReasonDrawCard = require 'app/sdk/modifiers/modifierMyMoveWatchAnyReasonDrawCard' ModifierBackstab = require 'app/sdk/modifiers/modifierBackstab' ModifierBackstabWatchSummonBackstabMinion = require 'app/sdk/modifiers/modifierBackstabWatchSummonBackstabMinion' ModifierMyAttackWatchApplyModifiers = require 'app/sdk/modifiers/modifierMyAttackWatchApplyModifiers' ModifierBackstabWatchApplyPlayerModifiers = require 'app/sdk/modifiers/modifierBackstabWatchApplyPlayerModifiers' ModifierFlying = require 'app/sdk/modifiers/modifierFlying' ModifierSummonWatchApplyModifiersToRanged = require 'app/sdk/modifiers/modifierSummonWatchApplyModifiersToRanged' ModifierFirstBlood = require 'app/sdk/modifiers/modifierFirstBlood' ModifierStartsInHand = require 'app/sdk/modifiers/modifierStartsInHand' ModifierManaCostChange = require 'app/sdk/modifiers/modifierManaCostChange' ModifierSpellWatchAnywhereApplyModifiers = require 'app/sdk/modifiers/modifierSpellWatchAnywhereApplyModifiers' ModifierDamageBothGeneralsOnReplace = require 'app/sdk/modifiers/modifierDamageBothGeneralsOnReplace' ModifierIntensifyTempBuffNearbyMinion = require 'app/sdk/modifiers/modifierIntensifyTempBuffNearbyMinion' ModifierOnSummonFromHandApplyEmblems = require 'app/sdk/modifiers/modifierOnSummonFromHandApplyEmblems' ModifierManaCostChange = require 'app/sdk/modifiers/modifierManaCostChange' ModifierTokenCreator = require 'app/sdk/modifiers/modifierTokenCreator' ModifierFateSonghaiMinionQuest = require 'app/sdk/modifiers/modifierFateSonghaiMinionQuest' ModifierCannotBeReplaced = require 'app/sdk/modifiers/modifierCannotBeReplaced' ModifierIntensify = require 'app/sdk/modifiers/modifierIntensify' ModifierCounterIntensify = require 'app/sdk/modifiers/modifierCounterIntensify' ModifierCannotBeRemovedFromHand = require 'app/sdk/modifiers/modifierCannotBeRemovedFromHand' PlayerModifierTeamAlwaysBackstabbed = require 'app/sdk/playerModifiers/playerModifierTeamAlwaysBackstabbed' PlayerModifierEmblemSummonWatchSonghaiMeltdownQuest = require 'app/sdk/playerModifiers/playerModifierEmblemSummonWatchSonghaiMeltdownQuest' PlayerModifierSpellWatchHollowVortex = require 'app/sdk/playerModifiers/playerModifierSpellWatchHollowVortex' i18next = require 'i18next' if i18next.t() is undefined i18next.t = (text) -> return text class CardFactory_CoreshatterSet_Faction2 ###* * Returns a card that matches the identifier. * @param {Number|String} identifier * @param {GameSession} gameSession * @returns {Card} ### @cardForIdentifier: (identifier,gameSession) -> card = null if (identifier == Cards.Faction2.DarkHeart) card = new Unit(gameSession) card.factionId = Factions.Faction2 card.setCardSetId(CardSet.Coreshatter) card.name = "Hideatsu the Ebon Ox" card.setDescription("Trial: Summon 7 minions from your action bar with different costs.\nDestiny: Summon friendly minions to deal their cost as damage to an enemy.") card.atk = 5 card.maxHP = 5 card.manaCost = 0 card.rarityId = Rarity.Mythron emblemContextObject = PlayerModifierEmblemSummonWatchSonghaiMeltdownQuest.createContextObject() emblemContextObject.appliedName = "Storm of the Ebon Ox" emblemContextObject.appliedDescription = "Whenever you summon a minion, deal damage equal to its cost to an enemy." card.setInherentModifiersContextObjects([ ModifierStartsInHand.createContextObject(), ModifierCannotBeReplaced.createContextObject(), ModifierOnSummonFromHandApplyEmblems.createContextObject([emblemContextObject], true, false), ModifierFateSonghaiMinionQuest.createContextObject(7), ModifierCannotBeRemovedFromHand.createContextObject() ]) card.setFXResource(["FX.Cards.Neutral.DarkHeart"]) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_chakriavatar_attack_swing.audio receiveDamage : RSX.sfx_f2_chakriavatar_hit.audio attackDamage : RSX.sfx_f2_chakriavatar_attack_impact.audio death : RSX.sfx_f2_chakriavatar_death.audio ) card.setBaseAnimResource( breathing : RSX.f2HeartOfTheSonghaiBreathing.name idle : RSX.f2HeartOfTheSonghaiIdle.name walk : RSX.f2HeartOfTheSonghaiRun.name attack : RSX.f2HeartOfTheSonghaiAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f2HeartOfTheSonghaiHit.name death : RSX.f2HeartOfTheSonghaiDeath.name ) if (identifier == Cards.Faction2.MoveMan) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "Bakezori" card.setDescription("Whenever this minion is moved for any reason, draw a card.") card.atk = 2 card.maxHP = 6 card.manaCost = 4 card.rarityId = Rarity.Epic card.setInherentModifiersContextObjects([ModifierMyMoveWatchAnyReasonDrawCard.createContextObject(1)]) card.setFXResource(["FX.Cards.Neutral.SunSeer"]) card.setBoundingBoxWidth(45) card.setBoundingBoxHeight(80) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_2.audio walk : RSX.sfx_unit_run_magical_4.audio attack : RSX.sfx_neutral_sunseer_attack_swing.audio receiveDamage : RSX.sfx_neutral_sunseer_hit.audio attackDamage : RSX.sfx_neutral_sunseer_attack_impact.audio death : RSX.sfx_neutral_sunseer_death.audio ) card.setBaseAnimResource( breathing : RSX.f2PaperDropperBreathing.name idle : RSX.f2PaperDropperIdle.name walk : RSX.f2PaperDropperRun.name attack : RSX.f2PaperDropperAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.f2PaperDropperHit.name death : RSX.f2PaperDropperDeath.name ) if (identifier == Cards.Spell.DejaVu) card = new SpellDejaVu(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.id = Cards.Spell.DejaVu card.name = "Meditate" card.setDescription("Shuffle five copies of the spell you cast most recently into your deck (excluding Meditate).") card.rarityId = Rarity.Rare card.manaCost = 0 card.spellFilterType = SpellFilterType.NeutralIndirect card.setFXResource(["FX.Cards.Spell.Meditate"]) card.setBaseSoundResource( apply : RSX.sfx_spell_fountainofyouth.audio ) card.setBaseAnimResource( idle : RSX.iconDejaVuIdle.name active : RSX.iconDejaVuActive.name ) if (identifier == Cards.Spell.Kindle) card = new SpellIntensifyDealDamage(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.id = Cards.Spell.Kindle card.name = "Knucklestorm" card.setDescription("Intensify: Deal 1 damage to an enemy.") card.rarityId = Rarity.Common card.manaCost = 1 card.spellFilterType = SpellFilterType.EnemyDirect card.canTargetGeneral = true card.damageAmount = 1 card.addKeywordClassToInclude(ModifierIntensify) card.setInherentModifiersContextObjects([ModifierCounterIntensify.createContextObject()]) card.setFXResource(["FX.Cards.Spell.Knucklestorm"]) card.setBaseSoundResource( apply : RSX.sfx_neutral_bluetipscorpion_attack_impact.audio ) card.setBaseAnimResource( idle : RSX.iconKindleIdle.name active : RSX.iconKindleActive.name ) if (identifier == Cards.Artifact.BackstabGloves) card = new Artifact(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.id = Cards.Artifact.BackstabGloves card.name = "Horned Mask" card.setDescription("Your General gains +1 Attack.\nAfter a friendly minion with Backstab attacks, it gains +1/+1.") card.manaCost = 1 card.rarityId = Rarity.Epic card.durability = 3 attackBuffContextObject = Modifier.createContextObjectWithAttributeBuffs(1,1) attackBuffContextObject.appliedName = "Growing Charge" auraContextObject = ModifierMyAttackWatchApplyModifiers.createContextObject([attackBuffContextObject]) auraContextObject.appliedName = "Poised to Strike" auraContextObject.appliedDescription = "After this minion attacks, it gains +1/+1." card.setTargetModifiersContextObjects([ Modifier.createContextObjectWithAttributeBuffs(1,0), Modifier.createContextObjectWithAuraForAllAllies([auraContextObject], null, null, [ModifierBackstab.type]) ]) card.addKeywordClassToInclude(ModifierBackstab) card.setFXResource(["FX.Cards.Artifact.EnergyAmulet"]) card.setBaseAnimResource( idle: RSX.iconGorehornMaskIdle.name active: RSX.iconGorehornMaskActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.Faction2.ShadowSummoner) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "Kaido Expert" card.setDescription("Backstab: (1).\nWhenever this minion backstabs, summon a minion with Backstab that costs 2 or less from your deck nearby.") card.atk = 2 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare card.setInherentModifiersContextObjects([ModifierBackstab.createContextObject(1), ModifierBackstabWatchSummonBackstabMinion.createContextObject(2)]) card.setFXResource(["FX.Cards.Neutral.VineEntangler"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_komodocharger_attack_swing.audio receiveDamage : RSX.sfx_f6_ancientgrove_hit.audio attackDamage : RSX.sfx_f6_ancientgrove_attack_impact.audio death : RSX.sfx_f6_ancientgrove_death.audio ) card.setBaseAnimResource( breathing : RSX.f2ShadowSummonerBreathing.name idle : RSX.f2ShadowSummonerIdle.name walk : RSX.f2ShadowSummonerRun.name attack : RSX.f2ShadowSummonerAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.f2ShadowSummonerHit.name death : RSX.f2ShadowSummonerDeath.name ) if (identifier == Cards.Faction2.Backbreaker) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "Massacre Artist" card.setDescription("Backstab: (2).\nAfter this minion attacks and backstabs, all attacks are backstabs this turn.") card.atk = 2 card.maxHP = 5 card.manaCost = 4 card.rarityId = Rarity.Legendary teamAlwaysBackstabbedModifier = PlayerModifierTeamAlwaysBackstabbed.createContextObject("Massacred", "Backstabbed from any angle!") teamAlwaysBackstabbedModifier.durationEndTurn = 1 card.setInherentModifiersContextObjects([ ModifierBackstab.createContextObject(2), ModifierBackstabWatchApplyPlayerModifiers.createContextObjectToTargetEnemyPlayer([teamAlwaysBackstabbedModifier], false) ]) card.setFXResource(["FX.Cards.Neutral.BloodshardGolem"]) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_redsynja_attack_swing.audio receiveDamage : RSX.sfx_f2_kaidoassassin_hit.audio attackDamage : RSX.sfx_neutral_syvrel_attack_impact.audio death : RSX.sfx_neutral_syvrel_death.audio ) card.setBaseAnimResource( breathing : RSX.f2SupekutaBreathing.name idle : RSX.f2SupekutaIdle.name walk : RSX.f2SupekutaRun.name attack : RSX.f2SupekutaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.f2SupekutaHit.name death : RSX.f2SupekutaDeath.name ) if (identifier == Cards.Faction2.CraneWalker) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "Orizuru" card.setDescription("Flying") card.atk = 3 card.maxHP = 4 card.manaCost = 3 card.rarityId = Rarity.Common card.setInherentModifiersContextObjects([ModifierFlying.createContextObject()]) card.setFXResource(["FX.Cards.Neutral.PutridMindflayer"]) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_zurael_death.audio attack : RSX.sfx_neutral_zurael_attack_swing.audio receiveDamage : RSX.sfx_neutral_zurael_hit.audio attackDamage : RSX.sfx_neutral_zurael_attack_impact.audio death : RSX.sfx_neutral_zurael_death.audio ) card.setBaseAnimResource( breathing : RSX.f2OrizuruBreathing.name idle : RSX.f2OrizuruIdle.name walk : RSX.f2OrizuruRun.name attack : RSX.f2OrizuruAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f2OrizuruHit.name death : RSX.f2OrizuruDeath.name ) if (identifier == Cards.Faction2.Flareslinger) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "Xenkai Cannoneer" card.setDescription("Ranged\nWhenever you summon a minion with Ranged, that minion gains Rush.") card.atk = 4 card.maxHP = 4 card.manaCost = 5 card.rarityId = Rarity.Legendary card.setInherentModifiersContextObjects([ModifierRanged.createContextObject(), ModifierSummonWatchApplyModifiersToRanged.createContextObject([ModifierFirstBlood.createContextObject()])]) card.addKeywordClassToInclude(ModifierFirstBlood) card.setFXResource(["FX.Cards.Faction2.FlareSlinger"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_1.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_firespitter_attack_swing.audio receiveDamage : RSX.sfx_neutral_firespitter_hit.audio attackDamage : RSX.sfx_neutral_firespitter_attack_impact.audio death : RSX.sfx_neutral_firespitter_death.audio ) card.setBaseAnimResource( breathing : RSX.f2FlareSlingerBreathing.name idle : RSX.f2FlareSlingerIdle.name walk : RSX.f2FlareSlingerRun.name attack : RSX.f2FlareSlingerAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f2FlareSlingerHit.name death : RSX.f2FlareSlingerDeath.name ) if (identifier == Cards.Faction2.PandaPuncher) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "Coalfist" card.setDescription("Intensify: Give a random nearby friendly minion +2 Attack this turn.") card.atk = 5 card.maxHP = 4 card.manaCost = 4 card.rarityId = Rarity.Common card.setInherentModifiersContextObjects([ ModifierIntensifyTempBuffNearbyMinion.createContextObject(2, 0, "Ignition Fist"), ModifierCounterIntensify.createContextObject() ]) card.setFXResource(["FX.Cards.Neutral.DeathBlighter"]) card.setBoundingBoxWidth(105) card.setBoundingBoxHeight(75) card.setBaseSoundResource( apply : RSX.sfx_neutral_chaoselemental_hit.audio walk : RSX.sfx_neutral_chaoselemental_death.audio attack : RSX.sfx_f4_blacksolus_attack_swing.audio receiveDamage : RSX.sfx_f4_blacksolus_hit.audio attackDamage : RSX.sfx_f4_blacksolus_attack_impact.audio death : RSX.sfx_f4_blacksolus_death.audio ) card.setBaseAnimResource( breathing : RSX.f2PandaPuncherBreathing.name idle : RSX.f2PandaPuncherIdle.name walk : RSX.f2PandaPuncherRun.name attack : RSX.f2PandaPuncherAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.f2PandaPuncherHit.name death : RSX.f2PandaPuncherDeath.name ) if (identifier == Cards.Spell.HollowVortex) card = new SpellApplyPlayerModifiers(gameSession) card.factionId = Factions.Faction2 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.HollowVortex card.name = "Kensho Vortex" card.setDescription("Costs 1 less for each spell you cast this game. Whenever you cast a spell this turn, summon a minion that costs up to 2 more nearby your General.") card.manaCost = 11 card.rarityId = Rarity.Legendary customContextObject = PlayerModifierSpellWatchHollowVortex.createContextObject(2) customContextObject.durationEndTurn = 1 customContextObject.appliedName = "Kensho Unleashed" customContextObject.appliedDescription = "Casting spells summons minions." card.applyToOwnGeneral = true card.setTargetModifiersContextObjects([customContextObject]) manaChangeContextObject = ModifierManaCostChange.createContextObject(-1) manaSpellWatch = ModifierSpellWatchAnywhereApplyModifiers.createContextObject([manaChangeContextObject]) card.setInherentModifiersContextObjects([manaSpellWatch]) card.spellFilterType = SpellFilterType.None card.setFXResource(["FX.Cards.Spell.KenshoVortex"]) card.setBaseSoundResource( apply : RSX.sfx_spell_scionsfirstwish.audio ) card.setBaseAnimResource( idle : RSX.iconHollowVortexIdle.name active : RSX.iconHollowVortexActive.name ) if (identifier == Cards.Spell.PandaJail) card = new SpellPandaJail(gameSession) card.factionId = Factions.Faction2 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.PandaJail card.name = "Pandatentiary" card.setDescription("Surround the enemy General with friendly Panddo that disappear at the start of your next turn.") card.manaCost = 3 card.rarityId = Rarity.Epic card.spellFilterType = SpellFilterType.None card.addKeywordClassToInclude(ModifierTokenCreator) card.setFXResource(["FX.Cards.Spell.Pandatentiary"]) card.setBaseSoundResource( apply : RSX.sfx_spell_onyxbearseal.audio ) card.setBaseAnimResource( idle : RSX.iconPandaJailIdle.name active : RSX.iconPandaJailActive.name ) if (identifier == Cards.Spell.GreaterPhoenixFire) card = new SpellDamageAndPutCardInHand(gameSession) card.factionId = Factions.Faction2 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.GreaterPhoenixFire card.name = "Phoenix Barrage" card.setDescription("Deal 3 damage to anything.\nPut a Phoenix Fire into your action bar.") card.manaCost = 5 card.rarityId = Rarity.Common card.spellFilterType = SpellFilterType.NeutralDirect card.damageAmount = 3 card.cardDataOrIndexToPutInHand = {id: Cards.Spell.PhoenixFire} card.canTargetGeneral = true card.setFXResource(["FX.Cards.Spell.PhoenixBarrage"]) card.setBaseSoundResource( apply : RSX.sfx_spell_phoenixfire.audio ) card.setBaseAnimResource( idle : RSX.iconPhoenixBarrageIdle.name active : RSX.iconPhoenixBarrageActive.name ) if (identifier == Cards.Spell.BootyProjection) card = new SpellCopyMinionToHand(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.id = Cards.Spell.BootyProjection card.name = "Second Self" card.setDescription("Put an EXACT copy of a friendly minion into your action bar.") card.rarityId = Rarity.Rare card.manaCost = 2 card.spellFilterType = SpellFilterType.AllyDirect card.canTargetGeneral = false card.setFXResource(["FX.Cards.Spell.SecondSelf"]) card.setBaseSoundResource( apply : RSX.sfx_spell_drainmorale.audio ) card.setBaseAnimResource( idle : RSX.iconProjectionIdle.name active : RSX.iconProjectionActive.name ) return card module.exports = CardFactory_CoreshatterSet_Faction2
15760
# do not add this file to a package # it is specifically parsed by the package generation script _ = require 'underscore' moment = require 'moment' Logger = require 'app/common/logger' CONFIG = require('app/common/config') RSX = require('app/data/resources') Card = require 'app/sdk/cards/card' Cards = require 'app/sdk/cards/cardsLookupComplete' CardType = require 'app/sdk/cards/cardType' Factions = require 'app/sdk/cards/factionsLookup' FactionFactory = require 'app/sdk/cards/factionFactory' Races = require 'app/sdk/cards/racesLookup' Rarity = require 'app/sdk/cards/rarityLookup' Unit = require 'app/sdk/entities/unit' CardSet = require 'app/sdk/cards/cardSetLookup' Artifact = require 'app/sdk/artifacts/artifact' SpellFilterType = require 'app/sdk/spells/spellFilterType' SpellDejaVu = require 'app/sdk/spells/spellDejaVu' SpellDamage = require 'app/sdk/spells/spellDamage' SpellSummonHighestCostMinion = require 'app/sdk/spells/spellSummonHighestCostMinion' SpellPandaJail = require 'app/sdk/spells/spellPandaJail' SpellCopyMinionToHand = require 'app/sdk/spells/spellCopyMinionToHand' SpellIntensifyDealDamage = require 'app/sdk/spells/spellIntensifyDealDamage' SpellDamageAndPutCardInHand = require 'app/sdk/spells/spellDamageAndPutCardInHand' SpellApplyPlayerModifiers = require 'app/sdk/spells/spellApplyPlayerModifiers' Modifier = require 'app/sdk/modifiers/modifier' ModifierRanged = require 'app/sdk/modifiers/modifierRanged' ModifierManaCostChange = require 'app/sdk/modifiers/modifierManaCostChange' ModifierMyMoveWatchAnyReasonDrawCard = require 'app/sdk/modifiers/modifierMyMoveWatchAnyReasonDrawCard' ModifierBackstab = require 'app/sdk/modifiers/modifierBackstab' ModifierBackstabWatchSummonBackstabMinion = require 'app/sdk/modifiers/modifierBackstabWatchSummonBackstabMinion' ModifierMyAttackWatchApplyModifiers = require 'app/sdk/modifiers/modifierMyAttackWatchApplyModifiers' ModifierBackstabWatchApplyPlayerModifiers = require 'app/sdk/modifiers/modifierBackstabWatchApplyPlayerModifiers' ModifierFlying = require 'app/sdk/modifiers/modifierFlying' ModifierSummonWatchApplyModifiersToRanged = require 'app/sdk/modifiers/modifierSummonWatchApplyModifiersToRanged' ModifierFirstBlood = require 'app/sdk/modifiers/modifierFirstBlood' ModifierStartsInHand = require 'app/sdk/modifiers/modifierStartsInHand' ModifierManaCostChange = require 'app/sdk/modifiers/modifierManaCostChange' ModifierSpellWatchAnywhereApplyModifiers = require 'app/sdk/modifiers/modifierSpellWatchAnywhereApplyModifiers' ModifierDamageBothGeneralsOnReplace = require 'app/sdk/modifiers/modifierDamageBothGeneralsOnReplace' ModifierIntensifyTempBuffNearbyMinion = require 'app/sdk/modifiers/modifierIntensifyTempBuffNearbyMinion' ModifierOnSummonFromHandApplyEmblems = require 'app/sdk/modifiers/modifierOnSummonFromHandApplyEmblems' ModifierManaCostChange = require 'app/sdk/modifiers/modifierManaCostChange' ModifierTokenCreator = require 'app/sdk/modifiers/modifierTokenCreator' ModifierFateSonghaiMinionQuest = require 'app/sdk/modifiers/modifierFateSonghaiMinionQuest' ModifierCannotBeReplaced = require 'app/sdk/modifiers/modifierCannotBeReplaced' ModifierIntensify = require 'app/sdk/modifiers/modifierIntensify' ModifierCounterIntensify = require 'app/sdk/modifiers/modifierCounterIntensify' ModifierCannotBeRemovedFromHand = require 'app/sdk/modifiers/modifierCannotBeRemovedFromHand' PlayerModifierTeamAlwaysBackstabbed = require 'app/sdk/playerModifiers/playerModifierTeamAlwaysBackstabbed' PlayerModifierEmblemSummonWatchSonghaiMeltdownQuest = require 'app/sdk/playerModifiers/playerModifierEmblemSummonWatchSonghaiMeltdownQuest' PlayerModifierSpellWatchHollowVortex = require 'app/sdk/playerModifiers/playerModifierSpellWatchHollowVortex' i18next = require 'i18next' if i18next.t() is undefined i18next.t = (text) -> return text class CardFactory_CoreshatterSet_Faction2 ###* * Returns a card that matches the identifier. * @param {Number|String} identifier * @param {GameSession} gameSession * @returns {Card} ### @cardForIdentifier: (identifier,gameSession) -> card = null if (identifier == Cards.Faction2.DarkHeart) card = new Unit(gameSession) card.factionId = Factions.Faction2 card.setCardSetId(CardSet.Coreshatter) card.name = "<NAME>" card.setDescription("Trial: Summon 7 minions from your action bar with different costs.\nDestiny: Summon friendly minions to deal their cost as damage to an enemy.") card.atk = 5 card.maxHP = 5 card.manaCost = 0 card.rarityId = Rarity.Mythron emblemContextObject = PlayerModifierEmblemSummonWatchSonghaiMeltdownQuest.createContextObject() emblemContextObject.appliedName = "Storm of the Ebon Ox" emblemContextObject.appliedDescription = "Whenever you summon a minion, deal damage equal to its cost to an enemy." card.setInherentModifiersContextObjects([ ModifierStartsInHand.createContextObject(), ModifierCannotBeReplaced.createContextObject(), ModifierOnSummonFromHandApplyEmblems.createContextObject([emblemContextObject], true, false), ModifierFateSonghaiMinionQuest.createContextObject(7), ModifierCannotBeRemovedFromHand.createContextObject() ]) card.setFXResource(["FX.Cards.Neutral.DarkHeart"]) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_chakriavatar_attack_swing.audio receiveDamage : RSX.sfx_f2_chakriavatar_hit.audio attackDamage : RSX.sfx_f2_chakriavatar_attack_impact.audio death : RSX.sfx_f2_chakriavatar_death.audio ) card.setBaseAnimResource( breathing : RSX.f2HeartOfTheSonghaiBreathing.name idle : RSX.f2HeartOfTheSonghaiIdle.name walk : RSX.f2HeartOfTheSonghaiRun.name attack : RSX.f2HeartOfTheSonghaiAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f2HeartOfTheSonghaiHit.name death : RSX.f2HeartOfTheSonghaiDeath.name ) if (identifier == Cards.Faction2.MoveMan) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "<NAME>" card.setDescription("Whenever this minion is moved for any reason, draw a card.") card.atk = 2 card.maxHP = 6 card.manaCost = 4 card.rarityId = Rarity.Epic card.setInherentModifiersContextObjects([ModifierMyMoveWatchAnyReasonDrawCard.createContextObject(1)]) card.setFXResource(["FX.Cards.Neutral.SunSeer"]) card.setBoundingBoxWidth(45) card.setBoundingBoxHeight(80) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_2.audio walk : RSX.sfx_unit_run_magical_4.audio attack : RSX.sfx_neutral_sunseer_attack_swing.audio receiveDamage : RSX.sfx_neutral_sunseer_hit.audio attackDamage : RSX.sfx_neutral_sunseer_attack_impact.audio death : RSX.sfx_neutral_sunseer_death.audio ) card.setBaseAnimResource( breathing : RSX.f2PaperDropperBreathing.name idle : RSX.f2PaperDropperIdle.name walk : RSX.f2PaperDropperRun.name attack : RSX.f2PaperDropperAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.f2PaperDropperHit.name death : RSX.f2PaperDropperDeath.name ) if (identifier == Cards.Spell.DejaVu) card = new SpellDejaVu(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.id = Cards.Spell.DejaVu card.name = "Meditate" card.setDescription("Shuffle five copies of the spell you cast most recently into your deck (excluding Meditate).") card.rarityId = Rarity.Rare card.manaCost = 0 card.spellFilterType = SpellFilterType.NeutralIndirect card.setFXResource(["FX.Cards.Spell.Meditate"]) card.setBaseSoundResource( apply : RSX.sfx_spell_fountainofyouth.audio ) card.setBaseAnimResource( idle : RSX.iconDejaVuIdle.name active : RSX.iconDejaVuActive.name ) if (identifier == Cards.Spell.Kindle) card = new SpellIntensifyDealDamage(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.id = Cards.Spell.Kindle card.name = "Knucklestorm" card.setDescription("Intensify: Deal 1 damage to an enemy.") card.rarityId = Rarity.Common card.manaCost = 1 card.spellFilterType = SpellFilterType.EnemyDirect card.canTargetGeneral = true card.damageAmount = 1 card.addKeywordClassToInclude(ModifierIntensify) card.setInherentModifiersContextObjects([ModifierCounterIntensify.createContextObject()]) card.setFXResource(["FX.Cards.Spell.Knucklestorm"]) card.setBaseSoundResource( apply : RSX.sfx_neutral_bluetipscorpion_attack_impact.audio ) card.setBaseAnimResource( idle : RSX.iconKindleIdle.name active : RSX.iconKindleActive.name ) if (identifier == Cards.Artifact.BackstabGloves) card = new Artifact(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.id = Cards.Artifact.BackstabGloves card.name = "<NAME>" card.setDescription("Your General gains +1 Attack.\nAfter a friendly minion with Backstab attacks, it gains +1/+1.") card.manaCost = 1 card.rarityId = Rarity.Epic card.durability = 3 attackBuffContextObject = Modifier.createContextObjectWithAttributeBuffs(1,1) attackBuffContextObject.appliedName = "Growing Charge" auraContextObject = ModifierMyAttackWatchApplyModifiers.createContextObject([attackBuffContextObject]) auraContextObject.appliedName = "Poised to Strike" auraContextObject.appliedDescription = "After this minion attacks, it gains +1/+1." card.setTargetModifiersContextObjects([ Modifier.createContextObjectWithAttributeBuffs(1,0), Modifier.createContextObjectWithAuraForAllAllies([auraContextObject], null, null, [ModifierBackstab.type]) ]) card.addKeywordClassToInclude(ModifierBackstab) card.setFXResource(["FX.Cards.Artifact.EnergyAmulet"]) card.setBaseAnimResource( idle: RSX.iconGorehornMaskIdle.name active: RSX.iconGorehornMaskActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.Faction2.ShadowSummoner) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "<NAME>" card.setDescription("Backstab: (1).\nWhenever this minion backstabs, summon a minion with Backstab that costs 2 or less from your deck nearby.") card.atk = 2 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare card.setInherentModifiersContextObjects([ModifierBackstab.createContextObject(1), ModifierBackstabWatchSummonBackstabMinion.createContextObject(2)]) card.setFXResource(["FX.Cards.Neutral.VineEntangler"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_komodocharger_attack_swing.audio receiveDamage : RSX.sfx_f6_ancientgrove_hit.audio attackDamage : RSX.sfx_f6_ancientgrove_attack_impact.audio death : RSX.sfx_f6_ancientgrove_death.audio ) card.setBaseAnimResource( breathing : RSX.f2ShadowSummonerBreathing.name idle : RSX.f2ShadowSummonerIdle.name walk : RSX.f2ShadowSummonerRun.name attack : RSX.f2ShadowSummonerAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.f2ShadowSummonerHit.name death : RSX.f2ShadowSummonerDeath.name ) if (identifier == Cards.Faction2.Backbreaker) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "<NAME>" card.setDescription("Backstab: (2).\nAfter this minion attacks and backstabs, all attacks are backstabs this turn.") card.atk = 2 card.maxHP = 5 card.manaCost = 4 card.rarityId = Rarity.Legendary teamAlwaysBackstabbedModifier = PlayerModifierTeamAlwaysBackstabbed.createContextObject("Massacred", "Backstabbed from any angle!") teamAlwaysBackstabbedModifier.durationEndTurn = 1 card.setInherentModifiersContextObjects([ ModifierBackstab.createContextObject(2), ModifierBackstabWatchApplyPlayerModifiers.createContextObjectToTargetEnemyPlayer([teamAlwaysBackstabbedModifier], false) ]) card.setFXResource(["FX.Cards.Neutral.BloodshardGolem"]) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_redsynja_attack_swing.audio receiveDamage : RSX.sfx_f2_kaidoassassin_hit.audio attackDamage : RSX.sfx_neutral_syvrel_attack_impact.audio death : RSX.sfx_neutral_syvrel_death.audio ) card.setBaseAnimResource( breathing : RSX.f2SupekutaBreathing.name idle : RSX.f2SupekutaIdle.name walk : RSX.f2SupekutaRun.name attack : RSX.f2SupekutaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.f2SupekutaHit.name death : RSX.f2SupekutaDeath.name ) if (identifier == Cards.Faction2.CraneWalker) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "<NAME>" card.setDescription("Flying") card.atk = 3 card.maxHP = 4 card.manaCost = 3 card.rarityId = Rarity.Common card.setInherentModifiersContextObjects([ModifierFlying.createContextObject()]) card.setFXResource(["FX.Cards.Neutral.PutridMindflayer"]) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_zurael_death.audio attack : RSX.sfx_neutral_zurael_attack_swing.audio receiveDamage : RSX.sfx_neutral_zurael_hit.audio attackDamage : RSX.sfx_neutral_zurael_attack_impact.audio death : RSX.sfx_neutral_zurael_death.audio ) card.setBaseAnimResource( breathing : RSX.f2OrizuruBreathing.name idle : RSX.f2OrizuruIdle.name walk : RSX.f2OrizuruRun.name attack : RSX.f2OrizuruAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f2OrizuruHit.name death : RSX.f2OrizuruDeath.name ) if (identifier == Cards.Faction2.Flareslinger) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "<NAME>" card.setDescription("Ranged\nWhenever you summon a minion with Ranged, that minion gains Rush.") card.atk = 4 card.maxHP = 4 card.manaCost = 5 card.rarityId = Rarity.Legendary card.setInherentModifiersContextObjects([ModifierRanged.createContextObject(), ModifierSummonWatchApplyModifiersToRanged.createContextObject([ModifierFirstBlood.createContextObject()])]) card.addKeywordClassToInclude(ModifierFirstBlood) card.setFXResource(["FX.Cards.Faction2.FlareSlinger"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_1.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_firespitter_attack_swing.audio receiveDamage : RSX.sfx_neutral_firespitter_hit.audio attackDamage : RSX.sfx_neutral_firespitter_attack_impact.audio death : RSX.sfx_neutral_firespitter_death.audio ) card.setBaseAnimResource( breathing : RSX.f2FlareSlingerBreathing.name idle : RSX.f2FlareSlingerIdle.name walk : RSX.f2FlareSlingerRun.name attack : RSX.f2FlareSlingerAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f2FlareSlingerHit.name death : RSX.f2FlareSlingerDeath.name ) if (identifier == Cards.Faction2.PandaPuncher) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "<NAME>" card.setDescription("Intensify: Give a random nearby friendly minion +2 Attack this turn.") card.atk = 5 card.maxHP = 4 card.manaCost = 4 card.rarityId = Rarity.Common card.setInherentModifiersContextObjects([ ModifierIntensifyTempBuffNearbyMinion.createContextObject(2, 0, "Ignition Fist"), ModifierCounterIntensify.createContextObject() ]) card.setFXResource(["FX.Cards.Neutral.DeathBlighter"]) card.setBoundingBoxWidth(105) card.setBoundingBoxHeight(75) card.setBaseSoundResource( apply : RSX.sfx_neutral_chaoselemental_hit.audio walk : RSX.sfx_neutral_chaoselemental_death.audio attack : RSX.sfx_f4_blacksolus_attack_swing.audio receiveDamage : RSX.sfx_f4_blacksolus_hit.audio attackDamage : RSX.sfx_f4_blacksolus_attack_impact.audio death : RSX.sfx_f4_blacksolus_death.audio ) card.setBaseAnimResource( breathing : RSX.f2PandaPuncherBreathing.name idle : RSX.f2PandaPuncherIdle.name walk : RSX.f2PandaPuncherRun.name attack : RSX.f2PandaPuncherAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.f2PandaPuncherHit.name death : RSX.f2PandaPuncherDeath.name ) if (identifier == Cards.Spell.HollowVortex) card = new SpellApplyPlayerModifiers(gameSession) card.factionId = Factions.Faction2 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.HollowVortex card.name = "<NAME>" card.setDescription("Costs 1 less for each spell you cast this game. Whenever you cast a spell this turn, summon a minion that costs up to 2 more nearby your General.") card.manaCost = 11 card.rarityId = Rarity.Legendary customContextObject = PlayerModifierSpellWatchHollowVortex.createContextObject(2) customContextObject.durationEndTurn = 1 customContextObject.appliedName = "<NAME> Unleashed" customContextObject.appliedDescription = "Casting spells summons minions." card.applyToOwnGeneral = true card.setTargetModifiersContextObjects([customContextObject]) manaChangeContextObject = ModifierManaCostChange.createContextObject(-1) manaSpellWatch = ModifierSpellWatchAnywhereApplyModifiers.createContextObject([manaChangeContextObject]) card.setInherentModifiersContextObjects([manaSpellWatch]) card.spellFilterType = SpellFilterType.None card.setFXResource(["FX.Cards.Spell.KenshoVortex"]) card.setBaseSoundResource( apply : RSX.sfx_spell_scionsfirstwish.audio ) card.setBaseAnimResource( idle : RSX.iconHollowVortexIdle.name active : RSX.iconHollowVortexActive.name ) if (identifier == Cards.Spell.PandaJail) card = new SpellPandaJail(gameSession) card.factionId = Factions.Faction2 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.PandaJail card.name = "<NAME>" card.setDescription("Surround the enemy General with friendly Panddo that disappear at the start of your next turn.") card.manaCost = 3 card.rarityId = Rarity.Epic card.spellFilterType = SpellFilterType.None card.addKeywordClassToInclude(ModifierTokenCreator) card.setFXResource(["FX.Cards.Spell.Pandatentiary"]) card.setBaseSoundResource( apply : RSX.sfx_spell_onyxbearseal.audio ) card.setBaseAnimResource( idle : RSX.iconPandaJailIdle.name active : RSX.iconPandaJailActive.name ) if (identifier == Cards.Spell.GreaterPhoenixFire) card = new SpellDamageAndPutCardInHand(gameSession) card.factionId = Factions.Faction2 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.GreaterPhoenixFire card.name = "<NAME>" card.setDescription("Deal 3 damage to anything.\nPut a Phoenix Fire into your action bar.") card.manaCost = 5 card.rarityId = Rarity.Common card.spellFilterType = SpellFilterType.NeutralDirect card.damageAmount = 3 card.cardDataOrIndexToPutInHand = {id: Cards.Spell.PhoenixFire} card.canTargetGeneral = true card.setFXResource(["FX.Cards.Spell.PhoenixBarrage"]) card.setBaseSoundResource( apply : RSX.sfx_spell_phoenixfire.audio ) card.setBaseAnimResource( idle : RSX.iconPhoenixBarrageIdle.name active : RSX.iconPhoenixBarrageActive.name ) if (identifier == Cards.Spell.BootyProjection) card = new SpellCopyMinionToHand(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.id = Cards.Spell.BootyProjection card.name = "<NAME>" card.setDescription("Put an EXACT copy of a friendly minion into your action bar.") card.rarityId = Rarity.Rare card.manaCost = 2 card.spellFilterType = SpellFilterType.AllyDirect card.canTargetGeneral = false card.setFXResource(["FX.Cards.Spell.SecondSelf"]) card.setBaseSoundResource( apply : RSX.sfx_spell_drainmorale.audio ) card.setBaseAnimResource( idle : RSX.iconProjectionIdle.name active : RSX.iconProjectionActive.name ) return card module.exports = CardFactory_CoreshatterSet_Faction2
true
# do not add this file to a package # it is specifically parsed by the package generation script _ = require 'underscore' moment = require 'moment' Logger = require 'app/common/logger' CONFIG = require('app/common/config') RSX = require('app/data/resources') Card = require 'app/sdk/cards/card' Cards = require 'app/sdk/cards/cardsLookupComplete' CardType = require 'app/sdk/cards/cardType' Factions = require 'app/sdk/cards/factionsLookup' FactionFactory = require 'app/sdk/cards/factionFactory' Races = require 'app/sdk/cards/racesLookup' Rarity = require 'app/sdk/cards/rarityLookup' Unit = require 'app/sdk/entities/unit' CardSet = require 'app/sdk/cards/cardSetLookup' Artifact = require 'app/sdk/artifacts/artifact' SpellFilterType = require 'app/sdk/spells/spellFilterType' SpellDejaVu = require 'app/sdk/spells/spellDejaVu' SpellDamage = require 'app/sdk/spells/spellDamage' SpellSummonHighestCostMinion = require 'app/sdk/spells/spellSummonHighestCostMinion' SpellPandaJail = require 'app/sdk/spells/spellPandaJail' SpellCopyMinionToHand = require 'app/sdk/spells/spellCopyMinionToHand' SpellIntensifyDealDamage = require 'app/sdk/spells/spellIntensifyDealDamage' SpellDamageAndPutCardInHand = require 'app/sdk/spells/spellDamageAndPutCardInHand' SpellApplyPlayerModifiers = require 'app/sdk/spells/spellApplyPlayerModifiers' Modifier = require 'app/sdk/modifiers/modifier' ModifierRanged = require 'app/sdk/modifiers/modifierRanged' ModifierManaCostChange = require 'app/sdk/modifiers/modifierManaCostChange' ModifierMyMoveWatchAnyReasonDrawCard = require 'app/sdk/modifiers/modifierMyMoveWatchAnyReasonDrawCard' ModifierBackstab = require 'app/sdk/modifiers/modifierBackstab' ModifierBackstabWatchSummonBackstabMinion = require 'app/sdk/modifiers/modifierBackstabWatchSummonBackstabMinion' ModifierMyAttackWatchApplyModifiers = require 'app/sdk/modifiers/modifierMyAttackWatchApplyModifiers' ModifierBackstabWatchApplyPlayerModifiers = require 'app/sdk/modifiers/modifierBackstabWatchApplyPlayerModifiers' ModifierFlying = require 'app/sdk/modifiers/modifierFlying' ModifierSummonWatchApplyModifiersToRanged = require 'app/sdk/modifiers/modifierSummonWatchApplyModifiersToRanged' ModifierFirstBlood = require 'app/sdk/modifiers/modifierFirstBlood' ModifierStartsInHand = require 'app/sdk/modifiers/modifierStartsInHand' ModifierManaCostChange = require 'app/sdk/modifiers/modifierManaCostChange' ModifierSpellWatchAnywhereApplyModifiers = require 'app/sdk/modifiers/modifierSpellWatchAnywhereApplyModifiers' ModifierDamageBothGeneralsOnReplace = require 'app/sdk/modifiers/modifierDamageBothGeneralsOnReplace' ModifierIntensifyTempBuffNearbyMinion = require 'app/sdk/modifiers/modifierIntensifyTempBuffNearbyMinion' ModifierOnSummonFromHandApplyEmblems = require 'app/sdk/modifiers/modifierOnSummonFromHandApplyEmblems' ModifierManaCostChange = require 'app/sdk/modifiers/modifierManaCostChange' ModifierTokenCreator = require 'app/sdk/modifiers/modifierTokenCreator' ModifierFateSonghaiMinionQuest = require 'app/sdk/modifiers/modifierFateSonghaiMinionQuest' ModifierCannotBeReplaced = require 'app/sdk/modifiers/modifierCannotBeReplaced' ModifierIntensify = require 'app/sdk/modifiers/modifierIntensify' ModifierCounterIntensify = require 'app/sdk/modifiers/modifierCounterIntensify' ModifierCannotBeRemovedFromHand = require 'app/sdk/modifiers/modifierCannotBeRemovedFromHand' PlayerModifierTeamAlwaysBackstabbed = require 'app/sdk/playerModifiers/playerModifierTeamAlwaysBackstabbed' PlayerModifierEmblemSummonWatchSonghaiMeltdownQuest = require 'app/sdk/playerModifiers/playerModifierEmblemSummonWatchSonghaiMeltdownQuest' PlayerModifierSpellWatchHollowVortex = require 'app/sdk/playerModifiers/playerModifierSpellWatchHollowVortex' i18next = require 'i18next' if i18next.t() is undefined i18next.t = (text) -> return text class CardFactory_CoreshatterSet_Faction2 ###* * Returns a card that matches the identifier. * @param {Number|String} identifier * @param {GameSession} gameSession * @returns {Card} ### @cardForIdentifier: (identifier,gameSession) -> card = null if (identifier == Cards.Faction2.DarkHeart) card = new Unit(gameSession) card.factionId = Factions.Faction2 card.setCardSetId(CardSet.Coreshatter) card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Trial: Summon 7 minions from your action bar with different costs.\nDestiny: Summon friendly minions to deal their cost as damage to an enemy.") card.atk = 5 card.maxHP = 5 card.manaCost = 0 card.rarityId = Rarity.Mythron emblemContextObject = PlayerModifierEmblemSummonWatchSonghaiMeltdownQuest.createContextObject() emblemContextObject.appliedName = "Storm of the Ebon Ox" emblemContextObject.appliedDescription = "Whenever you summon a minion, deal damage equal to its cost to an enemy." card.setInherentModifiersContextObjects([ ModifierStartsInHand.createContextObject(), ModifierCannotBeReplaced.createContextObject(), ModifierOnSummonFromHandApplyEmblems.createContextObject([emblemContextObject], true, false), ModifierFateSonghaiMinionQuest.createContextObject(7), ModifierCannotBeRemovedFromHand.createContextObject() ]) card.setFXResource(["FX.Cards.Neutral.DarkHeart"]) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_chakriavatar_attack_swing.audio receiveDamage : RSX.sfx_f2_chakriavatar_hit.audio attackDamage : RSX.sfx_f2_chakriavatar_attack_impact.audio death : RSX.sfx_f2_chakriavatar_death.audio ) card.setBaseAnimResource( breathing : RSX.f2HeartOfTheSonghaiBreathing.name idle : RSX.f2HeartOfTheSonghaiIdle.name walk : RSX.f2HeartOfTheSonghaiRun.name attack : RSX.f2HeartOfTheSonghaiAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f2HeartOfTheSonghaiHit.name death : RSX.f2HeartOfTheSonghaiDeath.name ) if (identifier == Cards.Faction2.MoveMan) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Whenever this minion is moved for any reason, draw a card.") card.atk = 2 card.maxHP = 6 card.manaCost = 4 card.rarityId = Rarity.Epic card.setInherentModifiersContextObjects([ModifierMyMoveWatchAnyReasonDrawCard.createContextObject(1)]) card.setFXResource(["FX.Cards.Neutral.SunSeer"]) card.setBoundingBoxWidth(45) card.setBoundingBoxHeight(80) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_2.audio walk : RSX.sfx_unit_run_magical_4.audio attack : RSX.sfx_neutral_sunseer_attack_swing.audio receiveDamage : RSX.sfx_neutral_sunseer_hit.audio attackDamage : RSX.sfx_neutral_sunseer_attack_impact.audio death : RSX.sfx_neutral_sunseer_death.audio ) card.setBaseAnimResource( breathing : RSX.f2PaperDropperBreathing.name idle : RSX.f2PaperDropperIdle.name walk : RSX.f2PaperDropperRun.name attack : RSX.f2PaperDropperAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.f2PaperDropperHit.name death : RSX.f2PaperDropperDeath.name ) if (identifier == Cards.Spell.DejaVu) card = new SpellDejaVu(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.id = Cards.Spell.DejaVu card.name = "Meditate" card.setDescription("Shuffle five copies of the spell you cast most recently into your deck (excluding Meditate).") card.rarityId = Rarity.Rare card.manaCost = 0 card.spellFilterType = SpellFilterType.NeutralIndirect card.setFXResource(["FX.Cards.Spell.Meditate"]) card.setBaseSoundResource( apply : RSX.sfx_spell_fountainofyouth.audio ) card.setBaseAnimResource( idle : RSX.iconDejaVuIdle.name active : RSX.iconDejaVuActive.name ) if (identifier == Cards.Spell.Kindle) card = new SpellIntensifyDealDamage(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.id = Cards.Spell.Kindle card.name = "Knucklestorm" card.setDescription("Intensify: Deal 1 damage to an enemy.") card.rarityId = Rarity.Common card.manaCost = 1 card.spellFilterType = SpellFilterType.EnemyDirect card.canTargetGeneral = true card.damageAmount = 1 card.addKeywordClassToInclude(ModifierIntensify) card.setInherentModifiersContextObjects([ModifierCounterIntensify.createContextObject()]) card.setFXResource(["FX.Cards.Spell.Knucklestorm"]) card.setBaseSoundResource( apply : RSX.sfx_neutral_bluetipscorpion_attack_impact.audio ) card.setBaseAnimResource( idle : RSX.iconKindleIdle.name active : RSX.iconKindleActive.name ) if (identifier == Cards.Artifact.BackstabGloves) card = new Artifact(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.id = Cards.Artifact.BackstabGloves card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Your General gains +1 Attack.\nAfter a friendly minion with Backstab attacks, it gains +1/+1.") card.manaCost = 1 card.rarityId = Rarity.Epic card.durability = 3 attackBuffContextObject = Modifier.createContextObjectWithAttributeBuffs(1,1) attackBuffContextObject.appliedName = "Growing Charge" auraContextObject = ModifierMyAttackWatchApplyModifiers.createContextObject([attackBuffContextObject]) auraContextObject.appliedName = "Poised to Strike" auraContextObject.appliedDescription = "After this minion attacks, it gains +1/+1." card.setTargetModifiersContextObjects([ Modifier.createContextObjectWithAttributeBuffs(1,0), Modifier.createContextObjectWithAuraForAllAllies([auraContextObject], null, null, [ModifierBackstab.type]) ]) card.addKeywordClassToInclude(ModifierBackstab) card.setFXResource(["FX.Cards.Artifact.EnergyAmulet"]) card.setBaseAnimResource( idle: RSX.iconGorehornMaskIdle.name active: RSX.iconGorehornMaskActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.Faction2.ShadowSummoner) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Backstab: (1).\nWhenever this minion backstabs, summon a minion with Backstab that costs 2 or less from your deck nearby.") card.atk = 2 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare card.setInherentModifiersContextObjects([ModifierBackstab.createContextObject(1), ModifierBackstabWatchSummonBackstabMinion.createContextObject(2)]) card.setFXResource(["FX.Cards.Neutral.VineEntangler"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_komodocharger_attack_swing.audio receiveDamage : RSX.sfx_f6_ancientgrove_hit.audio attackDamage : RSX.sfx_f6_ancientgrove_attack_impact.audio death : RSX.sfx_f6_ancientgrove_death.audio ) card.setBaseAnimResource( breathing : RSX.f2ShadowSummonerBreathing.name idle : RSX.f2ShadowSummonerIdle.name walk : RSX.f2ShadowSummonerRun.name attack : RSX.f2ShadowSummonerAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.f2ShadowSummonerHit.name death : RSX.f2ShadowSummonerDeath.name ) if (identifier == Cards.Faction2.Backbreaker) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Backstab: (2).\nAfter this minion attacks and backstabs, all attacks are backstabs this turn.") card.atk = 2 card.maxHP = 5 card.manaCost = 4 card.rarityId = Rarity.Legendary teamAlwaysBackstabbedModifier = PlayerModifierTeamAlwaysBackstabbed.createContextObject("Massacred", "Backstabbed from any angle!") teamAlwaysBackstabbedModifier.durationEndTurn = 1 card.setInherentModifiersContextObjects([ ModifierBackstab.createContextObject(2), ModifierBackstabWatchApplyPlayerModifiers.createContextObjectToTargetEnemyPlayer([teamAlwaysBackstabbedModifier], false) ]) card.setFXResource(["FX.Cards.Neutral.BloodshardGolem"]) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_redsynja_attack_swing.audio receiveDamage : RSX.sfx_f2_kaidoassassin_hit.audio attackDamage : RSX.sfx_neutral_syvrel_attack_impact.audio death : RSX.sfx_neutral_syvrel_death.audio ) card.setBaseAnimResource( breathing : RSX.f2SupekutaBreathing.name idle : RSX.f2SupekutaIdle.name walk : RSX.f2SupekutaRun.name attack : RSX.f2SupekutaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.f2SupekutaHit.name death : RSX.f2SupekutaDeath.name ) if (identifier == Cards.Faction2.CraneWalker) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Flying") card.atk = 3 card.maxHP = 4 card.manaCost = 3 card.rarityId = Rarity.Common card.setInherentModifiersContextObjects([ModifierFlying.createContextObject()]) card.setFXResource(["FX.Cards.Neutral.PutridMindflayer"]) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_zurael_death.audio attack : RSX.sfx_neutral_zurael_attack_swing.audio receiveDamage : RSX.sfx_neutral_zurael_hit.audio attackDamage : RSX.sfx_neutral_zurael_attack_impact.audio death : RSX.sfx_neutral_zurael_death.audio ) card.setBaseAnimResource( breathing : RSX.f2OrizuruBreathing.name idle : RSX.f2OrizuruIdle.name walk : RSX.f2OrizuruRun.name attack : RSX.f2OrizuruAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f2OrizuruHit.name death : RSX.f2OrizuruDeath.name ) if (identifier == Cards.Faction2.Flareslinger) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Ranged\nWhenever you summon a minion with Ranged, that minion gains Rush.") card.atk = 4 card.maxHP = 4 card.manaCost = 5 card.rarityId = Rarity.Legendary card.setInherentModifiersContextObjects([ModifierRanged.createContextObject(), ModifierSummonWatchApplyModifiersToRanged.createContextObject([ModifierFirstBlood.createContextObject()])]) card.addKeywordClassToInclude(ModifierFirstBlood) card.setFXResource(["FX.Cards.Faction2.FlareSlinger"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_1.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_firespitter_attack_swing.audio receiveDamage : RSX.sfx_neutral_firespitter_hit.audio attackDamage : RSX.sfx_neutral_firespitter_attack_impact.audio death : RSX.sfx_neutral_firespitter_death.audio ) card.setBaseAnimResource( breathing : RSX.f2FlareSlingerBreathing.name idle : RSX.f2FlareSlingerIdle.name walk : RSX.f2FlareSlingerRun.name attack : RSX.f2FlareSlingerAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.f2FlareSlingerHit.name death : RSX.f2FlareSlingerDeath.name ) if (identifier == Cards.Faction2.PandaPuncher) card = new Unit(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Intensify: Give a random nearby friendly minion +2 Attack this turn.") card.atk = 5 card.maxHP = 4 card.manaCost = 4 card.rarityId = Rarity.Common card.setInherentModifiersContextObjects([ ModifierIntensifyTempBuffNearbyMinion.createContextObject(2, 0, "Ignition Fist"), ModifierCounterIntensify.createContextObject() ]) card.setFXResource(["FX.Cards.Neutral.DeathBlighter"]) card.setBoundingBoxWidth(105) card.setBoundingBoxHeight(75) card.setBaseSoundResource( apply : RSX.sfx_neutral_chaoselemental_hit.audio walk : RSX.sfx_neutral_chaoselemental_death.audio attack : RSX.sfx_f4_blacksolus_attack_swing.audio receiveDamage : RSX.sfx_f4_blacksolus_hit.audio attackDamage : RSX.sfx_f4_blacksolus_attack_impact.audio death : RSX.sfx_f4_blacksolus_death.audio ) card.setBaseAnimResource( breathing : RSX.f2PandaPuncherBreathing.name idle : RSX.f2PandaPuncherIdle.name walk : RSX.f2PandaPuncherRun.name attack : RSX.f2PandaPuncherAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.f2PandaPuncherHit.name death : RSX.f2PandaPuncherDeath.name ) if (identifier == Cards.Spell.HollowVortex) card = new SpellApplyPlayerModifiers(gameSession) card.factionId = Factions.Faction2 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.HollowVortex card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Costs 1 less for each spell you cast this game. Whenever you cast a spell this turn, summon a minion that costs up to 2 more nearby your General.") card.manaCost = 11 card.rarityId = Rarity.Legendary customContextObject = PlayerModifierSpellWatchHollowVortex.createContextObject(2) customContextObject.durationEndTurn = 1 customContextObject.appliedName = "PI:NAME:<NAME>END_PI Unleashed" customContextObject.appliedDescription = "Casting spells summons minions." card.applyToOwnGeneral = true card.setTargetModifiersContextObjects([customContextObject]) manaChangeContextObject = ModifierManaCostChange.createContextObject(-1) manaSpellWatch = ModifierSpellWatchAnywhereApplyModifiers.createContextObject([manaChangeContextObject]) card.setInherentModifiersContextObjects([manaSpellWatch]) card.spellFilterType = SpellFilterType.None card.setFXResource(["FX.Cards.Spell.KenshoVortex"]) card.setBaseSoundResource( apply : RSX.sfx_spell_scionsfirstwish.audio ) card.setBaseAnimResource( idle : RSX.iconHollowVortexIdle.name active : RSX.iconHollowVortexActive.name ) if (identifier == Cards.Spell.PandaJail) card = new SpellPandaJail(gameSession) card.factionId = Factions.Faction2 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.PandaJail card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Surround the enemy General with friendly Panddo that disappear at the start of your next turn.") card.manaCost = 3 card.rarityId = Rarity.Epic card.spellFilterType = SpellFilterType.None card.addKeywordClassToInclude(ModifierTokenCreator) card.setFXResource(["FX.Cards.Spell.Pandatentiary"]) card.setBaseSoundResource( apply : RSX.sfx_spell_onyxbearseal.audio ) card.setBaseAnimResource( idle : RSX.iconPandaJailIdle.name active : RSX.iconPandaJailActive.name ) if (identifier == Cards.Spell.GreaterPhoenixFire) card = new SpellDamageAndPutCardInHand(gameSession) card.factionId = Factions.Faction2 card.setCardSetId(CardSet.Coreshatter) card.id = Cards.Spell.GreaterPhoenixFire card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Deal 3 damage to anything.\nPut a Phoenix Fire into your action bar.") card.manaCost = 5 card.rarityId = Rarity.Common card.spellFilterType = SpellFilterType.NeutralDirect card.damageAmount = 3 card.cardDataOrIndexToPutInHand = {id: Cards.Spell.PhoenixFire} card.canTargetGeneral = true card.setFXResource(["FX.Cards.Spell.PhoenixBarrage"]) card.setBaseSoundResource( apply : RSX.sfx_spell_phoenixfire.audio ) card.setBaseAnimResource( idle : RSX.iconPhoenixBarrageIdle.name active : RSX.iconPhoenixBarrageActive.name ) if (identifier == Cards.Spell.BootyProjection) card = new SpellCopyMinionToHand(gameSession) card.setCardSetId(CardSet.Coreshatter) card.factionId = Factions.Faction2 card.id = Cards.Spell.BootyProjection card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Put an EXACT copy of a friendly minion into your action bar.") card.rarityId = Rarity.Rare card.manaCost = 2 card.spellFilterType = SpellFilterType.AllyDirect card.canTargetGeneral = false card.setFXResource(["FX.Cards.Spell.SecondSelf"]) card.setBaseSoundResource( apply : RSX.sfx_spell_drainmorale.audio ) card.setBaseAnimResource( idle : RSX.iconProjectionIdle.name active : RSX.iconProjectionActive.name ) return card module.exports = CardFactory_CoreshatterSet_Faction2
[ { "context": ": lod curves + phe x gen (as mean +/- 2 SE) plot\n# Karl W Broman\n\niplotScanone_ci = (widgetdiv, lod_data, pxg_data", "end": 81, "score": 0.9998399615287781, "start": 68, "tag": "NAME", "value": "Karl W Broman" } ]
inst/htmlwidgets/lib/qtlcharts/iplotScanone_ci.coffee
cran/qtlcharts
64
# iplotScanone_ci: lod curves + phe x gen (as mean +/- 2 SE) plot # Karl W Broman iplotScanone_ci = (widgetdiv, lod_data, pxg_data, chartOpts) -> markers = (x for x of pxg_data.chrByMarkers) # chartOpts start height = chartOpts?.height ? 530 # height of image in pixels width = chartOpts?.width ? 1200 # width of image in pixels wleft = chartOpts?.wleft ? width*0.7 # width of left panel in pixels margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner) lod_axispos = chartOpts?.lod_axispos ? chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel) in LOD curve panel lod_titlepos = chartOpts?.lod_titlepos ? chartOpts?.titlepos ? 20 # position of title for LOD curve panel, in pixels chrGap = chartOpts?.chrGap ? 6 # gap between chromosomes rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of lighter background rectangle altrectcolor = chartOpts?.altrectcolor ? "#C8C8C8" # color of darker background rectangle lod_ylim = chartOpts?.lod_ylim ? null # y-axis limits in LOD curve panel lod_nyticks = chartOpts?.lod_nyticks ? 5 # number of ticks in y-axis in LOD curve panel lod_yticks = chartOpts?.lod_yticks ? null # vector of tick positions for y-axis in LOD curve panel lod_linecolor = chartOpts?.lod_linecolor ? "darkslateblue" # line color for LOD curves lod_linewidth = chartOpts?.lod_linewidth ? 2 # line width for LOD curves lod_pointcolor = chartOpts?.lod_pointcolor ? "#E9CFEC" # color for points at markers in LOD curve panel lod_pointsize = chartOpts?.lod_pointsize ? 0 # size of points at markers (default = 0 corresponding to no visible points at markers) lod_pointstroke = chartOpts?.lod_pointstroke ? "black" # color of outer circle for points at markers in LOD curve panel lod_title = chartOpts?.lod_title ? chartOpts.title ? "" # title of LOD curve panel lod_xlab = chartOpts?.lod_xlab ? null # x-axis label for LOD curve panel lod_ylab = chartOpts?.lod_ylab ? "LOD score" # y-axis label for LOD curve panel lod_rotate_ylab = chartOpts?.lod_rotate_ylab ? null # indicates whether to rotate the y-axis label 90 degrees, in LOD curve panel eff_ylim = chartOpts?.eff_ylim ? null # y-axis limits in effect plot panel eff_nyticks = chartOpts?.eff_nyticks ? 5 # number of ticks in y-axis in effect plot panel eff_yticks = chartOpts?.eff_yticks ? null # vector of tick positions for y-axis in effect plot panel eff_linecolor = chartOpts?.eff_linecolor ? "slateblue" # line color in effect plot panel eff_linewidth = chartOpts?.eff_linewidth ? "3" # line width in effect plot panel eff_xlab = chartOpts?.eff_xlab ? "Genotype" # x-axis label in effect plot panel eff_ylab = chartOpts?.eff_ylab ? "Phenotype" # y-axis label in effect plot panel eff_rotate_ylab = chartOpts?.eff_rotate_ylab ? null # indicates whether to rotate the y-axis label 90 degrees, in effect plot panel eff_segwidth = chartOpts?.eff_segwidth ? null # width of line segments in effect plot panel, in pixels eff_axispos = chartOpts?.eff_axispos ? chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel) in effect plot panel eff_titlepos = chartOpts?.eff_titlepos ? chartOpts?.titlepos ? 20 # position of title for effect plot panel, in pixels # chartOpts end chartdivid = chartOpts?.chartdivid ? 'chart' widgetdivid = d3.select(widgetdiv).attr('id') # make sure list args have all necessary bits margin = d3panels.check_listarg_v_default(margin, {left:60, top:40, right:40, bottom: 40, inner:5}) lod_axispos = d3panels.check_listarg_v_default(lod_axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5}) eff_axispos = d3panels.check_listarg_v_default(eff_axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5}) wright = width - wleft mylodchart = d3panels.lodchart({ height:height width:wleft margin:margin axispos:lod_axispos titlepos:lod_titlepos chrGap:chrGap altrectcolor:altrectcolor rectcolor:rectcolor ylim:lod_ylim nyticks:lod_nyticks yticks:lod_yticks linecolor:lod_linecolor linewidth:lod_linewidth pointcolor:lod_pointcolor pointsize:lod_pointsize pointstroke:lod_pointstroke title:lod_title xlab:lod_xlab ylab:lod_ylab rotate_ylab:lod_rotate_ylab tipclass:widgetdivid}) svg = d3.select(widgetdiv).select("svg") g_lod = svg.append("g") .attr("id", "lodchart") mylodchart(g_lod, lod_data) mycichart = null plotCI = (markername, markerindex) -> mycichart.remove() if mycichart? g = pxg_data.geno[markerindex] gabs = (Math.abs(x) for x in g) chr = pxg_data.chrByMarkers[markername] chrtype = pxg_data.chrtype[chr] genonames = pxg_data.genonames[chrtype] means = [] se = [] low = [] high = [] for j in [1..genonames.length] phesub = (p for p,i in pxg_data.pheno when gabs[i] == j and p?) if phesub.length>0 ave = (phesub.reduce (a,b) -> a+b)/phesub.length means.push(ave) else means.push(null) if phesub.length>1 variance = (phesub.reduce (a,b) -> a+Math.pow(b-ave, 2))/(phesub.length-1) se.push((Math.sqrt(variance/phesub.length))) low.push(means[j-1] - 2*se[j-1]) high.push(means[j-1] + 2*se[j-1]) else se.push(null) low.push(null) high.push(null) range = [d3.min(low), d3.max(high)] if eff_ylim? eff_ylim = [d3.min([range[0],eff_ylim[0]]), d3.max([range[1],eff_ylim[1]])] else eff_ylim = range mycichart = d3panels.cichart({ height:height width:wright margin:margin axispos:eff_axispos titlepos:eff_titlepos title:markername xlab:eff_xlab ylab:eff_ylab rotate_ylab:eff_rotate_ylab ylim:eff_ylim nyticks:eff_nyticks yticks:eff_yticks segcolor:eff_linecolor vertsegcolor:eff_linecolor segstrokewidth:eff_linewidth segwidth:eff_segwidth rectcolor:rectcolor tipclass:widgetdivid xcatlabels:genonames}) ci_g = svg.append("g") .attr("id", "cichart") .attr("transform", "translate(#{wleft},0)") mycichart(ci_g, {'mean':means, 'low':low, 'high':high}) # animate points at markers on click objects = mylodchart.markerSelect() .on "click", (event, d) -> i = objects.nodes().indexOf(this) plotCI(markers[i], i) if chartOpts.heading? d3.select("div#htmlwidget_container") .insert("h2", ":first-child") .html(chartOpts.heading) .style("font-family", "sans-serif") if chartOpts.caption? d3.select("body") .append("p") .attr("class", "caption") .html(chartOpts.caption) if chartOpts.footer? d3.select("body") .append("div") .html(chartOpts.footer) .style("font-family", "sans-serif")
192713
# iplotScanone_ci: lod curves + phe x gen (as mean +/- 2 SE) plot # <NAME> iplotScanone_ci = (widgetdiv, lod_data, pxg_data, chartOpts) -> markers = (x for x of pxg_data.chrByMarkers) # chartOpts start height = chartOpts?.height ? 530 # height of image in pixels width = chartOpts?.width ? 1200 # width of image in pixels wleft = chartOpts?.wleft ? width*0.7 # width of left panel in pixels margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner) lod_axispos = chartOpts?.lod_axispos ? chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel) in LOD curve panel lod_titlepos = chartOpts?.lod_titlepos ? chartOpts?.titlepos ? 20 # position of title for LOD curve panel, in pixels chrGap = chartOpts?.chrGap ? 6 # gap between chromosomes rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of lighter background rectangle altrectcolor = chartOpts?.altrectcolor ? "#C8C8C8" # color of darker background rectangle lod_ylim = chartOpts?.lod_ylim ? null # y-axis limits in LOD curve panel lod_nyticks = chartOpts?.lod_nyticks ? 5 # number of ticks in y-axis in LOD curve panel lod_yticks = chartOpts?.lod_yticks ? null # vector of tick positions for y-axis in LOD curve panel lod_linecolor = chartOpts?.lod_linecolor ? "darkslateblue" # line color for LOD curves lod_linewidth = chartOpts?.lod_linewidth ? 2 # line width for LOD curves lod_pointcolor = chartOpts?.lod_pointcolor ? "#E9CFEC" # color for points at markers in LOD curve panel lod_pointsize = chartOpts?.lod_pointsize ? 0 # size of points at markers (default = 0 corresponding to no visible points at markers) lod_pointstroke = chartOpts?.lod_pointstroke ? "black" # color of outer circle for points at markers in LOD curve panel lod_title = chartOpts?.lod_title ? chartOpts.title ? "" # title of LOD curve panel lod_xlab = chartOpts?.lod_xlab ? null # x-axis label for LOD curve panel lod_ylab = chartOpts?.lod_ylab ? "LOD score" # y-axis label for LOD curve panel lod_rotate_ylab = chartOpts?.lod_rotate_ylab ? null # indicates whether to rotate the y-axis label 90 degrees, in LOD curve panel eff_ylim = chartOpts?.eff_ylim ? null # y-axis limits in effect plot panel eff_nyticks = chartOpts?.eff_nyticks ? 5 # number of ticks in y-axis in effect plot panel eff_yticks = chartOpts?.eff_yticks ? null # vector of tick positions for y-axis in effect plot panel eff_linecolor = chartOpts?.eff_linecolor ? "slateblue" # line color in effect plot panel eff_linewidth = chartOpts?.eff_linewidth ? "3" # line width in effect plot panel eff_xlab = chartOpts?.eff_xlab ? "Genotype" # x-axis label in effect plot panel eff_ylab = chartOpts?.eff_ylab ? "Phenotype" # y-axis label in effect plot panel eff_rotate_ylab = chartOpts?.eff_rotate_ylab ? null # indicates whether to rotate the y-axis label 90 degrees, in effect plot panel eff_segwidth = chartOpts?.eff_segwidth ? null # width of line segments in effect plot panel, in pixels eff_axispos = chartOpts?.eff_axispos ? chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel) in effect plot panel eff_titlepos = chartOpts?.eff_titlepos ? chartOpts?.titlepos ? 20 # position of title for effect plot panel, in pixels # chartOpts end chartdivid = chartOpts?.chartdivid ? 'chart' widgetdivid = d3.select(widgetdiv).attr('id') # make sure list args have all necessary bits margin = d3panels.check_listarg_v_default(margin, {left:60, top:40, right:40, bottom: 40, inner:5}) lod_axispos = d3panels.check_listarg_v_default(lod_axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5}) eff_axispos = d3panels.check_listarg_v_default(eff_axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5}) wright = width - wleft mylodchart = d3panels.lodchart({ height:height width:wleft margin:margin axispos:lod_axispos titlepos:lod_titlepos chrGap:chrGap altrectcolor:altrectcolor rectcolor:rectcolor ylim:lod_ylim nyticks:lod_nyticks yticks:lod_yticks linecolor:lod_linecolor linewidth:lod_linewidth pointcolor:lod_pointcolor pointsize:lod_pointsize pointstroke:lod_pointstroke title:lod_title xlab:lod_xlab ylab:lod_ylab rotate_ylab:lod_rotate_ylab tipclass:widgetdivid}) svg = d3.select(widgetdiv).select("svg") g_lod = svg.append("g") .attr("id", "lodchart") mylodchart(g_lod, lod_data) mycichart = null plotCI = (markername, markerindex) -> mycichart.remove() if mycichart? g = pxg_data.geno[markerindex] gabs = (Math.abs(x) for x in g) chr = pxg_data.chrByMarkers[markername] chrtype = pxg_data.chrtype[chr] genonames = pxg_data.genonames[chrtype] means = [] se = [] low = [] high = [] for j in [1..genonames.length] phesub = (p for p,i in pxg_data.pheno when gabs[i] == j and p?) if phesub.length>0 ave = (phesub.reduce (a,b) -> a+b)/phesub.length means.push(ave) else means.push(null) if phesub.length>1 variance = (phesub.reduce (a,b) -> a+Math.pow(b-ave, 2))/(phesub.length-1) se.push((Math.sqrt(variance/phesub.length))) low.push(means[j-1] - 2*se[j-1]) high.push(means[j-1] + 2*se[j-1]) else se.push(null) low.push(null) high.push(null) range = [d3.min(low), d3.max(high)] if eff_ylim? eff_ylim = [d3.min([range[0],eff_ylim[0]]), d3.max([range[1],eff_ylim[1]])] else eff_ylim = range mycichart = d3panels.cichart({ height:height width:wright margin:margin axispos:eff_axispos titlepos:eff_titlepos title:markername xlab:eff_xlab ylab:eff_ylab rotate_ylab:eff_rotate_ylab ylim:eff_ylim nyticks:eff_nyticks yticks:eff_yticks segcolor:eff_linecolor vertsegcolor:eff_linecolor segstrokewidth:eff_linewidth segwidth:eff_segwidth rectcolor:rectcolor tipclass:widgetdivid xcatlabels:genonames}) ci_g = svg.append("g") .attr("id", "cichart") .attr("transform", "translate(#{wleft},0)") mycichart(ci_g, {'mean':means, 'low':low, 'high':high}) # animate points at markers on click objects = mylodchart.markerSelect() .on "click", (event, d) -> i = objects.nodes().indexOf(this) plotCI(markers[i], i) if chartOpts.heading? d3.select("div#htmlwidget_container") .insert("h2", ":first-child") .html(chartOpts.heading) .style("font-family", "sans-serif") if chartOpts.caption? d3.select("body") .append("p") .attr("class", "caption") .html(chartOpts.caption) if chartOpts.footer? d3.select("body") .append("div") .html(chartOpts.footer) .style("font-family", "sans-serif")
true
# iplotScanone_ci: lod curves + phe x gen (as mean +/- 2 SE) plot # PI:NAME:<NAME>END_PI iplotScanone_ci = (widgetdiv, lod_data, pxg_data, chartOpts) -> markers = (x for x of pxg_data.chrByMarkers) # chartOpts start height = chartOpts?.height ? 530 # height of image in pixels width = chartOpts?.width ? 1200 # width of image in pixels wleft = chartOpts?.wleft ? width*0.7 # width of left panel in pixels margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner) lod_axispos = chartOpts?.lod_axispos ? chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel) in LOD curve panel lod_titlepos = chartOpts?.lod_titlepos ? chartOpts?.titlepos ? 20 # position of title for LOD curve panel, in pixels chrGap = chartOpts?.chrGap ? 6 # gap between chromosomes rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of lighter background rectangle altrectcolor = chartOpts?.altrectcolor ? "#C8C8C8" # color of darker background rectangle lod_ylim = chartOpts?.lod_ylim ? null # y-axis limits in LOD curve panel lod_nyticks = chartOpts?.lod_nyticks ? 5 # number of ticks in y-axis in LOD curve panel lod_yticks = chartOpts?.lod_yticks ? null # vector of tick positions for y-axis in LOD curve panel lod_linecolor = chartOpts?.lod_linecolor ? "darkslateblue" # line color for LOD curves lod_linewidth = chartOpts?.lod_linewidth ? 2 # line width for LOD curves lod_pointcolor = chartOpts?.lod_pointcolor ? "#E9CFEC" # color for points at markers in LOD curve panel lod_pointsize = chartOpts?.lod_pointsize ? 0 # size of points at markers (default = 0 corresponding to no visible points at markers) lod_pointstroke = chartOpts?.lod_pointstroke ? "black" # color of outer circle for points at markers in LOD curve panel lod_title = chartOpts?.lod_title ? chartOpts.title ? "" # title of LOD curve panel lod_xlab = chartOpts?.lod_xlab ? null # x-axis label for LOD curve panel lod_ylab = chartOpts?.lod_ylab ? "LOD score" # y-axis label for LOD curve panel lod_rotate_ylab = chartOpts?.lod_rotate_ylab ? null # indicates whether to rotate the y-axis label 90 degrees, in LOD curve panel eff_ylim = chartOpts?.eff_ylim ? null # y-axis limits in effect plot panel eff_nyticks = chartOpts?.eff_nyticks ? 5 # number of ticks in y-axis in effect plot panel eff_yticks = chartOpts?.eff_yticks ? null # vector of tick positions for y-axis in effect plot panel eff_linecolor = chartOpts?.eff_linecolor ? "slateblue" # line color in effect plot panel eff_linewidth = chartOpts?.eff_linewidth ? "3" # line width in effect plot panel eff_xlab = chartOpts?.eff_xlab ? "Genotype" # x-axis label in effect plot panel eff_ylab = chartOpts?.eff_ylab ? "Phenotype" # y-axis label in effect plot panel eff_rotate_ylab = chartOpts?.eff_rotate_ylab ? null # indicates whether to rotate the y-axis label 90 degrees, in effect plot panel eff_segwidth = chartOpts?.eff_segwidth ? null # width of line segments in effect plot panel, in pixels eff_axispos = chartOpts?.eff_axispos ? chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel) in effect plot panel eff_titlepos = chartOpts?.eff_titlepos ? chartOpts?.titlepos ? 20 # position of title for effect plot panel, in pixels # chartOpts end chartdivid = chartOpts?.chartdivid ? 'chart' widgetdivid = d3.select(widgetdiv).attr('id') # make sure list args have all necessary bits margin = d3panels.check_listarg_v_default(margin, {left:60, top:40, right:40, bottom: 40, inner:5}) lod_axispos = d3panels.check_listarg_v_default(lod_axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5}) eff_axispos = d3panels.check_listarg_v_default(eff_axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5}) wright = width - wleft mylodchart = d3panels.lodchart({ height:height width:wleft margin:margin axispos:lod_axispos titlepos:lod_titlepos chrGap:chrGap altrectcolor:altrectcolor rectcolor:rectcolor ylim:lod_ylim nyticks:lod_nyticks yticks:lod_yticks linecolor:lod_linecolor linewidth:lod_linewidth pointcolor:lod_pointcolor pointsize:lod_pointsize pointstroke:lod_pointstroke title:lod_title xlab:lod_xlab ylab:lod_ylab rotate_ylab:lod_rotate_ylab tipclass:widgetdivid}) svg = d3.select(widgetdiv).select("svg") g_lod = svg.append("g") .attr("id", "lodchart") mylodchart(g_lod, lod_data) mycichart = null plotCI = (markername, markerindex) -> mycichart.remove() if mycichart? g = pxg_data.geno[markerindex] gabs = (Math.abs(x) for x in g) chr = pxg_data.chrByMarkers[markername] chrtype = pxg_data.chrtype[chr] genonames = pxg_data.genonames[chrtype] means = [] se = [] low = [] high = [] for j in [1..genonames.length] phesub = (p for p,i in pxg_data.pheno when gabs[i] == j and p?) if phesub.length>0 ave = (phesub.reduce (a,b) -> a+b)/phesub.length means.push(ave) else means.push(null) if phesub.length>1 variance = (phesub.reduce (a,b) -> a+Math.pow(b-ave, 2))/(phesub.length-1) se.push((Math.sqrt(variance/phesub.length))) low.push(means[j-1] - 2*se[j-1]) high.push(means[j-1] + 2*se[j-1]) else se.push(null) low.push(null) high.push(null) range = [d3.min(low), d3.max(high)] if eff_ylim? eff_ylim = [d3.min([range[0],eff_ylim[0]]), d3.max([range[1],eff_ylim[1]])] else eff_ylim = range mycichart = d3panels.cichart({ height:height width:wright margin:margin axispos:eff_axispos titlepos:eff_titlepos title:markername xlab:eff_xlab ylab:eff_ylab rotate_ylab:eff_rotate_ylab ylim:eff_ylim nyticks:eff_nyticks yticks:eff_yticks segcolor:eff_linecolor vertsegcolor:eff_linecolor segstrokewidth:eff_linewidth segwidth:eff_segwidth rectcolor:rectcolor tipclass:widgetdivid xcatlabels:genonames}) ci_g = svg.append("g") .attr("id", "cichart") .attr("transform", "translate(#{wleft},0)") mycichart(ci_g, {'mean':means, 'low':low, 'high':high}) # animate points at markers on click objects = mylodchart.markerSelect() .on "click", (event, d) -> i = objects.nodes().indexOf(this) plotCI(markers[i], i) if chartOpts.heading? d3.select("div#htmlwidget_container") .insert("h2", ":first-child") .html(chartOpts.heading) .style("font-family", "sans-serif") if chartOpts.caption? d3.select("body") .append("p") .attr("class", "caption") .html(chartOpts.caption) if chartOpts.footer? d3.select("body") .append("div") .html(chartOpts.footer) .style("font-family", "sans-serif")
[ { "context": "ic functionality for our controllers.\n\n @author Sebastian Sachtleben\n###\nclass BaseController\n\n\t# OVERRIDE to register", "end": 163, "score": 0.9998833537101746, "start": 143, "tag": "NAME", "value": "Sebastian Sachtleben" } ]
app/assets/javascripts/engine/controllers/baseController.coffee
ssachtleben/herowar
1
app = require 'application' popup = require 'popup' ### The BaseController provides basic functionality for our controllers. @author Sebastian Sachtleben ### class BaseController # OVERRIDE to register views, for special behavior just add views to app.views yourself views: {} # options is the arguments array passed from the router, so convert it to an object constructor: (options) -> @options = _.extend {}, options @$body = $ 'body' @initialize @options initialize: (options) -> @_registerViews() _registerViews: -> popup.remove() activeViews = {} _.keys(app.views) refreshAll = @_isArrayEqual _.keys(app.views), _.keys(@views) for key, value of app.views if not refreshAll and @views.hasOwnProperty key then activeViews[key] = value else value.remove() activeViews[viewName] = @_appendView @_createView(viewName),@$body for viewName of @views when activeViews[viewName] is undefined app.views = activeViews return _appendView: (view, el) -> el.append view.$el view.render() return view _createView: (viewName) -> options = @[@views[viewName]]() if @views[viewName] new (require viewName) options _isArrayEqual: (a1, a2) -> return false unless _.isArray(a1) and _.isArray(a2) and a1.length is a2.length return true if _.difference(a1,a2).length is 0 return false return BaseController
209113
app = require 'application' popup = require 'popup' ### The BaseController provides basic functionality for our controllers. @author <NAME> ### class BaseController # OVERRIDE to register views, for special behavior just add views to app.views yourself views: {} # options is the arguments array passed from the router, so convert it to an object constructor: (options) -> @options = _.extend {}, options @$body = $ 'body' @initialize @options initialize: (options) -> @_registerViews() _registerViews: -> popup.remove() activeViews = {} _.keys(app.views) refreshAll = @_isArrayEqual _.keys(app.views), _.keys(@views) for key, value of app.views if not refreshAll and @views.hasOwnProperty key then activeViews[key] = value else value.remove() activeViews[viewName] = @_appendView @_createView(viewName),@$body for viewName of @views when activeViews[viewName] is undefined app.views = activeViews return _appendView: (view, el) -> el.append view.$el view.render() return view _createView: (viewName) -> options = @[@views[viewName]]() if @views[viewName] new (require viewName) options _isArrayEqual: (a1, a2) -> return false unless _.isArray(a1) and _.isArray(a2) and a1.length is a2.length return true if _.difference(a1,a2).length is 0 return false return BaseController
true
app = require 'application' popup = require 'popup' ### The BaseController provides basic functionality for our controllers. @author PI:NAME:<NAME>END_PI ### class BaseController # OVERRIDE to register views, for special behavior just add views to app.views yourself views: {} # options is the arguments array passed from the router, so convert it to an object constructor: (options) -> @options = _.extend {}, options @$body = $ 'body' @initialize @options initialize: (options) -> @_registerViews() _registerViews: -> popup.remove() activeViews = {} _.keys(app.views) refreshAll = @_isArrayEqual _.keys(app.views), _.keys(@views) for key, value of app.views if not refreshAll and @views.hasOwnProperty key then activeViews[key] = value else value.remove() activeViews[viewName] = @_appendView @_createView(viewName),@$body for viewName of @views when activeViews[viewName] is undefined app.views = activeViews return _appendView: (view, el) -> el.append view.$el view.render() return view _createView: (viewName) -> options = @[@views[viewName]]() if @views[viewName] new (require viewName) options _isArrayEqual: (a1, a2) -> return false unless _.isArray(a1) and _.isArray(a2) and a1.length is a2.length return true if _.difference(a1,a2).length is 0 return false return BaseController
[ { "context": "# @author Gianluigi Mango\n# Comment Model\nmongoose = require 'mongoose'\n\nmo", "end": 25, "score": 0.9998734593391418, "start": 10, "tag": "NAME", "value": "Gianluigi Mango" } ]
dev/server/models/commentModel.coffee
knickatheart/mean-api
0
# @author Gianluigi Mango # Comment Model mongoose = require 'mongoose' module.exports = mongoose.model 'Comment', mongoose.Schema parent: String, data: String, active: Number, createdBy: String, createdAt: String 'comments'
39290
# @author <NAME> # Comment Model mongoose = require 'mongoose' module.exports = mongoose.model 'Comment', mongoose.Schema parent: String, data: String, active: Number, createdBy: String, createdAt: String 'comments'
true
# @author PI:NAME:<NAME>END_PI # Comment Model mongoose = require 'mongoose' module.exports = mongoose.model 'Comment', mongoose.Schema parent: String, data: String, active: Number, createdBy: String, createdAt: String 'comments'
[ { "context": "hub.com/TrevorBurnham/Jitter\n\n Copyright (c) 2010 Trevor Burnham\n http://iterative.ly\n\n Based on command.coffee ", "end": 184, "score": 0.9999106526374817, "start": 170, "tag": "NAME", "value": "Trevor Burnham" }, { "context": " http://iterative.ly\n\n Based on command.coffee by Jeremy Ashkenas\n http://jashkenas.github.com/coffee-script/docum", "end": 252, "score": 0.999839723110199, "start": 237, "tag": "NAME", "value": "Jeremy Ashkenas" }, { "context": "and.html\n\n Growl notification code contributed by Andrey Tarantsov\n http://www.tarantsov.com/\n\n Permission is here", "end": 387, "score": 0.9999043345451355, "start": 371, "tag": "NAME", "value": "Andrey Tarantsov" } ]
Workspace/QRef/NodeServer/node_modules/jitter/src/jitter.coffee
qrefdev/qref
0
### Jitter, a CoffeeScript compilation utility The latest version and documentation, can be found at: http://github.com/TrevorBurnham/Jitter Copyright (c) 2010 Trevor Burnham http://iterative.ly Based on command.coffee by Jeremy Ashkenas http://jashkenas.github.com/coffee-script/documentation/docs/command.html Growl notification code contributed by Andrey Tarantsov http://www.tarantsov.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### # External dependencies fs= require 'fs' path= require 'path' optparse= require './optparse' if path.basename(process.argv[1]) == 'witter' targetlib = 'coco' target_ext = '.coco' else targetlib = 'coffee-script' target_ext = '.coffee' CoffeeScript= require targetlib {exec}= require 'child_process' {puts, print}= try require 'util' catch e then require 'sys' {q}= require 'sink' # Banner shown if jitter is run without arguments BANNER= ''' Jitter takes a directory of *.coffee files and recursively compiles them to *.js files, preserving the original directory structure. Jitter also watches for changes and automatically recompiles as needed. It even detects new files, unlike the coffee utility. If passed a test directory, it will run each test through node on each change. Usage: jitter coffee-path js-path [test-path] ''' # Globals options= {} baseSource= baseTarget= baseTest= '' optionParser= null isWatched= {} testFiles= [] exports.run= -> options = parseOptions() return usage() unless baseTarget compileScripts(options) compileScripts= (options) -> dirs= Source: baseSource, Target: baseTarget dirs.Test= baseTest if baseTest for name, dir of dirs q path.exists, dir, (exists) -> unless exists die "#{name} directory '#{dir}' does not exist." else unless fs.statSync(dir).isDirectory() die "#{name} '#{dir}' is a file; Jitter needs a directory." q -> rootCompile options q runTests q -> puts 'Watching for changes and new files. Press Ctrl+C to stop.' setInterval -> rootCompile options , 500 compile= (source, target, options) -> for item in fs.readdirSync source sourcePath= "#{source}/#{item}" continue if item[0] is '.' continue if isWatched[sourcePath] try if path.extname(sourcePath) is target_ext readScript sourcePath, target, options else if fs.statSync(sourcePath).isDirectory() compile sourcePath, target, options catch e rootCompile= (options) -> compile(baseSource, baseTarget, options) compile(baseTest, baseTest, options) if baseTest readScript= (source, target, options) -> compileScript(source, target, options) watchScript(source, target, options) watchScript= (source, target, options) -> return if isWatched[source] isWatched[source]= true fs.watchFile source, persistent: true, interval: 250, (curr, prev) -> return if curr.mtime.getTime() is prev.mtime.getTime() compileScript(source, target, options) q runTests compileScript= (source, target, options) -> targetPath = jsPath source, target try code= fs.readFileSync(source).toString() try currentJS = fs.readFileSync(targetPath).toString() js= CoffeeScript.compile code, {source, bare: options?.bare} return if js is currentJS writeJS js, targetPath if currentJS? puts 'Recompiled '+ source else puts 'Compiled '+ source catch err puts err.message notifyGrowl source, err.message jsPath= (source, target) -> base= if target is baseTest then baseTest else baseSource filename= path.basename(source, path.extname(source)) + '.js' dir= target + path.dirname(source).substring(base.length) path.join dir, filename writeJS= (js, targetPath) -> q exec, "mkdir -p #{path.dirname targetPath}", -> fs.writeFileSync targetPath, js if baseTest and isSubpath(baseTest, targetPath) and (targetPath not in testFiles) testFiles.push targetPath notifyGrowl= (source, errMessage) -> basename= source.replace(/^.*[\/\\]/, '') if m= errMessage.match /Parse error on line (\d+)/ message= "Parse error in #{basename}\non line #{m[1]}." else message= "Error in #{basename}." args= ['growlnotify', '-n', 'CoffeeScript', '-p', '2', '-t', "\"Compilation failed\"", '-m', "\"#{message}\""] exec args.join(' ') runTests= -> for test in testFiles puts "Running #{test}" exec "node #{test}", (error, stdout, stderr) -> print stdout print stderr notifyGrowl test, stderr if stderr parseOptions= -> optionParser= new optparse.OptionParser [ ['-b', '--bare', 'compile without the top-level function wrapper'] ], BANNER options= optionParser.parse process.argv [baseSource, baseTarget, baseTest]= (options.arguments[arg] or '' for arg in [2..4]) if /\/$/.test baseSource then baseSource= baseSource.substr 0, baseSource.length-1 if /\/$/.test baseTarget then baseTarget= baseTarget.substr 0, baseTarget.length-1 options usage= -> puts optionParser.help() process.exit 0 die= (message) -> puts message process.exit 1 # http://stackoverflow.com/questions/5888477/ isSubpath= (parent, sub) -> parent = fs.realpathSync parent sub = fs.realpathSync sub sub.indexOf(parent) is 0
13188
### Jitter, a CoffeeScript compilation utility The latest version and documentation, can be found at: http://github.com/TrevorBurnham/Jitter Copyright (c) 2010 <NAME> http://iterative.ly Based on command.coffee by <NAME> http://jashkenas.github.com/coffee-script/documentation/docs/command.html Growl notification code contributed by <NAME> http://www.tarantsov.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### # External dependencies fs= require 'fs' path= require 'path' optparse= require './optparse' if path.basename(process.argv[1]) == 'witter' targetlib = 'coco' target_ext = '.coco' else targetlib = 'coffee-script' target_ext = '.coffee' CoffeeScript= require targetlib {exec}= require 'child_process' {puts, print}= try require 'util' catch e then require 'sys' {q}= require 'sink' # Banner shown if jitter is run without arguments BANNER= ''' Jitter takes a directory of *.coffee files and recursively compiles them to *.js files, preserving the original directory structure. Jitter also watches for changes and automatically recompiles as needed. It even detects new files, unlike the coffee utility. If passed a test directory, it will run each test through node on each change. Usage: jitter coffee-path js-path [test-path] ''' # Globals options= {} baseSource= baseTarget= baseTest= '' optionParser= null isWatched= {} testFiles= [] exports.run= -> options = parseOptions() return usage() unless baseTarget compileScripts(options) compileScripts= (options) -> dirs= Source: baseSource, Target: baseTarget dirs.Test= baseTest if baseTest for name, dir of dirs q path.exists, dir, (exists) -> unless exists die "#{name} directory '#{dir}' does not exist." else unless fs.statSync(dir).isDirectory() die "#{name} '#{dir}' is a file; Jitter needs a directory." q -> rootCompile options q runTests q -> puts 'Watching for changes and new files. Press Ctrl+C to stop.' setInterval -> rootCompile options , 500 compile= (source, target, options) -> for item in fs.readdirSync source sourcePath= "#{source}/#{item}" continue if item[0] is '.' continue if isWatched[sourcePath] try if path.extname(sourcePath) is target_ext readScript sourcePath, target, options else if fs.statSync(sourcePath).isDirectory() compile sourcePath, target, options catch e rootCompile= (options) -> compile(baseSource, baseTarget, options) compile(baseTest, baseTest, options) if baseTest readScript= (source, target, options) -> compileScript(source, target, options) watchScript(source, target, options) watchScript= (source, target, options) -> return if isWatched[source] isWatched[source]= true fs.watchFile source, persistent: true, interval: 250, (curr, prev) -> return if curr.mtime.getTime() is prev.mtime.getTime() compileScript(source, target, options) q runTests compileScript= (source, target, options) -> targetPath = jsPath source, target try code= fs.readFileSync(source).toString() try currentJS = fs.readFileSync(targetPath).toString() js= CoffeeScript.compile code, {source, bare: options?.bare} return if js is currentJS writeJS js, targetPath if currentJS? puts 'Recompiled '+ source else puts 'Compiled '+ source catch err puts err.message notifyGrowl source, err.message jsPath= (source, target) -> base= if target is baseTest then baseTest else baseSource filename= path.basename(source, path.extname(source)) + '.js' dir= target + path.dirname(source).substring(base.length) path.join dir, filename writeJS= (js, targetPath) -> q exec, "mkdir -p #{path.dirname targetPath}", -> fs.writeFileSync targetPath, js if baseTest and isSubpath(baseTest, targetPath) and (targetPath not in testFiles) testFiles.push targetPath notifyGrowl= (source, errMessage) -> basename= source.replace(/^.*[\/\\]/, '') if m= errMessage.match /Parse error on line (\d+)/ message= "Parse error in #{basename}\non line #{m[1]}." else message= "Error in #{basename}." args= ['growlnotify', '-n', 'CoffeeScript', '-p', '2', '-t', "\"Compilation failed\"", '-m', "\"#{message}\""] exec args.join(' ') runTests= -> for test in testFiles puts "Running #{test}" exec "node #{test}", (error, stdout, stderr) -> print stdout print stderr notifyGrowl test, stderr if stderr parseOptions= -> optionParser= new optparse.OptionParser [ ['-b', '--bare', 'compile without the top-level function wrapper'] ], BANNER options= optionParser.parse process.argv [baseSource, baseTarget, baseTest]= (options.arguments[arg] or '' for arg in [2..4]) if /\/$/.test baseSource then baseSource= baseSource.substr 0, baseSource.length-1 if /\/$/.test baseTarget then baseTarget= baseTarget.substr 0, baseTarget.length-1 options usage= -> puts optionParser.help() process.exit 0 die= (message) -> puts message process.exit 1 # http://stackoverflow.com/questions/5888477/ isSubpath= (parent, sub) -> parent = fs.realpathSync parent sub = fs.realpathSync sub sub.indexOf(parent) is 0
true
### Jitter, a CoffeeScript compilation utility The latest version and documentation, can be found at: http://github.com/TrevorBurnham/Jitter Copyright (c) 2010 PI:NAME:<NAME>END_PI http://iterative.ly Based on command.coffee by PI:NAME:<NAME>END_PI http://jashkenas.github.com/coffee-script/documentation/docs/command.html Growl notification code contributed by PI:NAME:<NAME>END_PI http://www.tarantsov.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### # External dependencies fs= require 'fs' path= require 'path' optparse= require './optparse' if path.basename(process.argv[1]) == 'witter' targetlib = 'coco' target_ext = '.coco' else targetlib = 'coffee-script' target_ext = '.coffee' CoffeeScript= require targetlib {exec}= require 'child_process' {puts, print}= try require 'util' catch e then require 'sys' {q}= require 'sink' # Banner shown if jitter is run without arguments BANNER= ''' Jitter takes a directory of *.coffee files and recursively compiles them to *.js files, preserving the original directory structure. Jitter also watches for changes and automatically recompiles as needed. It even detects new files, unlike the coffee utility. If passed a test directory, it will run each test through node on each change. Usage: jitter coffee-path js-path [test-path] ''' # Globals options= {} baseSource= baseTarget= baseTest= '' optionParser= null isWatched= {} testFiles= [] exports.run= -> options = parseOptions() return usage() unless baseTarget compileScripts(options) compileScripts= (options) -> dirs= Source: baseSource, Target: baseTarget dirs.Test= baseTest if baseTest for name, dir of dirs q path.exists, dir, (exists) -> unless exists die "#{name} directory '#{dir}' does not exist." else unless fs.statSync(dir).isDirectory() die "#{name} '#{dir}' is a file; Jitter needs a directory." q -> rootCompile options q runTests q -> puts 'Watching for changes and new files. Press Ctrl+C to stop.' setInterval -> rootCompile options , 500 compile= (source, target, options) -> for item in fs.readdirSync source sourcePath= "#{source}/#{item}" continue if item[0] is '.' continue if isWatched[sourcePath] try if path.extname(sourcePath) is target_ext readScript sourcePath, target, options else if fs.statSync(sourcePath).isDirectory() compile sourcePath, target, options catch e rootCompile= (options) -> compile(baseSource, baseTarget, options) compile(baseTest, baseTest, options) if baseTest readScript= (source, target, options) -> compileScript(source, target, options) watchScript(source, target, options) watchScript= (source, target, options) -> return if isWatched[source] isWatched[source]= true fs.watchFile source, persistent: true, interval: 250, (curr, prev) -> return if curr.mtime.getTime() is prev.mtime.getTime() compileScript(source, target, options) q runTests compileScript= (source, target, options) -> targetPath = jsPath source, target try code= fs.readFileSync(source).toString() try currentJS = fs.readFileSync(targetPath).toString() js= CoffeeScript.compile code, {source, bare: options?.bare} return if js is currentJS writeJS js, targetPath if currentJS? puts 'Recompiled '+ source else puts 'Compiled '+ source catch err puts err.message notifyGrowl source, err.message jsPath= (source, target) -> base= if target is baseTest then baseTest else baseSource filename= path.basename(source, path.extname(source)) + '.js' dir= target + path.dirname(source).substring(base.length) path.join dir, filename writeJS= (js, targetPath) -> q exec, "mkdir -p #{path.dirname targetPath}", -> fs.writeFileSync targetPath, js if baseTest and isSubpath(baseTest, targetPath) and (targetPath not in testFiles) testFiles.push targetPath notifyGrowl= (source, errMessage) -> basename= source.replace(/^.*[\/\\]/, '') if m= errMessage.match /Parse error on line (\d+)/ message= "Parse error in #{basename}\non line #{m[1]}." else message= "Error in #{basename}." args= ['growlnotify', '-n', 'CoffeeScript', '-p', '2', '-t', "\"Compilation failed\"", '-m', "\"#{message}\""] exec args.join(' ') runTests= -> for test in testFiles puts "Running #{test}" exec "node #{test}", (error, stdout, stderr) -> print stdout print stderr notifyGrowl test, stderr if stderr parseOptions= -> optionParser= new optparse.OptionParser [ ['-b', '--bare', 'compile without the top-level function wrapper'] ], BANNER options= optionParser.parse process.argv [baseSource, baseTarget, baseTest]= (options.arguments[arg] or '' for arg in [2..4]) if /\/$/.test baseSource then baseSource= baseSource.substr 0, baseSource.length-1 if /\/$/.test baseTarget then baseTarget= baseTarget.substr 0, baseTarget.length-1 options usage= -> puts optionParser.help() process.exit 0 die= (message) -> puts message process.exit 1 # http://stackoverflow.com/questions/5888477/ isSubpath= (parent, sub) -> parent = fs.realpathSync parent sub = fs.realpathSync sub sub.indexOf(parent) is 0
[ { "context": "esta).to.not.be.ok()\n testAdapter = { name: \"testa\" }\n Opentip.addAdapter testAdapter\n exp", "end": 15684, "score": 0.9843653440475464, "start": 15679, "tag": "NAME", "value": "testa" } ]
test/src/010-opentip.coffee
underscorebrody/opentip
453
$ = jQuery describe "Opentip", -> adapter = null beforeEach -> adapter = Opentip.adapter afterEach -> elements = $(".opentip-container") elements.remove() describe "constructor()", -> before -> sinon.stub Opentip::, "_setup" after -> Opentip::_setup.restore() it "arguments should be optional", -> element = adapter.create "<div></div>" opentip = new Opentip element, "content" expect(opentip.content).to.equal "content" expect(adapter.unwrap(opentip.triggerElement)).to.equal adapter.unwrap element opentip = new Opentip element, "content", "title", { hideOn: "click" } expect(opentip.content).to.equal "content" expect(adapter.unwrap opentip.triggerElement).to.equal adapter.unwrap element expect(opentip.options.hideOn).to.equal "click" expect(opentip.options.title).to.equal "title" opentip = new Opentip element, { hideOn: "click" } expect(adapter.unwrap opentip.triggerElement).to.equal adapter.unwrap element expect(opentip.options.hideOn).to.equal "click" expect(opentip.content).to.equal "" expect(opentip.options.title).to.equal undefined it "should always use the next tip id", -> element = document.createElement "div" Opentip.lastId = 0 opentip = new Opentip element, "Test" opentip2 = new Opentip element, "Test" opentip3 = new Opentip element, "Test" expect(opentip.id).to.be 1 expect(opentip2.id).to.be 2 expect(opentip3.id).to.be 3 it "should use the href attribute if AJAX and an A element", -> element = $("""<a href="http://testlink">link</a>""")[0] opentip = new Opentip element, ajax: on expect(opentip.options.ajax).to.equal "http://testlink" it "should disable AJAX if neither URL or a link HREF is provided", -> element = $("""<div>text</div>""")[0] opentip = new Opentip element, ajax: on expect(opentip.options.ajax).to.be false it "should disable a link if the event is onClick", -> sinon.stub adapter, "observe" element = $("""<a href="http://testlink">link</a>""")[0] sinon.stub Opentip::, "_setupObservers" opentip = new Opentip element, showOn: "click" expect(adapter.observe.calledOnce).to.be.ok() expect(adapter.observe.getCall(0).args[1]).to.equal "click" Opentip::_setupObservers.restore() adapter.observe.restore() it "should take all options from selected style", -> element = document.createElement "div" opentip = new Opentip element, style: "glass", showOn: "click" # Should have been set by the options expect(opentip.options.showOn).to.equal "click" # Should have been set by the glass theme expect(opentip.options.className).to.equal "glass" # Should have been set by the standard theme expect(opentip.options.stemLength).to.equal 5 it "the property 'style' should be handled the same as 'extends'", -> element = document.createElement "div" opentip = new Opentip element, extends: "glass", showOn: "click" # Should have been set by the options expect(opentip.options.showOn).to.equal "click" # Should have been set by the glass theme expect(opentip.options.className).to.equal "glass" # Should have been set by the standard theme expect(opentip.options.stemLength).to.equal 5 it "chaining incorrect styles should throw an exception", -> element = document.createElement "div" expect(-> new Opentip element, { extends: "invalidstyle" }).to.throwException /Invalid style\: invalidstyle/ it "chaining styles should work", -> element = document.createElement "div" Opentip.styles.test1 = stemLength: 40 Opentip.styles.test2 = extends: "test1", title: "overwritten title" Opentip.styles.test3 = extends: "test2", className: "test5", title: "some title" opentip = new Opentip element, { extends: "test3", stemBase: 20 } expect(opentip.options.className).to.equal "test5" expect(opentip.options.title).to.equal "some title" expect(opentip.options.stemLength).to.equal 40 expect(opentip.options.stemBase).to.equal 20 it "should set the options to fixed if a target is provided", -> element = document.createElement "div" opentip = new Opentip element, target: yes, fixed: no expect(opentip.options.fixed).to.be.ok() it "should use provided stem", -> element = document.createElement "div" opentip = new Opentip element, stem: "bottom", tipJoin: "topLeft" expect(opentip.options.stem.toString()).to.eql "bottom" it "should take the tipJoint as stem if stem is just true", -> element = document.createElement "div" opentip = new Opentip element, stem: yes, tipJoint: "top left" expect(opentip.options.stem.toString()).to.eql "top left" it "should use provided target", -> element = adapter.create "<div></div>" element2 = adapter.create "<div></div>" opentip = new Opentip element, target: element2 expect(adapter.unwrap opentip.options.target).to.equal adapter.unwrap element2 it "should take the triggerElement as target if target is just true", -> element = adapter.create "<div></div>" opentip = new Opentip element, target: yes expect(adapter.unwrap opentip.options.target).to.equal adapter.unwrap element it "currentStemPosition should be set to inital stemPosition", -> element = adapter.create "<div></div>" opentip = new Opentip element, stem: "topLeft" expect(opentip.currentStem.toString()).to.eql "top left" it "delay should be automatically set if none provided", -> element = document.createElement "div" opentip = new Opentip element, delay: null, showOn: "click" expect(opentip.options.delay).to.equal 0 opentip = new Opentip element, delay: null, showOn: "mouseover" expect(opentip.options.delay).to.equal 0.2 it "the targetJoint should be the inverse of the tipJoint if none provided", -> element = document.createElement "div" opentip = new Opentip element, tipJoint: "left" expect(opentip.options.targetJoint.toString()).to.eql "right" opentip = new Opentip element, tipJoint: "top" expect(opentip.options.targetJoint.toString()).to.eql "bottom" opentip = new Opentip element, tipJoint: "bottom right" expect(opentip.options.targetJoint.toString()).to.eql "top left" it "should setup all trigger elements", -> element = adapter.create "<div></div>" opentip = new Opentip element, showOn: "click" expect(opentip.showTriggers[0].event).to.eql "click" expect(adapter.unwrap opentip.showTriggers[0].element).to.equal adapter.unwrap element expect(opentip.showTriggersWhenVisible).to.eql [ ] expect(opentip.hideTriggers).to.eql [ ] opentip = new Opentip element, showOn: "creation" expect(opentip.showTriggers).to.eql [ ] expect(opentip.showTriggersWhenVisible).to.eql [ ] expect(opentip.hideTriggers).to.eql [ ] it "should copy options.hideTrigger onto options.hideTriggers", -> element = adapter.create "<div></div>" opentip = new Opentip element, hideTrigger: "closeButton", hideTriggers: [ ] expect(opentip.options.hideTriggers).to.eql [ "closeButton"] it "should NOT copy options.hideTrigger onto options.hideTriggers when hideTriggers are set", -> element = adapter.create "<div></div>" opentip = new Opentip element, hideTrigger: "closeButton", hideTriggers: [ "tip", "trigger" ] expect(opentip.options.hideTriggers).to.eql [ "tip", "trigger" ] it "should attach itself to the elements `data-opentips` property", -> element = $("<div></div>")[0] expect(adapter.data element, "opentips").to.not.be.ok() opentip = new Opentip element expect(adapter.data element, "opentips").to.eql [ opentip ] opentip2 = new Opentip element opentip3 = new Opentip element expect(adapter.data element, "opentips").to.eql [ opentip, opentip2, opentip3 ] it "should add itself to the Opentip.tips list", -> element = $("<div></div>")[0] Opentip.tips = [ ] opentip1 = new Opentip element opentip2 = new Opentip element expect(Opentip.tips.length).to.equal 2 expect(Opentip.tips[0]).to.equal opentip1 expect(Opentip.tips[1]).to.equal opentip2 it "should rename ajaxCache to cache for backwards compatibility", -> element = $("<div></div>")[0] opentip1 = new Opentip element, ajaxCache: off opentip2 = new Opentip element, ajaxCache: on expect(opentip1.options.ajaxCache == opentip2.options.ajaxCache == undefined).to.be.ok() expect(opentip1.options.cache).to.not.be.ok() expect(opentip2.options.cache).to.be.ok() describe "init()", -> describe "showOn == creation", -> element = document.createElement "div" beforeEach -> sinon.stub Opentip::, "prepareToShow" afterEach -> Opentip::prepareToShow.restore() it "should immediately call prepareToShow()", -> opentip = new Opentip element, showOn: "creation" expect(opentip.prepareToShow.callCount).to.equal 1 describe "setContent()", -> it "should update the content if tooltip currently visible", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip, "_updateElementContent" opentip.visible = no opentip.setContent "TEST" expect(opentip.content).to.equal "TEST" opentip.visible = yes opentip.setContent "TEST2" expect(opentip.content).to.equal "TEST2" expect(opentip._updateElementContent.callCount).to.equal 1 opentip._updateElementContent.restore() it "should not set the content directly if function", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip, "_updateElementContent" opentip.setContent -> "TEST" expect(opentip.content).to.equal "" describe "_updateElementContent()", -> it "should escape the content if @options.escapeContent", -> element = document.createElement "div" opentip = new Opentip element, "<div><span></span></div>", escapeContent: yes sinon.stub opentip, "_triggerElementExists", -> yes opentip.show() expect($(opentip.container).find(".ot-content").html()).to.be """&lt;div&gt;&lt;span&gt;&lt;/span&gt;&lt;/div&gt;""" it "should not escape the content if not @options.escapeContent", -> element = document.createElement "div" opentip = new Opentip element, "<div><span></span></div>", escapeContent: no sinon.stub opentip, "_triggerElementExists", -> yes opentip.show() expect($(opentip.container).find(".ot-content > div > span").length).to.be 1 it "should storeAndLock dimensions and reposition the element", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip, "_storeAndLockDimensions" sinon.stub opentip, "reposition" opentip.visible = yes opentip._updateElementContent() expect(opentip._storeAndLockDimensions.callCount).to.equal 1 expect(opentip.reposition.callCount).to.equal 1 it "should execute the content function", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip.adapter, "find", -> "element" opentip.visible = yes opentip.setContent -> "BLA TEST" expect(opentip.content).to.be "BLA TEST" opentip.adapter.find.restore() it "should only execute the content function once if cache:true", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click", cache: yes sinon.stub opentip.adapter, "find", -> "element" opentip.visible = yes counter = 0 opentip.setContent -> "count#{counter++}" expect(opentip.content).to.be "count0" opentip._updateElementContent() opentip._updateElementContent() expect(opentip.content).to.be "count0" opentip.adapter.find.restore() it "should execute the content function multiple times if cache:false", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click", cache: no sinon.stub opentip.adapter, "find", -> "element" opentip.visible = yes counter = 0 opentip.setContent -> "count#{counter++}" expect(opentip.content).to.be "count0" opentip._updateElementContent() opentip._updateElementContent() expect(opentip.content).to.be "count2" opentip.adapter.find.restore() it "should only update the HTML elements if the content has been changed", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip.adapter, "find", -> "element" sinon.stub opentip.adapter, "update", -> opentip.visible = yes opentip.setContent "TEST" expect(opentip.adapter.update.callCount).to.be 1 opentip._updateElementContent() opentip._updateElementContent() expect(opentip.adapter.update.callCount).to.be 1 opentip.setContent "TEST2" expect(opentip.adapter.update.callCount).to.be 2 opentip.adapter.find.restore() opentip.adapter.update.restore() describe "_buildContainer()", -> element = document.createElement "div" opentip = null beforeEach -> opentip = new Opentip element, style: "glass" showEffect: "appear" hideEffect: "fade" opentip._setup() it "should set the id", -> expect(adapter.attr opentip.container, "id").to.equal "opentip-" + opentip.id it "should set the classes", -> enderElement = $ adapter.unwrap opentip.container expect(enderElement.hasClass "opentip-container").to.be.ok() expect(enderElement.hasClass "ot-hidden").to.be.ok() expect(enderElement.hasClass "style-glass").to.be.ok() expect(enderElement.hasClass "ot-show-effect-appear").to.be.ok() expect(enderElement.hasClass "ot-hide-effect-fade").to.be.ok() describe "_buildElements()", -> element = opentip = null beforeEach -> element = document.createElement "div" opentip = new Opentip element, "the content", "the title", hideTrigger: "closeButton", stem: "top left", ajax: "bla" opentip._setup() opentip._buildElements() it "should add a h1 if title is provided", -> enderElement = $ adapter.unwrap opentip.container headerElement = enderElement.find "> .opentip > .ot-header > h1" expect(headerElement.length).to.be.ok() expect(headerElement.html()).to.be "the title" it "should add a loading indicator if ajax", -> enderElement = $ adapter.unwrap opentip.container loadingElement = enderElement.find "> .opentip > .ot-loading-indicator > span" expect(loadingElement.length).to.be.ok() expect(loadingElement.html()).to.be "↻" it "should add a close button if hideTrigger = close", -> enderElement = $ adapter.unwrap opentip.container closeButton = enderElement.find "> .opentip > .ot-header > a.ot-close > span" expect(closeButton.length).to.be.ok() expect(closeButton.html()).to.be "Close" describe "addAdapter()", -> it "should set the current adapter, and add the adapter to the list", -> expect(Opentip.adapters.testa).to.not.be.ok() testAdapter = { name: "testa" } Opentip.addAdapter testAdapter expect(Opentip.adapters.testa).to.equal testAdapter it "should use adapter.domReady to call findElements() with it" describe "_setupObservers()", -> it "should never setup the same observers twice" describe "_searchAndActivateCloseButtons()", -> it "should do what it says" describe "_activateFirstInput()", -> it "should do what it says", -> element = document.createElement "div" opentip = new Opentip element, "<input /><textarea>", escapeContent: false sinon.stub opentip, "_triggerElementExists", -> yes opentip.show() input = $("input", opentip.container)[0] expect(document.activeElement).to.not.be input opentip._activateFirstInput() input.focus() expect(document.activeElement).to.be input
200564
$ = jQuery describe "Opentip", -> adapter = null beforeEach -> adapter = Opentip.adapter afterEach -> elements = $(".opentip-container") elements.remove() describe "constructor()", -> before -> sinon.stub Opentip::, "_setup" after -> Opentip::_setup.restore() it "arguments should be optional", -> element = adapter.create "<div></div>" opentip = new Opentip element, "content" expect(opentip.content).to.equal "content" expect(adapter.unwrap(opentip.triggerElement)).to.equal adapter.unwrap element opentip = new Opentip element, "content", "title", { hideOn: "click" } expect(opentip.content).to.equal "content" expect(adapter.unwrap opentip.triggerElement).to.equal adapter.unwrap element expect(opentip.options.hideOn).to.equal "click" expect(opentip.options.title).to.equal "title" opentip = new Opentip element, { hideOn: "click" } expect(adapter.unwrap opentip.triggerElement).to.equal adapter.unwrap element expect(opentip.options.hideOn).to.equal "click" expect(opentip.content).to.equal "" expect(opentip.options.title).to.equal undefined it "should always use the next tip id", -> element = document.createElement "div" Opentip.lastId = 0 opentip = new Opentip element, "Test" opentip2 = new Opentip element, "Test" opentip3 = new Opentip element, "Test" expect(opentip.id).to.be 1 expect(opentip2.id).to.be 2 expect(opentip3.id).to.be 3 it "should use the href attribute if AJAX and an A element", -> element = $("""<a href="http://testlink">link</a>""")[0] opentip = new Opentip element, ajax: on expect(opentip.options.ajax).to.equal "http://testlink" it "should disable AJAX if neither URL or a link HREF is provided", -> element = $("""<div>text</div>""")[0] opentip = new Opentip element, ajax: on expect(opentip.options.ajax).to.be false it "should disable a link if the event is onClick", -> sinon.stub adapter, "observe" element = $("""<a href="http://testlink">link</a>""")[0] sinon.stub Opentip::, "_setupObservers" opentip = new Opentip element, showOn: "click" expect(adapter.observe.calledOnce).to.be.ok() expect(adapter.observe.getCall(0).args[1]).to.equal "click" Opentip::_setupObservers.restore() adapter.observe.restore() it "should take all options from selected style", -> element = document.createElement "div" opentip = new Opentip element, style: "glass", showOn: "click" # Should have been set by the options expect(opentip.options.showOn).to.equal "click" # Should have been set by the glass theme expect(opentip.options.className).to.equal "glass" # Should have been set by the standard theme expect(opentip.options.stemLength).to.equal 5 it "the property 'style' should be handled the same as 'extends'", -> element = document.createElement "div" opentip = new Opentip element, extends: "glass", showOn: "click" # Should have been set by the options expect(opentip.options.showOn).to.equal "click" # Should have been set by the glass theme expect(opentip.options.className).to.equal "glass" # Should have been set by the standard theme expect(opentip.options.stemLength).to.equal 5 it "chaining incorrect styles should throw an exception", -> element = document.createElement "div" expect(-> new Opentip element, { extends: "invalidstyle" }).to.throwException /Invalid style\: invalidstyle/ it "chaining styles should work", -> element = document.createElement "div" Opentip.styles.test1 = stemLength: 40 Opentip.styles.test2 = extends: "test1", title: "overwritten title" Opentip.styles.test3 = extends: "test2", className: "test5", title: "some title" opentip = new Opentip element, { extends: "test3", stemBase: 20 } expect(opentip.options.className).to.equal "test5" expect(opentip.options.title).to.equal "some title" expect(opentip.options.stemLength).to.equal 40 expect(opentip.options.stemBase).to.equal 20 it "should set the options to fixed if a target is provided", -> element = document.createElement "div" opentip = new Opentip element, target: yes, fixed: no expect(opentip.options.fixed).to.be.ok() it "should use provided stem", -> element = document.createElement "div" opentip = new Opentip element, stem: "bottom", tipJoin: "topLeft" expect(opentip.options.stem.toString()).to.eql "bottom" it "should take the tipJoint as stem if stem is just true", -> element = document.createElement "div" opentip = new Opentip element, stem: yes, tipJoint: "top left" expect(opentip.options.stem.toString()).to.eql "top left" it "should use provided target", -> element = adapter.create "<div></div>" element2 = adapter.create "<div></div>" opentip = new Opentip element, target: element2 expect(adapter.unwrap opentip.options.target).to.equal adapter.unwrap element2 it "should take the triggerElement as target if target is just true", -> element = adapter.create "<div></div>" opentip = new Opentip element, target: yes expect(adapter.unwrap opentip.options.target).to.equal adapter.unwrap element it "currentStemPosition should be set to inital stemPosition", -> element = adapter.create "<div></div>" opentip = new Opentip element, stem: "topLeft" expect(opentip.currentStem.toString()).to.eql "top left" it "delay should be automatically set if none provided", -> element = document.createElement "div" opentip = new Opentip element, delay: null, showOn: "click" expect(opentip.options.delay).to.equal 0 opentip = new Opentip element, delay: null, showOn: "mouseover" expect(opentip.options.delay).to.equal 0.2 it "the targetJoint should be the inverse of the tipJoint if none provided", -> element = document.createElement "div" opentip = new Opentip element, tipJoint: "left" expect(opentip.options.targetJoint.toString()).to.eql "right" opentip = new Opentip element, tipJoint: "top" expect(opentip.options.targetJoint.toString()).to.eql "bottom" opentip = new Opentip element, tipJoint: "bottom right" expect(opentip.options.targetJoint.toString()).to.eql "top left" it "should setup all trigger elements", -> element = adapter.create "<div></div>" opentip = new Opentip element, showOn: "click" expect(opentip.showTriggers[0].event).to.eql "click" expect(adapter.unwrap opentip.showTriggers[0].element).to.equal adapter.unwrap element expect(opentip.showTriggersWhenVisible).to.eql [ ] expect(opentip.hideTriggers).to.eql [ ] opentip = new Opentip element, showOn: "creation" expect(opentip.showTriggers).to.eql [ ] expect(opentip.showTriggersWhenVisible).to.eql [ ] expect(opentip.hideTriggers).to.eql [ ] it "should copy options.hideTrigger onto options.hideTriggers", -> element = adapter.create "<div></div>" opentip = new Opentip element, hideTrigger: "closeButton", hideTriggers: [ ] expect(opentip.options.hideTriggers).to.eql [ "closeButton"] it "should NOT copy options.hideTrigger onto options.hideTriggers when hideTriggers are set", -> element = adapter.create "<div></div>" opentip = new Opentip element, hideTrigger: "closeButton", hideTriggers: [ "tip", "trigger" ] expect(opentip.options.hideTriggers).to.eql [ "tip", "trigger" ] it "should attach itself to the elements `data-opentips` property", -> element = $("<div></div>")[0] expect(adapter.data element, "opentips").to.not.be.ok() opentip = new Opentip element expect(adapter.data element, "opentips").to.eql [ opentip ] opentip2 = new Opentip element opentip3 = new Opentip element expect(adapter.data element, "opentips").to.eql [ opentip, opentip2, opentip3 ] it "should add itself to the Opentip.tips list", -> element = $("<div></div>")[0] Opentip.tips = [ ] opentip1 = new Opentip element opentip2 = new Opentip element expect(Opentip.tips.length).to.equal 2 expect(Opentip.tips[0]).to.equal opentip1 expect(Opentip.tips[1]).to.equal opentip2 it "should rename ajaxCache to cache for backwards compatibility", -> element = $("<div></div>")[0] opentip1 = new Opentip element, ajaxCache: off opentip2 = new Opentip element, ajaxCache: on expect(opentip1.options.ajaxCache == opentip2.options.ajaxCache == undefined).to.be.ok() expect(opentip1.options.cache).to.not.be.ok() expect(opentip2.options.cache).to.be.ok() describe "init()", -> describe "showOn == creation", -> element = document.createElement "div" beforeEach -> sinon.stub Opentip::, "prepareToShow" afterEach -> Opentip::prepareToShow.restore() it "should immediately call prepareToShow()", -> opentip = new Opentip element, showOn: "creation" expect(opentip.prepareToShow.callCount).to.equal 1 describe "setContent()", -> it "should update the content if tooltip currently visible", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip, "_updateElementContent" opentip.visible = no opentip.setContent "TEST" expect(opentip.content).to.equal "TEST" opentip.visible = yes opentip.setContent "TEST2" expect(opentip.content).to.equal "TEST2" expect(opentip._updateElementContent.callCount).to.equal 1 opentip._updateElementContent.restore() it "should not set the content directly if function", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip, "_updateElementContent" opentip.setContent -> "TEST" expect(opentip.content).to.equal "" describe "_updateElementContent()", -> it "should escape the content if @options.escapeContent", -> element = document.createElement "div" opentip = new Opentip element, "<div><span></span></div>", escapeContent: yes sinon.stub opentip, "_triggerElementExists", -> yes opentip.show() expect($(opentip.container).find(".ot-content").html()).to.be """&lt;div&gt;&lt;span&gt;&lt;/span&gt;&lt;/div&gt;""" it "should not escape the content if not @options.escapeContent", -> element = document.createElement "div" opentip = new Opentip element, "<div><span></span></div>", escapeContent: no sinon.stub opentip, "_triggerElementExists", -> yes opentip.show() expect($(opentip.container).find(".ot-content > div > span").length).to.be 1 it "should storeAndLock dimensions and reposition the element", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip, "_storeAndLockDimensions" sinon.stub opentip, "reposition" opentip.visible = yes opentip._updateElementContent() expect(opentip._storeAndLockDimensions.callCount).to.equal 1 expect(opentip.reposition.callCount).to.equal 1 it "should execute the content function", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip.adapter, "find", -> "element" opentip.visible = yes opentip.setContent -> "BLA TEST" expect(opentip.content).to.be "BLA TEST" opentip.adapter.find.restore() it "should only execute the content function once if cache:true", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click", cache: yes sinon.stub opentip.adapter, "find", -> "element" opentip.visible = yes counter = 0 opentip.setContent -> "count#{counter++}" expect(opentip.content).to.be "count0" opentip._updateElementContent() opentip._updateElementContent() expect(opentip.content).to.be "count0" opentip.adapter.find.restore() it "should execute the content function multiple times if cache:false", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click", cache: no sinon.stub opentip.adapter, "find", -> "element" opentip.visible = yes counter = 0 opentip.setContent -> "count#{counter++}" expect(opentip.content).to.be "count0" opentip._updateElementContent() opentip._updateElementContent() expect(opentip.content).to.be "count2" opentip.adapter.find.restore() it "should only update the HTML elements if the content has been changed", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip.adapter, "find", -> "element" sinon.stub opentip.adapter, "update", -> opentip.visible = yes opentip.setContent "TEST" expect(opentip.adapter.update.callCount).to.be 1 opentip._updateElementContent() opentip._updateElementContent() expect(opentip.adapter.update.callCount).to.be 1 opentip.setContent "TEST2" expect(opentip.adapter.update.callCount).to.be 2 opentip.adapter.find.restore() opentip.adapter.update.restore() describe "_buildContainer()", -> element = document.createElement "div" opentip = null beforeEach -> opentip = new Opentip element, style: "glass" showEffect: "appear" hideEffect: "fade" opentip._setup() it "should set the id", -> expect(adapter.attr opentip.container, "id").to.equal "opentip-" + opentip.id it "should set the classes", -> enderElement = $ adapter.unwrap opentip.container expect(enderElement.hasClass "opentip-container").to.be.ok() expect(enderElement.hasClass "ot-hidden").to.be.ok() expect(enderElement.hasClass "style-glass").to.be.ok() expect(enderElement.hasClass "ot-show-effect-appear").to.be.ok() expect(enderElement.hasClass "ot-hide-effect-fade").to.be.ok() describe "_buildElements()", -> element = opentip = null beforeEach -> element = document.createElement "div" opentip = new Opentip element, "the content", "the title", hideTrigger: "closeButton", stem: "top left", ajax: "bla" opentip._setup() opentip._buildElements() it "should add a h1 if title is provided", -> enderElement = $ adapter.unwrap opentip.container headerElement = enderElement.find "> .opentip > .ot-header > h1" expect(headerElement.length).to.be.ok() expect(headerElement.html()).to.be "the title" it "should add a loading indicator if ajax", -> enderElement = $ adapter.unwrap opentip.container loadingElement = enderElement.find "> .opentip > .ot-loading-indicator > span" expect(loadingElement.length).to.be.ok() expect(loadingElement.html()).to.be "↻" it "should add a close button if hideTrigger = close", -> enderElement = $ adapter.unwrap opentip.container closeButton = enderElement.find "> .opentip > .ot-header > a.ot-close > span" expect(closeButton.length).to.be.ok() expect(closeButton.html()).to.be "Close" describe "addAdapter()", -> it "should set the current adapter, and add the adapter to the list", -> expect(Opentip.adapters.testa).to.not.be.ok() testAdapter = { name: "<NAME>" } Opentip.addAdapter testAdapter expect(Opentip.adapters.testa).to.equal testAdapter it "should use adapter.domReady to call findElements() with it" describe "_setupObservers()", -> it "should never setup the same observers twice" describe "_searchAndActivateCloseButtons()", -> it "should do what it says" describe "_activateFirstInput()", -> it "should do what it says", -> element = document.createElement "div" opentip = new Opentip element, "<input /><textarea>", escapeContent: false sinon.stub opentip, "_triggerElementExists", -> yes opentip.show() input = $("input", opentip.container)[0] expect(document.activeElement).to.not.be input opentip._activateFirstInput() input.focus() expect(document.activeElement).to.be input
true
$ = jQuery describe "Opentip", -> adapter = null beforeEach -> adapter = Opentip.adapter afterEach -> elements = $(".opentip-container") elements.remove() describe "constructor()", -> before -> sinon.stub Opentip::, "_setup" after -> Opentip::_setup.restore() it "arguments should be optional", -> element = adapter.create "<div></div>" opentip = new Opentip element, "content" expect(opentip.content).to.equal "content" expect(adapter.unwrap(opentip.triggerElement)).to.equal adapter.unwrap element opentip = new Opentip element, "content", "title", { hideOn: "click" } expect(opentip.content).to.equal "content" expect(adapter.unwrap opentip.triggerElement).to.equal adapter.unwrap element expect(opentip.options.hideOn).to.equal "click" expect(opentip.options.title).to.equal "title" opentip = new Opentip element, { hideOn: "click" } expect(adapter.unwrap opentip.triggerElement).to.equal adapter.unwrap element expect(opentip.options.hideOn).to.equal "click" expect(opentip.content).to.equal "" expect(opentip.options.title).to.equal undefined it "should always use the next tip id", -> element = document.createElement "div" Opentip.lastId = 0 opentip = new Opentip element, "Test" opentip2 = new Opentip element, "Test" opentip3 = new Opentip element, "Test" expect(opentip.id).to.be 1 expect(opentip2.id).to.be 2 expect(opentip3.id).to.be 3 it "should use the href attribute if AJAX and an A element", -> element = $("""<a href="http://testlink">link</a>""")[0] opentip = new Opentip element, ajax: on expect(opentip.options.ajax).to.equal "http://testlink" it "should disable AJAX if neither URL or a link HREF is provided", -> element = $("""<div>text</div>""")[0] opentip = new Opentip element, ajax: on expect(opentip.options.ajax).to.be false it "should disable a link if the event is onClick", -> sinon.stub adapter, "observe" element = $("""<a href="http://testlink">link</a>""")[0] sinon.stub Opentip::, "_setupObservers" opentip = new Opentip element, showOn: "click" expect(adapter.observe.calledOnce).to.be.ok() expect(adapter.observe.getCall(0).args[1]).to.equal "click" Opentip::_setupObservers.restore() adapter.observe.restore() it "should take all options from selected style", -> element = document.createElement "div" opentip = new Opentip element, style: "glass", showOn: "click" # Should have been set by the options expect(opentip.options.showOn).to.equal "click" # Should have been set by the glass theme expect(opentip.options.className).to.equal "glass" # Should have been set by the standard theme expect(opentip.options.stemLength).to.equal 5 it "the property 'style' should be handled the same as 'extends'", -> element = document.createElement "div" opentip = new Opentip element, extends: "glass", showOn: "click" # Should have been set by the options expect(opentip.options.showOn).to.equal "click" # Should have been set by the glass theme expect(opentip.options.className).to.equal "glass" # Should have been set by the standard theme expect(opentip.options.stemLength).to.equal 5 it "chaining incorrect styles should throw an exception", -> element = document.createElement "div" expect(-> new Opentip element, { extends: "invalidstyle" }).to.throwException /Invalid style\: invalidstyle/ it "chaining styles should work", -> element = document.createElement "div" Opentip.styles.test1 = stemLength: 40 Opentip.styles.test2 = extends: "test1", title: "overwritten title" Opentip.styles.test3 = extends: "test2", className: "test5", title: "some title" opentip = new Opentip element, { extends: "test3", stemBase: 20 } expect(opentip.options.className).to.equal "test5" expect(opentip.options.title).to.equal "some title" expect(opentip.options.stemLength).to.equal 40 expect(opentip.options.stemBase).to.equal 20 it "should set the options to fixed if a target is provided", -> element = document.createElement "div" opentip = new Opentip element, target: yes, fixed: no expect(opentip.options.fixed).to.be.ok() it "should use provided stem", -> element = document.createElement "div" opentip = new Opentip element, stem: "bottom", tipJoin: "topLeft" expect(opentip.options.stem.toString()).to.eql "bottom" it "should take the tipJoint as stem if stem is just true", -> element = document.createElement "div" opentip = new Opentip element, stem: yes, tipJoint: "top left" expect(opentip.options.stem.toString()).to.eql "top left" it "should use provided target", -> element = adapter.create "<div></div>" element2 = adapter.create "<div></div>" opentip = new Opentip element, target: element2 expect(adapter.unwrap opentip.options.target).to.equal adapter.unwrap element2 it "should take the triggerElement as target if target is just true", -> element = adapter.create "<div></div>" opentip = new Opentip element, target: yes expect(adapter.unwrap opentip.options.target).to.equal adapter.unwrap element it "currentStemPosition should be set to inital stemPosition", -> element = adapter.create "<div></div>" opentip = new Opentip element, stem: "topLeft" expect(opentip.currentStem.toString()).to.eql "top left" it "delay should be automatically set if none provided", -> element = document.createElement "div" opentip = new Opentip element, delay: null, showOn: "click" expect(opentip.options.delay).to.equal 0 opentip = new Opentip element, delay: null, showOn: "mouseover" expect(opentip.options.delay).to.equal 0.2 it "the targetJoint should be the inverse of the tipJoint if none provided", -> element = document.createElement "div" opentip = new Opentip element, tipJoint: "left" expect(opentip.options.targetJoint.toString()).to.eql "right" opentip = new Opentip element, tipJoint: "top" expect(opentip.options.targetJoint.toString()).to.eql "bottom" opentip = new Opentip element, tipJoint: "bottom right" expect(opentip.options.targetJoint.toString()).to.eql "top left" it "should setup all trigger elements", -> element = adapter.create "<div></div>" opentip = new Opentip element, showOn: "click" expect(opentip.showTriggers[0].event).to.eql "click" expect(adapter.unwrap opentip.showTriggers[0].element).to.equal adapter.unwrap element expect(opentip.showTriggersWhenVisible).to.eql [ ] expect(opentip.hideTriggers).to.eql [ ] opentip = new Opentip element, showOn: "creation" expect(opentip.showTriggers).to.eql [ ] expect(opentip.showTriggersWhenVisible).to.eql [ ] expect(opentip.hideTriggers).to.eql [ ] it "should copy options.hideTrigger onto options.hideTriggers", -> element = adapter.create "<div></div>" opentip = new Opentip element, hideTrigger: "closeButton", hideTriggers: [ ] expect(opentip.options.hideTriggers).to.eql [ "closeButton"] it "should NOT copy options.hideTrigger onto options.hideTriggers when hideTriggers are set", -> element = adapter.create "<div></div>" opentip = new Opentip element, hideTrigger: "closeButton", hideTriggers: [ "tip", "trigger" ] expect(opentip.options.hideTriggers).to.eql [ "tip", "trigger" ] it "should attach itself to the elements `data-opentips` property", -> element = $("<div></div>")[0] expect(adapter.data element, "opentips").to.not.be.ok() opentip = new Opentip element expect(adapter.data element, "opentips").to.eql [ opentip ] opentip2 = new Opentip element opentip3 = new Opentip element expect(adapter.data element, "opentips").to.eql [ opentip, opentip2, opentip3 ] it "should add itself to the Opentip.tips list", -> element = $("<div></div>")[0] Opentip.tips = [ ] opentip1 = new Opentip element opentip2 = new Opentip element expect(Opentip.tips.length).to.equal 2 expect(Opentip.tips[0]).to.equal opentip1 expect(Opentip.tips[1]).to.equal opentip2 it "should rename ajaxCache to cache for backwards compatibility", -> element = $("<div></div>")[0] opentip1 = new Opentip element, ajaxCache: off opentip2 = new Opentip element, ajaxCache: on expect(opentip1.options.ajaxCache == opentip2.options.ajaxCache == undefined).to.be.ok() expect(opentip1.options.cache).to.not.be.ok() expect(opentip2.options.cache).to.be.ok() describe "init()", -> describe "showOn == creation", -> element = document.createElement "div" beforeEach -> sinon.stub Opentip::, "prepareToShow" afterEach -> Opentip::prepareToShow.restore() it "should immediately call prepareToShow()", -> opentip = new Opentip element, showOn: "creation" expect(opentip.prepareToShow.callCount).to.equal 1 describe "setContent()", -> it "should update the content if tooltip currently visible", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip, "_updateElementContent" opentip.visible = no opentip.setContent "TEST" expect(opentip.content).to.equal "TEST" opentip.visible = yes opentip.setContent "TEST2" expect(opentip.content).to.equal "TEST2" expect(opentip._updateElementContent.callCount).to.equal 1 opentip._updateElementContent.restore() it "should not set the content directly if function", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip, "_updateElementContent" opentip.setContent -> "TEST" expect(opentip.content).to.equal "" describe "_updateElementContent()", -> it "should escape the content if @options.escapeContent", -> element = document.createElement "div" opentip = new Opentip element, "<div><span></span></div>", escapeContent: yes sinon.stub opentip, "_triggerElementExists", -> yes opentip.show() expect($(opentip.container).find(".ot-content").html()).to.be """&lt;div&gt;&lt;span&gt;&lt;/span&gt;&lt;/div&gt;""" it "should not escape the content if not @options.escapeContent", -> element = document.createElement "div" opentip = new Opentip element, "<div><span></span></div>", escapeContent: no sinon.stub opentip, "_triggerElementExists", -> yes opentip.show() expect($(opentip.container).find(".ot-content > div > span").length).to.be 1 it "should storeAndLock dimensions and reposition the element", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip, "_storeAndLockDimensions" sinon.stub opentip, "reposition" opentip.visible = yes opentip._updateElementContent() expect(opentip._storeAndLockDimensions.callCount).to.equal 1 expect(opentip.reposition.callCount).to.equal 1 it "should execute the content function", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip.adapter, "find", -> "element" opentip.visible = yes opentip.setContent -> "BLA TEST" expect(opentip.content).to.be "BLA TEST" opentip.adapter.find.restore() it "should only execute the content function once if cache:true", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click", cache: yes sinon.stub opentip.adapter, "find", -> "element" opentip.visible = yes counter = 0 opentip.setContent -> "count#{counter++}" expect(opentip.content).to.be "count0" opentip._updateElementContent() opentip._updateElementContent() expect(opentip.content).to.be "count0" opentip.adapter.find.restore() it "should execute the content function multiple times if cache:false", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click", cache: no sinon.stub opentip.adapter, "find", -> "element" opentip.visible = yes counter = 0 opentip.setContent -> "count#{counter++}" expect(opentip.content).to.be "count0" opentip._updateElementContent() opentip._updateElementContent() expect(opentip.content).to.be "count2" opentip.adapter.find.restore() it "should only update the HTML elements if the content has been changed", -> element = document.createElement "div" opentip = new Opentip element, showOn: "click" sinon.stub opentip.adapter, "find", -> "element" sinon.stub opentip.adapter, "update", -> opentip.visible = yes opentip.setContent "TEST" expect(opentip.adapter.update.callCount).to.be 1 opentip._updateElementContent() opentip._updateElementContent() expect(opentip.adapter.update.callCount).to.be 1 opentip.setContent "TEST2" expect(opentip.adapter.update.callCount).to.be 2 opentip.adapter.find.restore() opentip.adapter.update.restore() describe "_buildContainer()", -> element = document.createElement "div" opentip = null beforeEach -> opentip = new Opentip element, style: "glass" showEffect: "appear" hideEffect: "fade" opentip._setup() it "should set the id", -> expect(adapter.attr opentip.container, "id").to.equal "opentip-" + opentip.id it "should set the classes", -> enderElement = $ adapter.unwrap opentip.container expect(enderElement.hasClass "opentip-container").to.be.ok() expect(enderElement.hasClass "ot-hidden").to.be.ok() expect(enderElement.hasClass "style-glass").to.be.ok() expect(enderElement.hasClass "ot-show-effect-appear").to.be.ok() expect(enderElement.hasClass "ot-hide-effect-fade").to.be.ok() describe "_buildElements()", -> element = opentip = null beforeEach -> element = document.createElement "div" opentip = new Opentip element, "the content", "the title", hideTrigger: "closeButton", stem: "top left", ajax: "bla" opentip._setup() opentip._buildElements() it "should add a h1 if title is provided", -> enderElement = $ adapter.unwrap opentip.container headerElement = enderElement.find "> .opentip > .ot-header > h1" expect(headerElement.length).to.be.ok() expect(headerElement.html()).to.be "the title" it "should add a loading indicator if ajax", -> enderElement = $ adapter.unwrap opentip.container loadingElement = enderElement.find "> .opentip > .ot-loading-indicator > span" expect(loadingElement.length).to.be.ok() expect(loadingElement.html()).to.be "↻" it "should add a close button if hideTrigger = close", -> enderElement = $ adapter.unwrap opentip.container closeButton = enderElement.find "> .opentip > .ot-header > a.ot-close > span" expect(closeButton.length).to.be.ok() expect(closeButton.html()).to.be "Close" describe "addAdapter()", -> it "should set the current adapter, and add the adapter to the list", -> expect(Opentip.adapters.testa).to.not.be.ok() testAdapter = { name: "PI:NAME:<NAME>END_PI" } Opentip.addAdapter testAdapter expect(Opentip.adapters.testa).to.equal testAdapter it "should use adapter.domReady to call findElements() with it" describe "_setupObservers()", -> it "should never setup the same observers twice" describe "_searchAndActivateCloseButtons()", -> it "should do what it says" describe "_activateFirstInput()", -> it "should do what it says", -> element = document.createElement "div" opentip = new Opentip element, "<input /><textarea>", escapeContent: false sinon.stub opentip, "_triggerElementExists", -> yes opentip.show() input = $("input", opentip.container)[0] expect(document.activeElement).to.not.be input opentip._activateFirstInput() input.focus() expect(document.activeElement).to.be input
[ { "context": "'handles unicode strings', (done) ->\n KEY = 'string'\n url_parts = URL.parse(MODEL_URL, true); _.", "end": 1394, "score": 0.5929843187332153, "start": 1388, "tag": "KEY", "value": "string" }, { "context": " 'handles number strings', (done) ->\n KEY = 'number_string'\n url_parts = URL.parse(MODEL_URL, true); _.", "end": 1869, "score": 0.9968107342720032, "start": 1856, "tag": "KEY", "value": "number_string" }, { "context": "\n it 'handles numbers', (done) ->\n KEY = 'number'\n url_parts = URL.parse(MODEL_URL, true); _.", "end": 2330, "score": 0.9412261247634888, "start": 2324, "tag": "KEY", "value": "number" } ]
test/spec/lib/json_utils.tests.coffee
dk-dev/backbone-orm
54
assert = assert or require?('chai').assert BackboneORM = window?.BackboneORM; try BackboneORM or= require?('backbone-orm') catch; try BackboneORM or= require?('../../../../backbone-orm') {_, JSONUtils} = BackboneORM URL = BackboneORM.modules.url VALUES = date: new Date() string: "日本語" number: 123456789 number_string: "123456789" number2: 123456789e21 number2_string: '123456789e21' object: date: new Date() string: "日本語" number: 123456789 array: [new Date(), "日本語", 123456789e21, "123456789e21"] MODEL_URL = 'https://things/1' describe 'JSONUtils @quick @json', -> it 'parse maintains types correctly', (done) -> parsed_json = JSONUtils.parseQuery(JSONUtils.querify(VALUES)) assert.deepEqual(parsed_json, VALUES) done() it 'querify handles control directives', (done) -> query = {$limit: 1, $one: true, $hello: 'abc', $sort: ['name'], $id: {$in: [1, '2']}} parsed_query = {$limit: 1, $one: true, $hello: 'abc', $sort: ['name'], $id: {$in: [1, '2']}} assert.deepEqual(JSONUtils.parseQuery(JSONUtils.querify(query)), parsed_query, 'matches without extra JSON operations') assert.deepEqual(JSONUtils.parseQuery(JSON.parse(JSON.stringify(JSONUtils.querify(query)))), parsed_query, 'matches with extra JSON operations') done() describe 'Strict JSON in URL', -> it 'handles unicode strings', (done) -> KEY = 'string' url_parts = URL.parse(MODEL_URL, true); _.extend(url_parts.query, JSONUtils.querify(_.pick(VALUES, KEY))); url = URL.format(url_parts) assert.equal(url, "#{MODEL_URL}?#{KEY}=#{encodeURIComponent('"' + VALUES[KEY] + '"')}", 'URL has string') url_parts = URL.parse(url, true) assert.equal(JSONUtils.parseQuery(url_parts.query)[KEY], VALUES[KEY], 'Same type returned') done() it 'handles number strings', (done) -> KEY = 'number_string' url_parts = URL.parse(MODEL_URL, true); _.extend(url_parts.query, JSONUtils.querify(_.pick(VALUES, KEY))); url = URL.format(url_parts) assert.equal(url, "#{MODEL_URL}?#{KEY}=#{encodeURIComponent('"' + VALUES[KEY] + '"')}", 'URL has string') url_parts = URL.parse(url, true) assert.equal(JSONUtils.parseQuery(url_parts.query)[KEY], VALUES[KEY], 'Same type returned') done() it 'handles numbers', (done) -> KEY = 'number' url_parts = URL.parse(MODEL_URL, true); _.extend(url_parts.query, JSONUtils.querify(_.pick(VALUES, KEY))); url = URL.format(url_parts) assert.equal(url, "#{MODEL_URL}?#{KEY}=#{encodeURIComponent(VALUES[KEY])}", 'URL has number') url_parts = URL.parse(url, true) assert.equal(JSONUtils.parseQuery(url_parts.query)[KEY], VALUES[KEY], 'Same type returned') done()
194810
assert = assert or require?('chai').assert BackboneORM = window?.BackboneORM; try BackboneORM or= require?('backbone-orm') catch; try BackboneORM or= require?('../../../../backbone-orm') {_, JSONUtils} = BackboneORM URL = BackboneORM.modules.url VALUES = date: new Date() string: "日本語" number: 123456789 number_string: "123456789" number2: 123456789e21 number2_string: '123456789e21' object: date: new Date() string: "日本語" number: 123456789 array: [new Date(), "日本語", 123456789e21, "123456789e21"] MODEL_URL = 'https://things/1' describe 'JSONUtils @quick @json', -> it 'parse maintains types correctly', (done) -> parsed_json = JSONUtils.parseQuery(JSONUtils.querify(VALUES)) assert.deepEqual(parsed_json, VALUES) done() it 'querify handles control directives', (done) -> query = {$limit: 1, $one: true, $hello: 'abc', $sort: ['name'], $id: {$in: [1, '2']}} parsed_query = {$limit: 1, $one: true, $hello: 'abc', $sort: ['name'], $id: {$in: [1, '2']}} assert.deepEqual(JSONUtils.parseQuery(JSONUtils.querify(query)), parsed_query, 'matches without extra JSON operations') assert.deepEqual(JSONUtils.parseQuery(JSON.parse(JSON.stringify(JSONUtils.querify(query)))), parsed_query, 'matches with extra JSON operations') done() describe 'Strict JSON in URL', -> it 'handles unicode strings', (done) -> KEY = '<KEY>' url_parts = URL.parse(MODEL_URL, true); _.extend(url_parts.query, JSONUtils.querify(_.pick(VALUES, KEY))); url = URL.format(url_parts) assert.equal(url, "#{MODEL_URL}?#{KEY}=#{encodeURIComponent('"' + VALUES[KEY] + '"')}", 'URL has string') url_parts = URL.parse(url, true) assert.equal(JSONUtils.parseQuery(url_parts.query)[KEY], VALUES[KEY], 'Same type returned') done() it 'handles number strings', (done) -> KEY = '<KEY>' url_parts = URL.parse(MODEL_URL, true); _.extend(url_parts.query, JSONUtils.querify(_.pick(VALUES, KEY))); url = URL.format(url_parts) assert.equal(url, "#{MODEL_URL}?#{KEY}=#{encodeURIComponent('"' + VALUES[KEY] + '"')}", 'URL has string') url_parts = URL.parse(url, true) assert.equal(JSONUtils.parseQuery(url_parts.query)[KEY], VALUES[KEY], 'Same type returned') done() it 'handles numbers', (done) -> KEY = '<KEY>' url_parts = URL.parse(MODEL_URL, true); _.extend(url_parts.query, JSONUtils.querify(_.pick(VALUES, KEY))); url = URL.format(url_parts) assert.equal(url, "#{MODEL_URL}?#{KEY}=#{encodeURIComponent(VALUES[KEY])}", 'URL has number') url_parts = URL.parse(url, true) assert.equal(JSONUtils.parseQuery(url_parts.query)[KEY], VALUES[KEY], 'Same type returned') done()
true
assert = assert or require?('chai').assert BackboneORM = window?.BackboneORM; try BackboneORM or= require?('backbone-orm') catch; try BackboneORM or= require?('../../../../backbone-orm') {_, JSONUtils} = BackboneORM URL = BackboneORM.modules.url VALUES = date: new Date() string: "日本語" number: 123456789 number_string: "123456789" number2: 123456789e21 number2_string: '123456789e21' object: date: new Date() string: "日本語" number: 123456789 array: [new Date(), "日本語", 123456789e21, "123456789e21"] MODEL_URL = 'https://things/1' describe 'JSONUtils @quick @json', -> it 'parse maintains types correctly', (done) -> parsed_json = JSONUtils.parseQuery(JSONUtils.querify(VALUES)) assert.deepEqual(parsed_json, VALUES) done() it 'querify handles control directives', (done) -> query = {$limit: 1, $one: true, $hello: 'abc', $sort: ['name'], $id: {$in: [1, '2']}} parsed_query = {$limit: 1, $one: true, $hello: 'abc', $sort: ['name'], $id: {$in: [1, '2']}} assert.deepEqual(JSONUtils.parseQuery(JSONUtils.querify(query)), parsed_query, 'matches without extra JSON operations') assert.deepEqual(JSONUtils.parseQuery(JSON.parse(JSON.stringify(JSONUtils.querify(query)))), parsed_query, 'matches with extra JSON operations') done() describe 'Strict JSON in URL', -> it 'handles unicode strings', (done) -> KEY = 'PI:KEY:<KEY>END_PI' url_parts = URL.parse(MODEL_URL, true); _.extend(url_parts.query, JSONUtils.querify(_.pick(VALUES, KEY))); url = URL.format(url_parts) assert.equal(url, "#{MODEL_URL}?#{KEY}=#{encodeURIComponent('"' + VALUES[KEY] + '"')}", 'URL has string') url_parts = URL.parse(url, true) assert.equal(JSONUtils.parseQuery(url_parts.query)[KEY], VALUES[KEY], 'Same type returned') done() it 'handles number strings', (done) -> KEY = 'PI:KEY:<KEY>END_PI' url_parts = URL.parse(MODEL_URL, true); _.extend(url_parts.query, JSONUtils.querify(_.pick(VALUES, KEY))); url = URL.format(url_parts) assert.equal(url, "#{MODEL_URL}?#{KEY}=#{encodeURIComponent('"' + VALUES[KEY] + '"')}", 'URL has string') url_parts = URL.parse(url, true) assert.equal(JSONUtils.parseQuery(url_parts.query)[KEY], VALUES[KEY], 'Same type returned') done() it 'handles numbers', (done) -> KEY = 'PI:KEY:<KEY>END_PI' url_parts = URL.parse(MODEL_URL, true); _.extend(url_parts.query, JSONUtils.querify(_.pick(VALUES, KEY))); url = URL.format(url_parts) assert.equal(url, "#{MODEL_URL}?#{KEY}=#{encodeURIComponent(VALUES[KEY])}", 'URL has number') url_parts = URL.parse(url, true) assert.equal(JSONUtils.parseQuery(url_parts.query)[KEY], VALUES[KEY], 'Same type returned') done()
[ { "context": "ser, 'expected user'\n user.email.should.eql 'foo@bar.com'\n done()\n", "end": 1027, "score": 0.9998416900634766, "start": 1016, "tag": "EMAIL", "value": "foo@bar.com" } ]
test/seed.coffee
TorchlightSoftware/axiom-mongoose
0
{join} = require 'path' rel = (args...) -> join __dirname, '..', args... should = require 'should' axiom = require 'axiom' _ = require 'lodash' axiomMongoose = require '..' describe 'Mongoose Seed', -> before (done) -> axiom.wireUpLoggers [{writer: 'console', level: 'warning'}] axiom.init {timeout: 1200}, {root: rel 'sample'} # Given the seed command is initiated axiom.request "db.seed", {}, (err, {mongoose: {@db}}) => should.not.exist err done() afterEach (done) -> axiom.reset(done) it 'models should be loaded after db.seed', -> @db.models.should.have.keys ['User'] it 'a user should exist', (done) -> # get our own model for data verification db = require 'mongoose' db.connect axiomMongoose.config.host db.model 'User', require('../sample/domain/mongoose/models/User')(db.Schema) {User} = db.models User.findOne {}, (err, user) -> should.not.exist err should.exist user, 'expected user' user.email.should.eql 'foo@bar.com' done()
61752
{join} = require 'path' rel = (args...) -> join __dirname, '..', args... should = require 'should' axiom = require 'axiom' _ = require 'lodash' axiomMongoose = require '..' describe 'Mongoose Seed', -> before (done) -> axiom.wireUpLoggers [{writer: 'console', level: 'warning'}] axiom.init {timeout: 1200}, {root: rel 'sample'} # Given the seed command is initiated axiom.request "db.seed", {}, (err, {mongoose: {@db}}) => should.not.exist err done() afterEach (done) -> axiom.reset(done) it 'models should be loaded after db.seed', -> @db.models.should.have.keys ['User'] it 'a user should exist', (done) -> # get our own model for data verification db = require 'mongoose' db.connect axiomMongoose.config.host db.model 'User', require('../sample/domain/mongoose/models/User')(db.Schema) {User} = db.models User.findOne {}, (err, user) -> should.not.exist err should.exist user, 'expected user' user.email.should.eql '<EMAIL>' done()
true
{join} = require 'path' rel = (args...) -> join __dirname, '..', args... should = require 'should' axiom = require 'axiom' _ = require 'lodash' axiomMongoose = require '..' describe 'Mongoose Seed', -> before (done) -> axiom.wireUpLoggers [{writer: 'console', level: 'warning'}] axiom.init {timeout: 1200}, {root: rel 'sample'} # Given the seed command is initiated axiom.request "db.seed", {}, (err, {mongoose: {@db}}) => should.not.exist err done() afterEach (done) -> axiom.reset(done) it 'models should be loaded after db.seed', -> @db.models.should.have.keys ['User'] it 'a user should exist', (done) -> # get our own model for data verification db = require 'mongoose' db.connect axiomMongoose.config.host db.model 'User', require('../sample/domain/mongoose/models/User')(db.Schema) {User} = db.models User.findOne {}, (err, user) -> should.not.exist err should.exist user, 'expected user' user.email.should.eql 'PI:EMAIL:<EMAIL>END_PI' done()
[ { "context": ">\n\t\t@manager = {\n\t\t\tid: \"666666\",\n\t\t\tfirst_name: \"Daenerys\"\n\t\t\tlast_name: \"Targaryen\"\n\t\t\temail: \"daenerys@ex", "end": 455, "score": 0.9997895359992981, "start": 447, "tag": "NAME", "value": "Daenerys" }, { "context": "666666\",\n\t\t\tfirst_name: \"Daenerys\"\n\t\t\tlast_name: \"Targaryen\"\n\t\t\temail: \"daenerys@example.com\"\n\t\t}\n\n\t\t@token =", "end": 481, "score": 0.9997923374176025, "start": 472, "tag": "NAME", "value": "Targaryen" }, { "context": ": \"Daenerys\"\n\t\t\tlast_name: \"Targaryen\"\n\t\t\temail: \"daenerys@example.com\"\n\t\t}\n\n\t\t@token = \"aaaaaaaaaaaaaaaaaaaaaa\"\n\n\t\t@tea", "end": 514, "score": 0.9999305605888367, "start": 494, "tag": "EMAIL", "value": "daenerys@example.com" }, { "context": "\t\t\temail: \"daenerys@example.com\"\n\t\t}\n\n\t\t@token = \"aaaaaaaaaaaaaaaaaaaaaa\"\n\n\t\t@teamInvite = {\n\t\t\temail: \"jorah@example.com\"", "end": 555, "score": 0.7741248607635498, "start": 533, "tag": "PASSWORD", "value": "aaaaaaaaaaaaaaaaaaaaaa" }, { "context": "aaaaaaaaaaaaaaaaaa\"\n\n\t\t@teamInvite = {\n\t\t\temail: \"jorah@example.com\",\n\t\t\ttoken: @token,\n\t\t}\n\n\t\t@subscription = {\n\t\t\ti", "end": 604, "score": 0.9999234080314636, "start": 587, "tag": "EMAIL", "value": "jorah@example.com" }, { "context": "il: sinon.stub().yields(null)\n\t\t}\n\n\t\t@newToken = \"bbbbbbbbb\"\n\n\t\t@crypto = {\n\t\t\trandomBytes: =>\n\t\t\t\ttoString: ", "end": 1401, "score": 0.737481415271759, "start": 1392, "tag": "PASSWORD", "value": "bbbbbbbbb" }, { "context": "\t\t\t@TeamInvitesHandler.createInvite @manager.id, \"John.Snow@example.com\", (err, invite) =>\n\t\t\t\texpect(err).to.eq(null)\n\t\t", "end": 3038, "score": 0.9998775124549866, "start": 3017, "tag": "EMAIL", "value": "John.Snow@example.com" }, { "context": ".to.eq(@newToken)\n\t\t\t\texpect(invite.email).to.eq(\"john.snow@example.com\")\n\t\t\t\texpect(invite.inviterName).to.eq(\"Daenerys ", "end": 3181, "score": 0.9999107718467712, "start": 3160, "tag": "EMAIL", "value": "john.snow@example.com" }, { "context": "m\")\n\t\t\t\texpect(invite.inviterName).to.eq(\"Daenerys Targaryen (daenerys@example.com)\")\n\t\t\t\texpect(@subscription", "end": 3240, "score": 0.9987354874610901, "start": 3231, "tag": "NAME", "value": "Targaryen" }, { "context": "ct(invite.inviterName).to.eq(\"Daenerys Targaryen (daenerys@example.com)\")\n\t\t\t\texpect(@subscription.teamInvites).to.deep.", "end": 3262, "score": 0.9999272227287292, "start": 3242, "tag": "EMAIL", "value": "daenerys@example.com" }, { "context": "\t\t\t@TeamInvitesHandler.createInvite @manager.id, \"John.Snow@example.com\", (err, invite) =>\n\t\t\t\t@EmailHandler.sendEmail.ca", "end": 3444, "score": 0.9999240636825562, "start": 3423, "tag": "EMAIL", "value": "John.Snow@example.com" }, { "context": "fyEmailToJoinTeam\",\n\t\t\t\t\tsinon.match({\n\t\t\t\t\t\tto: \"john.snow@example.com\",\n\t\t\t\t\t\tinviterName: \"Daenerys Targaryen (daenery", "end": 3579, "score": 0.9999246001243591, "start": 3558, "tag": "EMAIL", "value": "john.snow@example.com" }, { "context": "\tto: \"john.snow@example.com\",\n\t\t\t\t\t\tinviterName: \"Daenerys Targaryen (daenerys@example.com)\",\n\t\t\t\t\t\tacceptInviteUrl: \"", "end": 3620, "score": 0.9998517036437988, "start": 3602, "tag": "NAME", "value": "Daenerys Targaryen" }, { "context": "ple.com\",\n\t\t\t\t\t\tinviterName: \"Daenerys Targaryen (daenerys@example.com)\",\n\t\t\t\t\t\tacceptInviteUrl: \"http://example.com/sub", "end": 3642, "score": 0.9999284744262695, "start": 3622, "tag": "EMAIL", "value": "daenerys@example.com" }, { "context": "\t\t\t@TeamInvitesHandler.createInvite @manager.id, \"John.Snow@example.com\", (err, invite) =>\n\t\t\t\t@Subscription.update.calle", "end": 4419, "score": 0.9999208450317383, "start": 4398, "tag": "EMAIL", "value": "John.Snow@example.com" }, { "context": "65bbf700d\") },\n\t\t\t\t\t{ '$pull': { invited_emails: \"john.snow@example.com\" } }\n\t\t\t\t).should.eq true\n\t\t\t\tdone()\n\n\tdescribe \"", "end": 4588, "score": 0.9999250769615173, "start": 4567, "tag": "EMAIL", "value": "john.snow@example.com" }, { "context": "\t\t\t\tname: \"Team Daenerys\"\n\n\t\t\t@user =\n\t\t\t\temail: \"John.Snow@example.com\"\n\n\t\tit \"adds the team invite to the subscription\"", "end": 4801, "score": 0.9999234080314636, "start": 4780, "tag": "EMAIL", "value": "John.Snow@example.com" }, { "context": "ct(err).to.eq(null)\n\t\t\t\texpect(invite.token).to.eq(@newToken)\n\t\t\t\texpect(invite.email).to.eq(\"john.snow@exampl", "end": 5007, "score": 0.5041672587394714, "start": 4998, "tag": "USERNAME", "value": "@newToken" }, { "context": ".to.eq(@newToken)\n\t\t\t\texpect(invite.email).to.eq(\"john.snow@example.com\")\n\t\t\t\texpect(invite.inviterName).to.eq(\"Team Daen", "end": 5062, "score": 0.9999279975891113, "start": 5041, "tag": "EMAIL", "value": "john.snow@example.com" }, { "context": "fyEmailToJoinTeam\",\n\t\t\t\t\tsinon.match({\n\t\t\t\t\t\tto: \"john.snow@example.com\"\n\t\t\t\t\t\tinviterName: \"Team Daenerys\"\n\t\t\t\t\t\tacceptI", "end": 5417, "score": 0.9999215006828308, "start": 5396, "tag": "EMAIL", "value": "john.snow@example.com" }, { "context": "tesHandler.importInvite @subscription, \"A-Team\", \"hannibal@a-team.org\",\n\t\t\t\t\"secret\", @sentAt, (error) =>\n\t\t\t\t\texpect(e", "end": 5769, "score": 0.9996439814567566, "start": 5750, "tag": "EMAIL", "value": "hannibal@a-team.org" }, { "context": "@subscription.teamInvites.find (i) -> i.email == \"hannibal@a-team.org\"\n\t\t\t\t\texpect(invite.token).to.eq(\"secret\")\n\t\t\t\t\te", "end": 5973, "score": 0.9996973872184753, "start": 5954, "tag": "EMAIL", "value": "hannibal@a-team.org" }, { "context": "\t\t@user = {\n\t\t\t\tid: \"123456789\",\n\t\t\t\tfirst_name: \"Tyrion\",\n\t\t\t\tlast_name: \"Lannister\",\n\t\t\t\temail: \"tyrion@", "end": 6163, "score": 0.9997969269752502, "start": 6157, "tag": "NAME", "value": "Tyrion" }, { "context": "56789\",\n\t\t\t\tfirst_name: \"Tyrion\",\n\t\t\t\tlast_name: \"Lannister\",\n\t\t\t\temail: \"tyrion@example.com\"\n\t\t\t}\n\n\t\t\t@UserG", "end": 6191, "score": 0.9997744560241699, "start": 6182, "tag": "NAME", "value": "Lannister" }, { "context": "\"Tyrion\",\n\t\t\t\tlast_name: \"Lannister\",\n\t\t\t\temail: \"tyrion@example.com\"\n\t\t\t}\n\n\t\t\t@UserGetter.getUserByAnyEmail.withArgs(", "end": 6224, "score": 0.9999300241470337, "start": 6206, "tag": "EMAIL", "value": "tyrion@example.com" }, { "context": "\n\n\t\t\t@subscription.teamInvites.push({\n\t\t\t\temail: \"john.snow@example.com\",\n\t\t\t\ttoken: \"dddddddd\",\n\t\t\t\tinviterName: \"Daener", "end": 6377, "score": 0.9999216198921204, "start": 6356, "tag": "EMAIL", "value": "john.snow@example.com" }, { "context": "{\n\t\t\t\temail: \"john.snow@example.com\",\n\t\t\t\ttoken: \"dddddddd\",\n\t\t\t\tinviterName: \"Daenerys Targaryen (daenerys@", "end": 6400, "score": 0.9981517791748047, "start": 6392, "tag": "PASSWORD", "value": "dddddddd" }, { "context": "le.com\",\n\t\t\t\ttoken: \"dddddddd\",\n\t\t\t\tinviterName: \"Daenerys Targaryen (daenerys@example.com)\"\n\t\t\t})\n\n\t\tit \"adds the use", "end": 6439, "score": 0.9998802542686462, "start": 6421, "tag": "NAME", "value": "Daenerys Targaryen" }, { "context": "\"dddddddd\",\n\t\t\t\tinviterName: \"Daenerys Targaryen (daenerys@example.com)\"\n\t\t\t})\n\n\t\tit \"adds the user to the team\", (done)", "end": 6461, "score": 0.9999272227287292, "start": 6441, "tag": "EMAIL", "value": "daenerys@example.com" }, { "context": "00d\") },\n\t\t\t\t\t{ '$pull': { teamInvites: { email: 'john.snow@example.com' } } }\n\t\t\t\t).should.eq true\n\t\t\t\tdone()\n\n\tdescribe", "end": 6952, "score": 0.9999092817306519, "start": 6931, "tag": "EMAIL", "value": "john.snow@example.com" }, { "context": "\t\t\t@TeamInvitesHandler.revokeInvite @manager.id, \"jorah@example.com\", =>\n\t\t\t\t@Subscription.update.calledWith(\n\t\t\t\t\t{ ", "end": 7153, "score": 0.9999210238456726, "start": 7136, "tag": "EMAIL", "value": "jorah@example.com" }, { "context": "00d\") },\n\t\t\t\t\t{ '$pull': { teamInvites: { email: \"jorah@example.com\" } } }\n\t\t\t\t).should.eq true\n\n\t\t\t\t@Subscription.up", "end": 7310, "score": 0.9999239444732666, "start": 7293, "tag": "EMAIL", "value": "jorah@example.com" }, { "context": "65bbf700d\") },\n\t\t\t\t\t{ '$pull': { invited_emails: \"jorah@example.com\" } }\n\t\t\t\t).should.eq true\n\t\t\t\tdone()\n\n\tdescribe \"", "end": 7485, "score": 0.99992436170578, "start": 7468, "tag": "EMAIL", "value": "jorah@example.com" }, { "context": "beforeEach ->\n\t\t\t@subscription.invited_emails = [\"eddard@example.com\", \"robert@example.com\"]\n\t\t\t@TeamInvitesHandler.cr", "end": 7656, "score": 0.9999241828918457, "start": 7638, "tag": "EMAIL", "value": "eddard@example.com" }, { "context": "cription.invited_emails = [\"eddard@example.com\", \"robert@example.com\"]\n\t\t\t@TeamInvitesHandler.createInvite = sinon.stu", "end": 7678, "score": 0.9999260902404785, "start": 7660, "tag": "EMAIL", "value": "robert@example.com" }, { "context": "esHandler.createTeamInvitesForLegacyInvitedEmail \"eddard@example.com\", (err, invite) =>\n\t\t\t\texpect(err).not.to.exist\n\n", "end": 8013, "score": 0.99992436170578, "start": 7995, "tag": "EMAIL", "value": "eddard@example.com" }, { "context": "te.calledWith(\n\t\t\t\t\t@subscription.admin_id,\n\t\t\t\t\t\"eddard@example.com\"\n\t\t\t\t).should.eq true\n\n\t\t\t\t@TeamInvitesHandler.cr", "end": 8165, "score": 0.9999241828918457, "start": 8147, "tag": "EMAIL", "value": "eddard@example.com" }, { "context": "\t\t\t@TeamInvitesHandler.createInvite @manager.id, \"John.Snow@example.com\", (err, invite) =>\n\t\t\t\texpect(err).to.deep.equal(", "end": 8515, "score": 0.9998744130134583, "start": 8494, "tag": "EMAIL", "value": "John.Snow@example.com" }, { "context": "\t\t\t@TeamInvitesHandler.createInvite @manager.id, \"John.Snow@example.com\", (err, invite) =>\n\t\t\t\texpect(err).to.deep.equal(", "end": 8789, "score": 0.999890148639679, "start": 8768, "tag": "EMAIL", "value": "John.Snow@example.com" }, { "context": " = {\n\t\t\t\tid: \"1a2b\",\n\t\t\t\t_id: \"1a2b\",\n\t\t\t\temail: \"tyrion@example.com\"\n\t\t\t}\n\n\t\t\t@subscription.member_ids = [member.id]\n", "end": 9028, "score": 0.9999226927757263, "start": 9010, "tag": "EMAIL", "value": "tyrion@example.com" }, { "context": "\t\t\t@TeamInvitesHandler.createInvite @manager.id, \"tyrion@example.com\", (err, invite) =>\n\t\t\t\texpect(err).to.deep.equal(", "end": 9224, "score": 0.9999194741249084, "start": 9206, "tag": "EMAIL", "value": "tyrion@example.com" } ]
test/unit/coffee/Subscription/TeamInvitesHandlerTests.coffee
davidmehren/web-sharelatex
0
SandboxedModule = require('sandboxed-module') should = require('chai').should() sinon = require 'sinon' expect = require("chai").expect querystring = require 'querystring' modulePath = "../../../../app/js/Features/Subscription/TeamInvitesHandler" ObjectId = require("mongojs").ObjectId Errors = require("../../../../app/js/Features/Errors/Errors") describe "TeamInvitesHandler", -> beforeEach -> @manager = { id: "666666", first_name: "Daenerys" last_name: "Targaryen" email: "daenerys@example.com" } @token = "aaaaaaaaaaaaaaaaaaaaaa" @teamInvite = { email: "jorah@example.com", token: @token, } @subscription = { id: "55153a8014829a865bbf700d", admin_id: @manager.id, groupPlan: true, member_ids: [], teamInvites: [ @teamInvite ], save: sinon.stub().yields(null), } @SubscriptionLocator = { getUsersSubscription: sinon.stub(), getSubscription: sinon.stub().yields(null, @subscription) } @UserGetter = { getUser: sinon.stub().yields(), getUserByAnyEmail: sinon.stub().yields() } @SubscriptionUpdater = { addUserToGroup: sinon.stub().yields() } @LimitationsManager = { teamHasReachedMemberLimit: sinon.stub().returns(false) } @Subscription = { findOne: sinon.stub().yields() update: sinon.stub().yields() } @EmailHandler = { sendEmail: sinon.stub().yields(null) } @newToken = "bbbbbbbbb" @crypto = { randomBytes: => toString: sinon.stub().returns(@newToken) } @UserGetter.getUser.withArgs(@manager.id).yields(null, @manager) @UserGetter.getUserByAnyEmail.withArgs(@manager.email).yields(null, @manager) @SubscriptionLocator.getUsersSubscription.yields(null, @subscription) @Subscription.findOne.yields(null, @subscription) @TeamInvitesHandler = SandboxedModule.require modulePath, requires: "logger-sharelatex": { log: -> } "crypto": @crypto "settings-sharelatex": { siteUrl: "http://example.com" } "../../models/TeamInvite": { TeamInvite: @TeamInvite = {} } "../../models/Subscription": { Subscription: @Subscription } "../User/UserGetter": @UserGetter "./SubscriptionLocator": @SubscriptionLocator "./SubscriptionUpdater": @SubscriptionUpdater "./LimitationsManager": @LimitationsManager "../Email/EmailHandler": @EmailHandler "../Errors/Errors": Errors describe "getInvite", -> it "returns the invite if there's one", (done) -> @TeamInvitesHandler.getInvite @token, (err, invite, subscription) => expect(err).to.eq(null) expect(invite).to.deep.eq(@teamInvite) expect(subscription).to.deep.eq(@subscription) done() it "returns teamNotFound if there's none", (done) -> @Subscription.findOne = sinon.stub().yields(null, null) @TeamInvitesHandler.getInvite @token, (err, invite, subscription) -> expect(err).to.be.instanceof(Errors.NotFoundError) done() describe "createInvite", -> it "adds the team invite to the subscription", (done) -> @TeamInvitesHandler.createInvite @manager.id, "John.Snow@example.com", (err, invite) => expect(err).to.eq(null) expect(invite.token).to.eq(@newToken) expect(invite.email).to.eq("john.snow@example.com") expect(invite.inviterName).to.eq("Daenerys Targaryen (daenerys@example.com)") expect(@subscription.teamInvites).to.deep.include(invite) done() it "sends an email", (done) -> @TeamInvitesHandler.createInvite @manager.id, "John.Snow@example.com", (err, invite) => @EmailHandler.sendEmail.calledWith("verifyEmailToJoinTeam", sinon.match({ to: "john.snow@example.com", inviterName: "Daenerys Targaryen (daenerys@example.com)", acceptInviteUrl: "http://example.com/subscription/invites/#{@newToken}/" }) ).should.equal true done() it "refreshes the existing invite if the email has already been invited", (done) -> originalInvite = Object.assign({}, @teamInvite) @TeamInvitesHandler.createInvite @manager.id, originalInvite.email, (err, invite) => expect(err).to.eq(null) expect(invite).to.exist expect(@subscription.teamInvites.length).to.eq 1 expect(@subscription.teamInvites).to.deep.include invite expect(invite.email).to.eq originalInvite.email @subscription.save.calledOnce.should.eq true done() it "removes any legacy invite from the subscription", (done) -> @TeamInvitesHandler.createInvite @manager.id, "John.Snow@example.com", (err, invite) => @Subscription.update.calledWith( { _id: new ObjectId("55153a8014829a865bbf700d") }, { '$pull': { invited_emails: "john.snow@example.com" } } ).should.eq true done() describe "createDomainInvite", -> beforeEach -> @licence = subscription_id: @subscription.id name: "Team Daenerys" @user = email: "John.Snow@example.com" it "adds the team invite to the subscription", (done) -> @TeamInvitesHandler.createDomainInvite @user, @licence, (err, invite) => expect(err).to.eq(null) expect(invite.token).to.eq(@newToken) expect(invite.email).to.eq("john.snow@example.com") expect(invite.inviterName).to.eq("Team Daenerys") expect(@subscription.teamInvites).to.deep.include(invite) done() it "sends an email", (done) -> @TeamInvitesHandler.createDomainInvite @user, @licence, (err, invite) => @EmailHandler.sendEmail.calledWith("verifyEmailToJoinTeam", sinon.match({ to: "john.snow@example.com" inviterName: "Team Daenerys" acceptInviteUrl: "http://example.com/subscription/invites/#{@newToken}/" }) ).should.equal true done() describe "importInvite", -> beforeEach -> @sentAt = new Date() it "can imports an invite from v1", -> @TeamInvitesHandler.importInvite @subscription, "A-Team", "hannibal@a-team.org", "secret", @sentAt, (error) => expect(error).not.to.exist @subscription.save.calledOnce.should.eq true invite = @subscription.teamInvites.find (i) -> i.email == "hannibal@a-team.org" expect(invite.token).to.eq("secret") expect(invite.sentAt).to.eq(@sentAt) describe "acceptInvite", -> beforeEach -> @user = { id: "123456789", first_name: "Tyrion", last_name: "Lannister", email: "tyrion@example.com" } @UserGetter.getUserByAnyEmail.withArgs(@user.email).yields(null, @user) @subscription.teamInvites.push({ email: "john.snow@example.com", token: "dddddddd", inviterName: "Daenerys Targaryen (daenerys@example.com)" }) it "adds the user to the team", (done) -> @TeamInvitesHandler.acceptInvite "dddddddd", @user.id, => @SubscriptionUpdater.addUserToGroup.calledWith(@manager.id, @user.id).should.eq true done() it "removes the invite from the subscription", (done) -> @TeamInvitesHandler.acceptInvite "dddddddd", @user.id, => @Subscription.update.calledWith( { _id: new ObjectId("55153a8014829a865bbf700d") }, { '$pull': { teamInvites: { email: 'john.snow@example.com' } } } ).should.eq true done() describe "revokeInvite", -> it "removes the team invite from the subscription", (done) -> @TeamInvitesHandler.revokeInvite @manager.id, "jorah@example.com", => @Subscription.update.calledWith( { _id: new ObjectId("55153a8014829a865bbf700d") }, { '$pull': { teamInvites: { email: "jorah@example.com" } } } ).should.eq true @Subscription.update.calledWith( { _id: new ObjectId("55153a8014829a865bbf700d") }, { '$pull': { invited_emails: "jorah@example.com" } } ).should.eq true done() describe "createTeamInvitesForLegacyInvitedEmail", (done) -> beforeEach -> @subscription.invited_emails = ["eddard@example.com", "robert@example.com"] @TeamInvitesHandler.createInvite = sinon.stub().yields(null) @SubscriptionLocator.getGroupsWithEmailInvite = sinon.stub().yields(null, [@subscription]) it "sends an invitation email to addresses in the legacy invited_emails field", (done) -> @TeamInvitesHandler.createTeamInvitesForLegacyInvitedEmail "eddard@example.com", (err, invite) => expect(err).not.to.exist @TeamInvitesHandler.createInvite.calledWith( @subscription.admin_id, "eddard@example.com" ).should.eq true @TeamInvitesHandler.createInvite.callCount.should.eq 1 done() describe "validation", -> it "doesn't create an invite if the team limit has been reached", (done) -> @LimitationsManager.teamHasReachedMemberLimit = sinon.stub().returns(true) @TeamInvitesHandler.createInvite @manager.id, "John.Snow@example.com", (err, invite) => expect(err).to.deep.equal(limitReached: true) done() it "doesn't create an invite if the subscription is not in a group plan", (done) -> @subscription.groupPlan = false @TeamInvitesHandler.createInvite @manager.id, "John.Snow@example.com", (err, invite) => expect(err).to.deep.equal(wrongPlan: true) done() it "doesn't create an invite if the user is already part of the team", (done) -> member = { id: "1a2b", _id: "1a2b", email: "tyrion@example.com" } @subscription.member_ids = [member.id] @UserGetter.getUserByAnyEmail.withArgs(member.email).yields(null, member) @TeamInvitesHandler.createInvite @manager.id, "tyrion@example.com", (err, invite) => expect(err).to.deep.equal(alreadyInTeam: true) expect(invite).not.to.exist done()
75158
SandboxedModule = require('sandboxed-module') should = require('chai').should() sinon = require 'sinon' expect = require("chai").expect querystring = require 'querystring' modulePath = "../../../../app/js/Features/Subscription/TeamInvitesHandler" ObjectId = require("mongojs").ObjectId Errors = require("../../../../app/js/Features/Errors/Errors") describe "TeamInvitesHandler", -> beforeEach -> @manager = { id: "666666", first_name: "<NAME>" last_name: "<NAME>" email: "<EMAIL>" } @token = "<PASSWORD>" @teamInvite = { email: "<EMAIL>", token: @token, } @subscription = { id: "55153a8014829a865bbf700d", admin_id: @manager.id, groupPlan: true, member_ids: [], teamInvites: [ @teamInvite ], save: sinon.stub().yields(null), } @SubscriptionLocator = { getUsersSubscription: sinon.stub(), getSubscription: sinon.stub().yields(null, @subscription) } @UserGetter = { getUser: sinon.stub().yields(), getUserByAnyEmail: sinon.stub().yields() } @SubscriptionUpdater = { addUserToGroup: sinon.stub().yields() } @LimitationsManager = { teamHasReachedMemberLimit: sinon.stub().returns(false) } @Subscription = { findOne: sinon.stub().yields() update: sinon.stub().yields() } @EmailHandler = { sendEmail: sinon.stub().yields(null) } @newToken = "<PASSWORD>" @crypto = { randomBytes: => toString: sinon.stub().returns(@newToken) } @UserGetter.getUser.withArgs(@manager.id).yields(null, @manager) @UserGetter.getUserByAnyEmail.withArgs(@manager.email).yields(null, @manager) @SubscriptionLocator.getUsersSubscription.yields(null, @subscription) @Subscription.findOne.yields(null, @subscription) @TeamInvitesHandler = SandboxedModule.require modulePath, requires: "logger-sharelatex": { log: -> } "crypto": @crypto "settings-sharelatex": { siteUrl: "http://example.com" } "../../models/TeamInvite": { TeamInvite: @TeamInvite = {} } "../../models/Subscription": { Subscription: @Subscription } "../User/UserGetter": @UserGetter "./SubscriptionLocator": @SubscriptionLocator "./SubscriptionUpdater": @SubscriptionUpdater "./LimitationsManager": @LimitationsManager "../Email/EmailHandler": @EmailHandler "../Errors/Errors": Errors describe "getInvite", -> it "returns the invite if there's one", (done) -> @TeamInvitesHandler.getInvite @token, (err, invite, subscription) => expect(err).to.eq(null) expect(invite).to.deep.eq(@teamInvite) expect(subscription).to.deep.eq(@subscription) done() it "returns teamNotFound if there's none", (done) -> @Subscription.findOne = sinon.stub().yields(null, null) @TeamInvitesHandler.getInvite @token, (err, invite, subscription) -> expect(err).to.be.instanceof(Errors.NotFoundError) done() describe "createInvite", -> it "adds the team invite to the subscription", (done) -> @TeamInvitesHandler.createInvite @manager.id, "<EMAIL>", (err, invite) => expect(err).to.eq(null) expect(invite.token).to.eq(@newToken) expect(invite.email).to.eq("<EMAIL>") expect(invite.inviterName).to.eq("Daenerys <NAME> (<EMAIL>)") expect(@subscription.teamInvites).to.deep.include(invite) done() it "sends an email", (done) -> @TeamInvitesHandler.createInvite @manager.id, "<EMAIL>", (err, invite) => @EmailHandler.sendEmail.calledWith("verifyEmailToJoinTeam", sinon.match({ to: "<EMAIL>", inviterName: "<NAME> (<EMAIL>)", acceptInviteUrl: "http://example.com/subscription/invites/#{@newToken}/" }) ).should.equal true done() it "refreshes the existing invite if the email has already been invited", (done) -> originalInvite = Object.assign({}, @teamInvite) @TeamInvitesHandler.createInvite @manager.id, originalInvite.email, (err, invite) => expect(err).to.eq(null) expect(invite).to.exist expect(@subscription.teamInvites.length).to.eq 1 expect(@subscription.teamInvites).to.deep.include invite expect(invite.email).to.eq originalInvite.email @subscription.save.calledOnce.should.eq true done() it "removes any legacy invite from the subscription", (done) -> @TeamInvitesHandler.createInvite @manager.id, "<EMAIL>", (err, invite) => @Subscription.update.calledWith( { _id: new ObjectId("55153a8014829a865bbf700d") }, { '$pull': { invited_emails: "<EMAIL>" } } ).should.eq true done() describe "createDomainInvite", -> beforeEach -> @licence = subscription_id: @subscription.id name: "Team Daenerys" @user = email: "<EMAIL>" it "adds the team invite to the subscription", (done) -> @TeamInvitesHandler.createDomainInvite @user, @licence, (err, invite) => expect(err).to.eq(null) expect(invite.token).to.eq(@newToken) expect(invite.email).to.eq("<EMAIL>") expect(invite.inviterName).to.eq("Team Daenerys") expect(@subscription.teamInvites).to.deep.include(invite) done() it "sends an email", (done) -> @TeamInvitesHandler.createDomainInvite @user, @licence, (err, invite) => @EmailHandler.sendEmail.calledWith("verifyEmailToJoinTeam", sinon.match({ to: "<EMAIL>" inviterName: "Team Daenerys" acceptInviteUrl: "http://example.com/subscription/invites/#{@newToken}/" }) ).should.equal true done() describe "importInvite", -> beforeEach -> @sentAt = new Date() it "can imports an invite from v1", -> @TeamInvitesHandler.importInvite @subscription, "A-Team", "<EMAIL>", "secret", @sentAt, (error) => expect(error).not.to.exist @subscription.save.calledOnce.should.eq true invite = @subscription.teamInvites.find (i) -> i.email == "<EMAIL>" expect(invite.token).to.eq("secret") expect(invite.sentAt).to.eq(@sentAt) describe "acceptInvite", -> beforeEach -> @user = { id: "123456789", first_name: "<NAME>", last_name: "<NAME>", email: "<EMAIL>" } @UserGetter.getUserByAnyEmail.withArgs(@user.email).yields(null, @user) @subscription.teamInvites.push({ email: "<EMAIL>", token: "<PASSWORD>", inviterName: "<NAME> (<EMAIL>)" }) it "adds the user to the team", (done) -> @TeamInvitesHandler.acceptInvite "dddddddd", @user.id, => @SubscriptionUpdater.addUserToGroup.calledWith(@manager.id, @user.id).should.eq true done() it "removes the invite from the subscription", (done) -> @TeamInvitesHandler.acceptInvite "dddddddd", @user.id, => @Subscription.update.calledWith( { _id: new ObjectId("55153a8014829a865bbf700d") }, { '$pull': { teamInvites: { email: '<EMAIL>' } } } ).should.eq true done() describe "revokeInvite", -> it "removes the team invite from the subscription", (done) -> @TeamInvitesHandler.revokeInvite @manager.id, "<EMAIL>", => @Subscription.update.calledWith( { _id: new ObjectId("55153a8014829a865bbf700d") }, { '$pull': { teamInvites: { email: "<EMAIL>" } } } ).should.eq true @Subscription.update.calledWith( { _id: new ObjectId("55153a8014829a865bbf700d") }, { '$pull': { invited_emails: "<EMAIL>" } } ).should.eq true done() describe "createTeamInvitesForLegacyInvitedEmail", (done) -> beforeEach -> @subscription.invited_emails = ["<EMAIL>", "<EMAIL>"] @TeamInvitesHandler.createInvite = sinon.stub().yields(null) @SubscriptionLocator.getGroupsWithEmailInvite = sinon.stub().yields(null, [@subscription]) it "sends an invitation email to addresses in the legacy invited_emails field", (done) -> @TeamInvitesHandler.createTeamInvitesForLegacyInvitedEmail "<EMAIL>", (err, invite) => expect(err).not.to.exist @TeamInvitesHandler.createInvite.calledWith( @subscription.admin_id, "<EMAIL>" ).should.eq true @TeamInvitesHandler.createInvite.callCount.should.eq 1 done() describe "validation", -> it "doesn't create an invite if the team limit has been reached", (done) -> @LimitationsManager.teamHasReachedMemberLimit = sinon.stub().returns(true) @TeamInvitesHandler.createInvite @manager.id, "<EMAIL>", (err, invite) => expect(err).to.deep.equal(limitReached: true) done() it "doesn't create an invite if the subscription is not in a group plan", (done) -> @subscription.groupPlan = false @TeamInvitesHandler.createInvite @manager.id, "<EMAIL>", (err, invite) => expect(err).to.deep.equal(wrongPlan: true) done() it "doesn't create an invite if the user is already part of the team", (done) -> member = { id: "1a2b", _id: "1a2b", email: "<EMAIL>" } @subscription.member_ids = [member.id] @UserGetter.getUserByAnyEmail.withArgs(member.email).yields(null, member) @TeamInvitesHandler.createInvite @manager.id, "<EMAIL>", (err, invite) => expect(err).to.deep.equal(alreadyInTeam: true) expect(invite).not.to.exist done()
true
SandboxedModule = require('sandboxed-module') should = require('chai').should() sinon = require 'sinon' expect = require("chai").expect querystring = require 'querystring' modulePath = "../../../../app/js/Features/Subscription/TeamInvitesHandler" ObjectId = require("mongojs").ObjectId Errors = require("../../../../app/js/Features/Errors/Errors") describe "TeamInvitesHandler", -> beforeEach -> @manager = { id: "666666", first_name: "PI:NAME:<NAME>END_PI" last_name: "PI:NAME:<NAME>END_PI" email: "PI:EMAIL:<EMAIL>END_PI" } @token = "PI:PASSWORD:<PASSWORD>END_PI" @teamInvite = { email: "PI:EMAIL:<EMAIL>END_PI", token: @token, } @subscription = { id: "55153a8014829a865bbf700d", admin_id: @manager.id, groupPlan: true, member_ids: [], teamInvites: [ @teamInvite ], save: sinon.stub().yields(null), } @SubscriptionLocator = { getUsersSubscription: sinon.stub(), getSubscription: sinon.stub().yields(null, @subscription) } @UserGetter = { getUser: sinon.stub().yields(), getUserByAnyEmail: sinon.stub().yields() } @SubscriptionUpdater = { addUserToGroup: sinon.stub().yields() } @LimitationsManager = { teamHasReachedMemberLimit: sinon.stub().returns(false) } @Subscription = { findOne: sinon.stub().yields() update: sinon.stub().yields() } @EmailHandler = { sendEmail: sinon.stub().yields(null) } @newToken = "PI:PASSWORD:<PASSWORD>END_PI" @crypto = { randomBytes: => toString: sinon.stub().returns(@newToken) } @UserGetter.getUser.withArgs(@manager.id).yields(null, @manager) @UserGetter.getUserByAnyEmail.withArgs(@manager.email).yields(null, @manager) @SubscriptionLocator.getUsersSubscription.yields(null, @subscription) @Subscription.findOne.yields(null, @subscription) @TeamInvitesHandler = SandboxedModule.require modulePath, requires: "logger-sharelatex": { log: -> } "crypto": @crypto "settings-sharelatex": { siteUrl: "http://example.com" } "../../models/TeamInvite": { TeamInvite: @TeamInvite = {} } "../../models/Subscription": { Subscription: @Subscription } "../User/UserGetter": @UserGetter "./SubscriptionLocator": @SubscriptionLocator "./SubscriptionUpdater": @SubscriptionUpdater "./LimitationsManager": @LimitationsManager "../Email/EmailHandler": @EmailHandler "../Errors/Errors": Errors describe "getInvite", -> it "returns the invite if there's one", (done) -> @TeamInvitesHandler.getInvite @token, (err, invite, subscription) => expect(err).to.eq(null) expect(invite).to.deep.eq(@teamInvite) expect(subscription).to.deep.eq(@subscription) done() it "returns teamNotFound if there's none", (done) -> @Subscription.findOne = sinon.stub().yields(null, null) @TeamInvitesHandler.getInvite @token, (err, invite, subscription) -> expect(err).to.be.instanceof(Errors.NotFoundError) done() describe "createInvite", -> it "adds the team invite to the subscription", (done) -> @TeamInvitesHandler.createInvite @manager.id, "PI:EMAIL:<EMAIL>END_PI", (err, invite) => expect(err).to.eq(null) expect(invite.token).to.eq(@newToken) expect(invite.email).to.eq("PI:EMAIL:<EMAIL>END_PI") expect(invite.inviterName).to.eq("Daenerys PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)") expect(@subscription.teamInvites).to.deep.include(invite) done() it "sends an email", (done) -> @TeamInvitesHandler.createInvite @manager.id, "PI:EMAIL:<EMAIL>END_PI", (err, invite) => @EmailHandler.sendEmail.calledWith("verifyEmailToJoinTeam", sinon.match({ to: "PI:EMAIL:<EMAIL>END_PI", inviterName: "PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)", acceptInviteUrl: "http://example.com/subscription/invites/#{@newToken}/" }) ).should.equal true done() it "refreshes the existing invite if the email has already been invited", (done) -> originalInvite = Object.assign({}, @teamInvite) @TeamInvitesHandler.createInvite @manager.id, originalInvite.email, (err, invite) => expect(err).to.eq(null) expect(invite).to.exist expect(@subscription.teamInvites.length).to.eq 1 expect(@subscription.teamInvites).to.deep.include invite expect(invite.email).to.eq originalInvite.email @subscription.save.calledOnce.should.eq true done() it "removes any legacy invite from the subscription", (done) -> @TeamInvitesHandler.createInvite @manager.id, "PI:EMAIL:<EMAIL>END_PI", (err, invite) => @Subscription.update.calledWith( { _id: new ObjectId("55153a8014829a865bbf700d") }, { '$pull': { invited_emails: "PI:EMAIL:<EMAIL>END_PI" } } ).should.eq true done() describe "createDomainInvite", -> beforeEach -> @licence = subscription_id: @subscription.id name: "Team Daenerys" @user = email: "PI:EMAIL:<EMAIL>END_PI" it "adds the team invite to the subscription", (done) -> @TeamInvitesHandler.createDomainInvite @user, @licence, (err, invite) => expect(err).to.eq(null) expect(invite.token).to.eq(@newToken) expect(invite.email).to.eq("PI:EMAIL:<EMAIL>END_PI") expect(invite.inviterName).to.eq("Team Daenerys") expect(@subscription.teamInvites).to.deep.include(invite) done() it "sends an email", (done) -> @TeamInvitesHandler.createDomainInvite @user, @licence, (err, invite) => @EmailHandler.sendEmail.calledWith("verifyEmailToJoinTeam", sinon.match({ to: "PI:EMAIL:<EMAIL>END_PI" inviterName: "Team Daenerys" acceptInviteUrl: "http://example.com/subscription/invites/#{@newToken}/" }) ).should.equal true done() describe "importInvite", -> beforeEach -> @sentAt = new Date() it "can imports an invite from v1", -> @TeamInvitesHandler.importInvite @subscription, "A-Team", "PI:EMAIL:<EMAIL>END_PI", "secret", @sentAt, (error) => expect(error).not.to.exist @subscription.save.calledOnce.should.eq true invite = @subscription.teamInvites.find (i) -> i.email == "PI:EMAIL:<EMAIL>END_PI" expect(invite.token).to.eq("secret") expect(invite.sentAt).to.eq(@sentAt) describe "acceptInvite", -> beforeEach -> @user = { id: "123456789", first_name: "PI:NAME:<NAME>END_PI", last_name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI" } @UserGetter.getUserByAnyEmail.withArgs(@user.email).yields(null, @user) @subscription.teamInvites.push({ email: "PI:EMAIL:<EMAIL>END_PI", token: "PI:PASSWORD:<PASSWORD>END_PI", inviterName: "PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)" }) it "adds the user to the team", (done) -> @TeamInvitesHandler.acceptInvite "dddddddd", @user.id, => @SubscriptionUpdater.addUserToGroup.calledWith(@manager.id, @user.id).should.eq true done() it "removes the invite from the subscription", (done) -> @TeamInvitesHandler.acceptInvite "dddddddd", @user.id, => @Subscription.update.calledWith( { _id: new ObjectId("55153a8014829a865bbf700d") }, { '$pull': { teamInvites: { email: 'PI:EMAIL:<EMAIL>END_PI' } } } ).should.eq true done() describe "revokeInvite", -> it "removes the team invite from the subscription", (done) -> @TeamInvitesHandler.revokeInvite @manager.id, "PI:EMAIL:<EMAIL>END_PI", => @Subscription.update.calledWith( { _id: new ObjectId("55153a8014829a865bbf700d") }, { '$pull': { teamInvites: { email: "PI:EMAIL:<EMAIL>END_PI" } } } ).should.eq true @Subscription.update.calledWith( { _id: new ObjectId("55153a8014829a865bbf700d") }, { '$pull': { invited_emails: "PI:EMAIL:<EMAIL>END_PI" } } ).should.eq true done() describe "createTeamInvitesForLegacyInvitedEmail", (done) -> beforeEach -> @subscription.invited_emails = ["PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI"] @TeamInvitesHandler.createInvite = sinon.stub().yields(null) @SubscriptionLocator.getGroupsWithEmailInvite = sinon.stub().yields(null, [@subscription]) it "sends an invitation email to addresses in the legacy invited_emails field", (done) -> @TeamInvitesHandler.createTeamInvitesForLegacyInvitedEmail "PI:EMAIL:<EMAIL>END_PI", (err, invite) => expect(err).not.to.exist @TeamInvitesHandler.createInvite.calledWith( @subscription.admin_id, "PI:EMAIL:<EMAIL>END_PI" ).should.eq true @TeamInvitesHandler.createInvite.callCount.should.eq 1 done() describe "validation", -> it "doesn't create an invite if the team limit has been reached", (done) -> @LimitationsManager.teamHasReachedMemberLimit = sinon.stub().returns(true) @TeamInvitesHandler.createInvite @manager.id, "PI:EMAIL:<EMAIL>END_PI", (err, invite) => expect(err).to.deep.equal(limitReached: true) done() it "doesn't create an invite if the subscription is not in a group plan", (done) -> @subscription.groupPlan = false @TeamInvitesHandler.createInvite @manager.id, "PI:EMAIL:<EMAIL>END_PI", (err, invite) => expect(err).to.deep.equal(wrongPlan: true) done() it "doesn't create an invite if the user is already part of the team", (done) -> member = { id: "1a2b", _id: "1a2b", email: "PI:EMAIL:<EMAIL>END_PI" } @subscription.member_ids = [member.id] @UserGetter.getUserByAnyEmail.withArgs(member.email).yields(null, member) @TeamInvitesHandler.createInvite @manager.id, "PI:EMAIL:<EMAIL>END_PI", (err, invite) => expect(err).to.deep.equal(alreadyInTeam: true) expect(invite).not.to.exist done()
[ { "context": "sorry I ever had anything to do with it.\n > Erwin Schrödinger, Sorry\n foobar foobar\n foobar\n\n ", "end": 2276, "score": 0.9998116493225098, "start": 2259, "tag": "NAME", "value": "Erwin Schrödinger" }, { "context": "1\n expect(tokens[2][0]).toEqualJson value: '> Erwin Schrödinger, Sorry', scopes: ['source.asciidoc', 'markup.ital", "end": 2943, "score": 0.9996302723884583, "start": 2926, "tag": "NAME", "value": "Erwin Schrödinger" } ]
spec/blocks/quote-markdown-grammar-spec.coffee
andrewcarver/atom-language-asciidoc
45
describe 'Quotes with Markdown style', -> grammar = null beforeEach -> waitsForPromise -> atom.packages.activatePackage 'language-asciidoc' runs -> grammar = atom.grammars.grammarForScopeName 'source.asciidoc' it 'parses the grammar', -> expect(grammar).toBeDefined() expect(grammar.scopeName).toBe 'source.asciidoc' describe 'Should tokenizes when', -> it 'include inlines element', -> tokens = grammar.tokenizeLines ''' > I've got Markdown in my AsciiDoc! > > *strong* > Yep. AsciiDoc and Markdown share a lot of common syntax already. ''' expect(tokens).toHaveLength 4 expect(tokens[0]).toHaveLength 2 expect(tokens[0][0]).toEqualJson value: '> ', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[0][1]).toEqualJson value: 'I\'ve got Markdown in my AsciiDoc!', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[1]).toHaveLength 1 expect(tokens[1][0]).toEqualJson value: '>', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[2]).toHaveLength 4 expect(tokens[2][0]).toEqualJson value: '> ', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[2][1]).toEqualJson value: '*', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc', 'markup.strong.constrained.asciidoc', 'markup.bold.asciidoc', 'punctuation.definition.asciidoc'] expect(tokens[2][2]).toEqualJson value: 'strong', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc', 'markup.strong.constrained.asciidoc', 'markup.bold.asciidoc'] expect(tokens[2][3]).toEqualJson value: '*', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc', 'markup.strong.constrained.asciidoc', 'markup.bold.asciidoc', 'punctuation.definition.asciidoc'] expect(tokens[3]).toHaveLength 1 expect(tokens[3][0]).toEqualJson value: '> Yep. AsciiDoc and Markdown share a lot of common syntax already.', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] it 'contains multi-lines', -> tokens = grammar.tokenizeLines ''' foobar > I don't like it, and I'm sorry I ever had anything to do with it. > Erwin Schrödinger, Sorry foobar foobar foobar foobar ''' expect(tokens).toHaveLength 7 expect(tokens[0]).toHaveLength 1 expect(tokens[0][0]).toEqualJson value: 'foobar', scopes: ['source.asciidoc'] expect(tokens[1]).toHaveLength 2 expect(tokens[1][0]).toEqualJson value: '> ', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[1][1]).toEqualJson value: 'I don\'t like it, and I\'m sorry I ever had anything to do with it.', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[2]).toHaveLength 1 expect(tokens[2][0]).toEqualJson value: '> Erwin Schrödinger, Sorry', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[3]).toHaveLength 1 expect(tokens[3][0]).toEqualJson value: 'foobar foobar', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[4]).toHaveLength 1 expect(tokens[4][0]).toEqualJson value: 'foobar', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[5]).toHaveLength 1 expect(tokens[5][0]).toEqualJson value: '', scopes: ['source.asciidoc'] expect(tokens[6]).toHaveLength 1 expect(tokens[6][0]).toEqualJson value: 'foobar', scopes: ['source.asciidoc']
71043
describe 'Quotes with Markdown style', -> grammar = null beforeEach -> waitsForPromise -> atom.packages.activatePackage 'language-asciidoc' runs -> grammar = atom.grammars.grammarForScopeName 'source.asciidoc' it 'parses the grammar', -> expect(grammar).toBeDefined() expect(grammar.scopeName).toBe 'source.asciidoc' describe 'Should tokenizes when', -> it 'include inlines element', -> tokens = grammar.tokenizeLines ''' > I've got Markdown in my AsciiDoc! > > *strong* > Yep. AsciiDoc and Markdown share a lot of common syntax already. ''' expect(tokens).toHaveLength 4 expect(tokens[0]).toHaveLength 2 expect(tokens[0][0]).toEqualJson value: '> ', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[0][1]).toEqualJson value: 'I\'ve got Markdown in my AsciiDoc!', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[1]).toHaveLength 1 expect(tokens[1][0]).toEqualJson value: '>', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[2]).toHaveLength 4 expect(tokens[2][0]).toEqualJson value: '> ', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[2][1]).toEqualJson value: '*', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc', 'markup.strong.constrained.asciidoc', 'markup.bold.asciidoc', 'punctuation.definition.asciidoc'] expect(tokens[2][2]).toEqualJson value: 'strong', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc', 'markup.strong.constrained.asciidoc', 'markup.bold.asciidoc'] expect(tokens[2][3]).toEqualJson value: '*', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc', 'markup.strong.constrained.asciidoc', 'markup.bold.asciidoc', 'punctuation.definition.asciidoc'] expect(tokens[3]).toHaveLength 1 expect(tokens[3][0]).toEqualJson value: '> Yep. AsciiDoc and Markdown share a lot of common syntax already.', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] it 'contains multi-lines', -> tokens = grammar.tokenizeLines ''' foobar > I don't like it, and I'm sorry I ever had anything to do with it. > <NAME>, Sorry foobar foobar foobar foobar ''' expect(tokens).toHaveLength 7 expect(tokens[0]).toHaveLength 1 expect(tokens[0][0]).toEqualJson value: 'foobar', scopes: ['source.asciidoc'] expect(tokens[1]).toHaveLength 2 expect(tokens[1][0]).toEqualJson value: '> ', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[1][1]).toEqualJson value: 'I don\'t like it, and I\'m sorry I ever had anything to do with it.', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[2]).toHaveLength 1 expect(tokens[2][0]).toEqualJson value: '> <NAME>, Sorry', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[3]).toHaveLength 1 expect(tokens[3][0]).toEqualJson value: 'foobar foobar', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[4]).toHaveLength 1 expect(tokens[4][0]).toEqualJson value: 'foobar', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[5]).toHaveLength 1 expect(tokens[5][0]).toEqualJson value: '', scopes: ['source.asciidoc'] expect(tokens[6]).toHaveLength 1 expect(tokens[6][0]).toEqualJson value: 'foobar', scopes: ['source.asciidoc']
true
describe 'Quotes with Markdown style', -> grammar = null beforeEach -> waitsForPromise -> atom.packages.activatePackage 'language-asciidoc' runs -> grammar = atom.grammars.grammarForScopeName 'source.asciidoc' it 'parses the grammar', -> expect(grammar).toBeDefined() expect(grammar.scopeName).toBe 'source.asciidoc' describe 'Should tokenizes when', -> it 'include inlines element', -> tokens = grammar.tokenizeLines ''' > I've got Markdown in my AsciiDoc! > > *strong* > Yep. AsciiDoc and Markdown share a lot of common syntax already. ''' expect(tokens).toHaveLength 4 expect(tokens[0]).toHaveLength 2 expect(tokens[0][0]).toEqualJson value: '> ', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[0][1]).toEqualJson value: 'I\'ve got Markdown in my AsciiDoc!', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[1]).toHaveLength 1 expect(tokens[1][0]).toEqualJson value: '>', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[2]).toHaveLength 4 expect(tokens[2][0]).toEqualJson value: '> ', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[2][1]).toEqualJson value: '*', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc', 'markup.strong.constrained.asciidoc', 'markup.bold.asciidoc', 'punctuation.definition.asciidoc'] expect(tokens[2][2]).toEqualJson value: 'strong', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc', 'markup.strong.constrained.asciidoc', 'markup.bold.asciidoc'] expect(tokens[2][3]).toEqualJson value: '*', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc', 'markup.strong.constrained.asciidoc', 'markup.bold.asciidoc', 'punctuation.definition.asciidoc'] expect(tokens[3]).toHaveLength 1 expect(tokens[3][0]).toEqualJson value: '> Yep. AsciiDoc and Markdown share a lot of common syntax already.', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] it 'contains multi-lines', -> tokens = grammar.tokenizeLines ''' foobar > I don't like it, and I'm sorry I ever had anything to do with it. > PI:NAME:<NAME>END_PI, Sorry foobar foobar foobar foobar ''' expect(tokens).toHaveLength 7 expect(tokens[0]).toHaveLength 1 expect(tokens[0][0]).toEqualJson value: 'foobar', scopes: ['source.asciidoc'] expect(tokens[1]).toHaveLength 2 expect(tokens[1][0]).toEqualJson value: '> ', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[1][1]).toEqualJson value: 'I don\'t like it, and I\'m sorry I ever had anything to do with it.', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[2]).toHaveLength 1 expect(tokens[2][0]).toEqualJson value: '> PI:NAME:<NAME>END_PI, Sorry', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[3]).toHaveLength 1 expect(tokens[3][0]).toEqualJson value: 'foobar foobar', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[4]).toHaveLength 1 expect(tokens[4][0]).toEqualJson value: 'foobar', scopes: ['source.asciidoc', 'markup.italic.quotes.asciidoc'] expect(tokens[5]).toHaveLength 1 expect(tokens[5][0]).toEqualJson value: '', scopes: ['source.asciidoc'] expect(tokens[6]).toHaveLength 1 expect(tokens[6][0]).toEqualJson value: 'foobar', scopes: ['source.asciidoc']
[ { "context": " new FormData()\n fd.append('key1', 'value1')\n fd.append('key2', 'value2')\n ", "end": 2805, "score": 0.656977653503418, "start": 2804, "tag": "KEY", "value": "1" }, { "context": "ey1', 'value1')\n fd.append('key2', 'value2')\n string = up.params.toQuery(fd)\n ", "end": 2843, "score": 0.7961127161979675, "start": 2842, "tag": "KEY", "value": "2" }, { "context": " array = up.params.toArray(\n 'foo-key': 'foo-value'\n 'bar-key': 'bar-value'\n )\n ", "end": 3407, "score": 0.9532082676887512, "start": 3398, "tag": "KEY", "value": "foo-value" }, { "context": " 'foo-key': 'foo-value'\n 'bar-key': 'bar-value'\n )\n expect(array).toEqual([\n ", "end": 3440, "score": 0.9558727145195007, "start": 3431, "tag": "KEY", "value": "bar-value" }, { "context": "value' },\n { name: 'bar-key', value: 'bar-value' },\n ])\n\n it 'returns a given array w", "end": 3581, "score": 0.8176124095916748, "start": 3576, "tag": "KEY", "value": "value" }, { "context": " expect(array).toEqual([\n { name: 'äpfel', value: 'bäume' },\n ])\n\n it 'does ", "end": 4149, "score": 0.6288712620735168, "start": 4147, "tag": "NAME", "value": "pf" }, { "context": " {\n key1: 'value1',\n key2: 'value2'\n }\n formData = up.params.toFor", "end": 5891, "score": 0.9534575939178467, "start": 5885, "tag": "KEY", "value": "value2" }, { "context": "a)).toEqual [\n { name: 'key1', value: 'value1' },\n { name: 'key2', value: 'value2' }", "end": 6053, "score": 0.944692850112915, "start": 6047, "tag": "KEY", "value": "value1" }, { "context": ": 'value1' },\n { name: 'key2', value: 'value2' },\n ]\n\n it 'returns a FormData o", "end": 6100, "score": 0.8382376432418823, "start": 6094, "tag": "KEY", "value": "value2" }, { "context": "a)).toEqual [\n { name: 'key1', value: 'value1' },\n { name: 'key2', value: 'value2' }", "end": 6551, "score": 0.888830304145813, "start": 6545, "tag": "KEY", "value": "value1" }, { "context": ": 'value1' },\n { name: 'key2', value: 'value2' },\n ]\n\n it 'unescapes percent-en", "end": 6598, "score": 0.6386988162994385, "start": 6592, "tag": "KEY", "value": "value2" }, { "context": ").toEqual [\n { name: 'key', value: 'value2' }\n ]\n\n it 'includes a checked <input", "end": 24441, "score": 0.5930126905441284, "start": 24440, "tag": "KEY", "value": "2" } ]
spec_app/spec/javascripts/up/params_spec.coffee
ktec/unpoly
0
describe 'up.params', -> u = up.util describe 'JavaScript functions', -> encodeBrackets = (str) -> str = str.replace(/\[/g, '%5B') str = str.replace(/\]/g, '%5D') str beforeEach -> jasmine.addMatchers toEqualAfterEncodingBrackets: (util, customEqualityTesters) -> compare: (actual, expected) -> pass: actual == encodeBrackets(expected) describe 'up.params.toQuery', -> # encodedOpeningBracket = '%5B' # encodedClosingBracket = '%5D' encodedSpace = '%20' it 'returns the query section for the given object', -> string = up.params.toQuery('foo-key': 'foo value', 'bar-key': 'bar value') expect(string).toEqual("foo-key=foo#{encodedSpace}value&bar-key=bar#{encodedSpace}value") it 'returns the query section for the given array with { name } and { value } keys', -> string = up.params.toQuery([ { name: 'foo-key', value: 'foo value' }, { name: 'bar-key', value: 'bar value' } ]) expect(string).toEqual("foo-key=foo#{encodedSpace}value&bar-key=bar#{encodedSpace}value") it 'returns a given query string', -> string = up.params.toQuery('foo=bar') expect(string).toEqual('foo=bar') it 'returns an empty string for an empty object', -> string = up.params.toQuery({}) expect(string).toEqual('') it 'returns an empty string for an empty string', -> string = up.params.toQuery('') expect(string).toEqual('') it 'returns an empty string for undefined', -> string = up.params.toQuery(undefined) expect(string).toEqual('') it 'URL-encodes characters in the key and value', -> string = up.params.toQuery({ 'äpfel': 'bäume' }) expect(string).toEqual('%C3%A4pfel=b%C3%A4ume') it "sets a blank value after the equal sign if a key's value is a blank string", -> string = up.params.toQuery({'foo': ''}) expect(string).toEqual('foo=') it 'omits non-primitive values (like Files) from the given params', -> # I would like to construct a File, but IE11 does not support the constructor blob = new Blob([]) string = up.params.toQuery(string: 'foo', blob: blob) expect(string).toEqual('string=foo') it "omits an equal sign if a key's value is null", -> string = up.params.toQuery({'foo': null}) expect(string).toEqual('foo') it 'URL-encodes plus characters', -> string = up.params.toQuery({ 'my+key': 'my+value' }) expect(string).toEqual('my%2Bkey=my%2Bvalue') describeCapability 'canInspectFormData', -> it 'converts a FormData object to a query string', -> fd = new FormData() fd.append('key1', 'value1') fd.append('key2', 'value2') string = up.params.toQuery(fd) expect(string).toEqual('key1=value1&key2=value2') describe 'up.params.toArray', -> it 'normalized null to an empty array', -> array = up.params.toArray(null) expect(array).toEqual([]) it 'normalized undefined to an empty array', -> array = up.params.toArray(undefined) expect(array).toEqual([]) it 'normalizes an object hash to an array of objects with { name } and { value } keys', -> array = up.params.toArray( 'foo-key': 'foo-value' 'bar-key': 'bar-value' ) expect(array).toEqual([ { name: 'foo-key', value: 'foo-value' }, { name: 'bar-key', value: 'bar-value' }, ]) it 'returns a given array without modification', -> array = up.params.toArray([ { name: 'foo-key', value: 'foo-value' }, { name: 'bar-key', value: 'bar-value' }, ]) expect(array).toEqual([ { name: 'foo-key', value: 'foo-value' }, { name: 'bar-key', value: 'bar-value' }, ]) it 'does not URL-encode special characters in keys or values', -> array = up.params.toArray( 'äpfel': 'bäume' ) expect(array).toEqual([ { name: 'äpfel', value: 'bäume' }, ]) it 'does not URL-encode spaces in keys or values', -> array = up.params.toArray( 'my key': 'my value' ) expect(array).toEqual([ { name: 'my key', value: 'my value' }, ]) it 'does not URL-encode ampersands in keys or values', -> array = up.params.toArray( 'my&key': 'my&value' ) expect(array).toEqual([ { name: 'my&key', value: 'my&value' }, ]) it 'does not URL-encode equal signs in keys or values', -> array = up.params.toArray( 'my=key': 'my=value' ) expect(array).toEqual([ { name: 'my=key', value: 'my=value' }, ]) describeCapability 'canInspectFormData', -> it 'converts a FormData object to an array', -> fd = new FormData() fd.append('key1', 'value1') fd.append('key2', 'value2') array = up.params.toArray(fd) expect(array).toEqual([ { name: 'key1', value: 'value1' }, { name: 'key2', value: 'value2' }, ]) describe 'up.params.toFormData', -> describeCapability 'canInspectFormData', -> it 'converts undefined to an empty FormData object', -> params = undefined formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [] it 'converts null to an empty FormData object', -> params = null formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [] it 'converts an object to a FormData object', -> params = { key1: 'value1', key2: 'value2' } formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [ { name: 'key1', value: 'value1' }, { name: 'key2', value: 'value2' }, ] it 'returns a FormData object unchanged', -> params = new FormData() formData = up.params.toFormData(params) expect(formData).toBe(params) it 'converts a query string to a FormData object', -> params = 'key1=value1&key2=value2' formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [ { name: 'key1', value: 'value1' }, { name: 'key2', value: 'value2' }, ] it 'unescapes percent-encoded characters from a query string', -> params = 'my%20key=my%20value' formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [ { name: 'my key', value: 'my value' } ] describe 'up.params.toObject', -> it "parses flat key/value pairs", -> expect(up.params.toObject("xfoo")).toEqual("xfoo": null) expect(up.params.toObject("foo=")).toEqual("foo": "") expect(up.params.toObject("foo=bar")).toEqual("foo": "bar") expect(up.params.toObject("foo=\"bar\"")).toEqual("foo": "\"bar\"") expect(up.params.toObject("foo=bar&foo=quux")).toEqual("foo": "quux") expect(up.params.toObject("foo&foo=")).toEqual("foo": "") expect(up.params.toObject("foo=1&bar=2")).toEqual("foo": "1", "bar": "2") expect(up.params.toObject("&foo=1&&bar=2")).toEqual("foo": "1", "bar": "2") expect(up.params.toObject("foo&bar=")).toEqual("foo": null, "bar": "") expect(up.params.toObject("foo=bar&baz=")).toEqual("foo": "bar", "baz": "") it 'URL-decodes keys and values', -> expect(up.params.toObject("my%20weird%20field=q1%212%22%27w%245%267%2Fz8%29%3F")).toEqual("my weird field": "q1!2\"'w$5&7/z8)?") expect(up.params.toObject("a=b&pid%3D1234=1023")).toEqual("pid=1234": "1023", "a": "b") # expect(-> up.params.toObject("foo%81E=1")).toThrowError() # invalid byte sequence in UTF-8 it 'ignores keys that would overwrite an Object prototype property', -> obj = up.params.toObject("foo=bar&hasOwnProperty=baz") expect(obj['foo']).toEqual('bar') expect(u.isFunction obj['hasOwnProperty']).toBe(true) describe 'up.params.add', -> describe '(with object)', -> it 'adds a single key and value', -> obj = { foo: 'one' } obj = up.params.add(obj, 'bar', 'two') expect(obj).toEqual { foo: 'one', bar: 'two' } describe '(with array)', -> it 'adds a single key and value', -> obj = [{ name: 'foo', value: 'one' }] obj = up.params.add(obj, 'bar', 'two') expect(obj).toEqual [{ name: 'foo', value: 'one' }, { name: 'bar', value: 'two' }] describe '(with query string)', -> it 'adds a new key/value pair to the end of a query', -> query = 'foo=one' query = up.params.add(query, 'bar', 'two') expect(query).toEqual('foo=one&bar=two') it 'does not add superfluous ampersands if the previous query was a blank string', -> query = '' query = up.params.add(query, 'bar', 'two') expect(query).toEqual('bar=two') it 'escapes special characters in the new key and value', -> query = 'foo=one' query = up.params.add(query, 'bär', 'twö') expect(query).toEqual('foo=one&b%C3%A4r=tw%C3%B6') describe '(with FormData)', -> describeCapability 'canInspectFormData', -> it 'adds a single entry', -> formData = new FormData() formData.append('key1', 'value1') up.params.add(formData, 'key2', 'value2') expect(up.params.toArray(formData)).toEqual [ { name: 'key1', value: 'value1' }, { name: 'key2', value: 'value2' }, ] describe '(with missing params)', -> it 'returns an object with only the new key and value', -> obj = undefined obj = up.params.add(obj, 'bar', 'two') expect(obj).toEqual { bar: 'two' } describe 'up.params.get', -> describe '(with object)', -> it 'returns the value for the given name', -> obj = { foo: 'one', bar: 'two' } value = up.params.get(obj, 'bar') expect(value).toEqual('two') it 'returns undefined if no value is set for the given name', -> obj = { foo: 'one' } value = up.params.get(obj, 'bar') expect(value).toBeUndefined() it 'returns undefined for names that are also a basic object property', -> obj = {} value = up.params.get(obj, 'hasOwnProperty') expect(value).toBeUndefined() describe '(with array)', -> it 'returns the value of the first entry with the given name', -> array = [ { name: 'foo', value: 'one' } { name: 'bar', value: 'two' } { name: 'foo', value: 'three' } ] value = up.params.get(array, 'foo') expect(value).toEqual('one') it 'returns undefined if there is no entry with the given name', -> array = [ { name: 'foo', value: 'one' } ] value = up.params.get(array, 'bar') expect(value).toBeUndefined() describe '(with query string)', -> it 'returns the query param with the given name', -> query = 'foo=one&bar=two' value = up.params.get(query, 'bar') expect(value).toEqual('two') it 'returns undefined if there is no query param with the given name', -> query = 'foo=one' query = up.params.get(query, 'bar') expect(query).toBeUndefined() it 'unescapes percent-encoded characters in the returned value', -> query = 'foo=one%20two' value = up.params.get(query, 'foo') expect(value).toEqual('one two') describe '(with FormData)', -> describeCapability 'canInspectFormData', -> it 'returns the first entry with the given name', -> formData = new FormData() formData.append('key1', 'value1') formData.append('key2', 'value2') value = up.params.get(formData, 'key2') expect(value).toEqual('value2') it 'returns undefined if there is no entry with the given name', -> formData = new FormData() value = up.params.get(formData, 'key') expect(value).toBeUndefined() describe '(with missing params)', -> it 'returns undefined', -> params = undefined value = up.params.get(params, 'foo') expect(value).toBeUndefined() describe 'up.params.merge', -> describe '(with object)', -> it 'merges a flat object', -> obj = { a: '1', b: '2' } other = { c: '3', d: '4'} obj = up.params.merge(obj, other) expect(obj).toEqual({ a: '1', b: '2', c: '3', d: '4' }) it 'merges an array', -> obj = { a: '1', b: '2' } other = [ { name: 'c', value: '3' }, { name: 'd', value: '4' } ] obj = up.params.merge(obj, other) expect(obj).toEqual({ a: '1', b: '2', c: '3', d: '4' }) it 'merges a query string', -> obj = { a: '1', b: '2' } other = 'c=3&d=4' obj = up.params.merge(obj, other) expect(obj).toEqual({ a: '1', b: '2', c: '3', d: '4' }) it 'does not change or crash when merged with undefined', -> obj = { a: '1', b: '2' } obj = up.params.merge(obj, undefined) expect(obj).toEqual({ a: '1', b: '2' }) describeCapability 'canInspectFormData', -> it 'merges a FormData object', -> obj = { a: '1', b: '2' } formData = new FormData() formData.append('c', '3') formData.append('d', '4') merged = up.params.merge(obj, formData) expect(merged).toEqual({ a: '1', b: '2', c: '3', d: '4' }) describe '(with array)', -> it 'merges a flat object', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] other = { c: '3', d: '4'} array = up.params.merge(array, other) expect(array).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' }, { name: 'c', value: '3' }, { name: 'd', value: '4' } ] it 'merges another array', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] other = [ { name: 'c', value: '3' }, { name: 'd', value: '4' } ] array = up.params.merge(array, other) expect(array).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' }, { name: 'c', value: '3' }, { name: 'd', value: '4' } ] it 'merges a query string', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] other = 'c=3&d=4' array = up.params.merge(array, other) expect(array).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' }, { name: 'c', value: '3' }, { name: 'd', value: '4' } ] it 'does not change or crash when merged with undefined', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] array = up.params.merge(array, undefined) expect(array).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] describeCapability 'canInspectFormData', -> it 'merges a FormData object', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] formData = new FormData() formData.append('c', '3') formData.append('d', '4') merged = up.params.merge(array, formData) expect(merged).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' }, { name: 'c', value: '3' }, { name: 'd', value: '4' } ] describe '(with query)', -> it 'merges a flat object', -> query = 'a=1&b=2' other = { c: '3', d: '4'} query = up.params.merge(query, other) expect(query).toEqual('a=1&b=2&c=3&d=4') it 'merges an array', -> query = 'a=1&b=2' other = [ { name: 'c', value: '3' }, { name: 'd', value: '4' } ] query = up.params.merge(query, other) expect(query).toEqual('a=1&b=2&c=3&d=4') it 'merges another query string', -> query = 'a=1&b=2' other = 'c=3&d=4' query = up.params.merge(query, other) expect(query).toEqual('a=1&b=2&c=3&d=4') it 'does not change or crash when merged with undefined', -> query = 'a=1&b=2' query = up.params.merge(query, undefined) expect(query).toEqual('a=1&b=2') describeCapability 'canInspectFormData', -> it 'merges a FormData object', -> query = 'a=1&b=2' formData = new FormData() formData.append('c', '3') formData.append('d', '4') merged = up.params.merge(query, formData) expect(merged).toEqual('a=1&b=2&c=3&d=4') describe 'up.params.buildURL', -> it 'composes a URL from a base URL (without query section) and a query section', -> base = 'http://foo.bar/path' query = 'key=value' expect(up.params.buildURL(base, query)).toEqual('http://foo.bar/path?key=value') it 'accepts other forms of params (instead of query sections)', -> base = 'http://foo.bar/path' params = { key: 'value' } expect(up.params.buildURL(base, params)).toEqual('http://foo.bar/path?key=value') it 'adds more params to a base URL that already has a query section', -> base = 'http://foo.bar/path?key1=value1' params = { key2: 'value2' } expect(up.params.buildURL(base, params)).toEqual('http://foo.bar/path?key1=value1&key2=value2') it 'does not add a question mark to the base URL if the given params are blank', -> base = 'http://foo.bar/path' params = '' expect(up.params.buildURL(base, params)).toEqual('http://foo.bar/path') describe 'up.params.fromURL', -> it 'returns the query section from an URL, without leading question mark', -> url = 'http://foo.bar/path?key=value' expect(up.params.fromURL(url)).toEqual('key=value') it 'returns undefined if the URL has no query section', -> url = 'http://foo.bar/path' expect(up.params.fromURL(url)).toBeUndefined() describe 'up.params.fromForm', -> it 'serializes a form with multiple inputs', -> $form = affix('form') $form.append('<input name="key1" value="value1">') $form.append('<input name="key2" value="value2">') params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key1', value: 'value1' }, { name: 'key2', value: 'value2' }, ] it 'serializes an <input type="text"> with its default [value]', -> $form = affix('form') $form.append('<input type="text" name="key" value="value-from-attribute">') params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value-from-attribute' } ] it 'serializes an <input type="text"> that had its value property changed by a script', -> $form = affix('form') $input = $('<input type="text" name="key" value="value-from-attribute">').appendTo($form) $input[0].value = 'value-from-script' params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value-from-script' } ] it 'serializes an <input type="hidden"> with its default [value]', -> $form = affix('form') $form.append('<input type="hidden" name="key" value="value-from-attribute">') params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value-from-attribute' } ] it 'serializes an <input type="hidden"> that had its value property changed by a script', -> $form = affix('form') $input = $('<input type="hidden" name="key" value="value-from-attribute">').appendTo($form) $input[0].value = 'value-from-script' params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value-from-script' } ] it 'seralizes a <select> with its default selected option', -> $form = affix('form') $select = $('<select name="key"></select>').appendTo($form) $option1 = $('<option value="value1">').appendTo($select) $option2 = $('<option value="value2" selected>').appendTo($select) $option3 = $('<option value="value3">').appendTo($select) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value2' } ] it 'seralizes a <select> that had its selection changed by a script', -> $form = affix('form') $select = $('<select name="key"></select>').appendTo($form) $option1 = $('<option value="value1">').appendTo($select) $option2 = $('<option value="value2" selected>').appendTo($select) $option3 = $('<option value="value3">').appendTo($select) $option2[0].selected = false $option3[0].selected = true params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value3' } ] it 'serializes a <select multiple> with multiple selected options into multiple params', -> $form = affix('form') $select = $('<select name="key" multiple></select>').appendTo($form) $option1 = $('<option value="value1">').appendTo($select) $option2 = $('<option value="value2" selected>').appendTo($select) $option3 = $('<option value="value3" selected>').appendTo($select) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value2' }, { name: 'key', value: 'value3' } ] it 'serializes an <input type="file">' it 'serializes an <input type="file" multiple> into multiple params' it 'includes an <input type="checkbox"> that was [checked] by default', -> $form = affix('form') $input = $('<input type="checkbox" name="key" value="value" checked>').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value' } ] it 'includes an <input type="checkbox"> that was checked by a script', -> $form = affix('form') $input = $('<input type="checkbox" name="key" value="value">').appendTo($form) $input[0].checked = true params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value' } ] it 'excludes an <input type="checkbox"> that is unchecked', -> $form = affix('form') $input = $('<input type="checkbox" name="key" value="value">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [] it 'includes a checked <input type="radio"> in a radio button group that was [checked] by default', -> $form = affix('form') $button1 = $('<input type="radio" name="key" value="value1">').appendTo($form) $button2 = $('<input type="radio" name="key" value="value2" checked>').appendTo($form) $button3 = $('<input type="radio" name="key" value="value3">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value2' } ] it 'includes a checked <input type="radio"> in a radio button group that was checked by a script', -> $form = affix('form') $button1 = $('<input type="radio" name="key" value="value1">').appendTo($form) $button2 = $('<input type="radio" name="key" value="value2" checked>').appendTo($form) $button3 = $('<input type="radio" name="key" value="value3">').appendTo($form) $button2[0].checked = false $button3[0].checked = true params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value3' } ] it 'excludes an radio button group if no button is selected', -> $form = affix('form') $button1 = $('<input type="radio" name="key" value="value1">').appendTo($form) $button2 = $('<input type="radio" name="key" value="value2">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [] it 'excludes an <input> that is [disabled] by default', -> $form = affix('form') $input = $('<input type="text" name="key" value="value" disabled>').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [] it 'excludes an <input> that was disabled by a script', -> $form = affix('form') $input = $('<input type="text" name="key" value="value">').appendTo($form) $input[0].disabled = true params = up.params.fromForm($form) expect(params).toEqual [] it 'excludes an <input> without a [name] attribute', -> $form = affix('form') $input = $('<input type="text" value="value">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [] it 'includes an <input readonly>', -> $form = affix('form') $input = $('<input type="text" name="key" value="value" readonly>').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value' } ] it 'includes the focused submit button', -> $form = affix('form') $input = $('<input type="text" name="input-key" value="input-value">').appendTo($form) $submit1 = $('<button type="submit" name="submit1-key" value="submit1-value">').appendTo($form) $submit2 = $('<input type="submit" name="submit2-key" value="submit2-value">').appendTo($form) $submit3 = $('<input type="submit" name="submit3-key" value="submit3-value">').appendTo($form) $submit2.focus() params = up.params.fromForm($form) expect(params).toEqual [ { name: 'input-key', value: 'input-value' }, { name: 'submit2-key', value: 'submit2-value' } ] it 'includes a the first submit button if no button is focused', -> $form = affix('form') $input = $('<input type="text" name="input-key" value="input-value">').appendTo($form) $submit1 = $('<button type="submit" name="submit1-key" value="submit1-value">').appendTo($form) $submit2 = $('<input type="submit" name="submit2-key" value="submit2-value">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'input-key', value: 'input-value' }, { name: 'submit1-key', value: 'submit1-value' } ] it 'excludes a submit button without a [name] attribute', -> $form = affix('form') $input = $('<input type="text" name="input-key" value="input-value">').appendTo($form) $submit = $('<button type="submit" value="submit-value">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'input-key', value: 'input-value' } ]
50944
describe 'up.params', -> u = up.util describe 'JavaScript functions', -> encodeBrackets = (str) -> str = str.replace(/\[/g, '%5B') str = str.replace(/\]/g, '%5D') str beforeEach -> jasmine.addMatchers toEqualAfterEncodingBrackets: (util, customEqualityTesters) -> compare: (actual, expected) -> pass: actual == encodeBrackets(expected) describe 'up.params.toQuery', -> # encodedOpeningBracket = '%5B' # encodedClosingBracket = '%5D' encodedSpace = '%20' it 'returns the query section for the given object', -> string = up.params.toQuery('foo-key': 'foo value', 'bar-key': 'bar value') expect(string).toEqual("foo-key=foo#{encodedSpace}value&bar-key=bar#{encodedSpace}value") it 'returns the query section for the given array with { name } and { value } keys', -> string = up.params.toQuery([ { name: 'foo-key', value: 'foo value' }, { name: 'bar-key', value: 'bar value' } ]) expect(string).toEqual("foo-key=foo#{encodedSpace}value&bar-key=bar#{encodedSpace}value") it 'returns a given query string', -> string = up.params.toQuery('foo=bar') expect(string).toEqual('foo=bar') it 'returns an empty string for an empty object', -> string = up.params.toQuery({}) expect(string).toEqual('') it 'returns an empty string for an empty string', -> string = up.params.toQuery('') expect(string).toEqual('') it 'returns an empty string for undefined', -> string = up.params.toQuery(undefined) expect(string).toEqual('') it 'URL-encodes characters in the key and value', -> string = up.params.toQuery({ 'äpfel': 'bäume' }) expect(string).toEqual('%C3%A4pfel=b%C3%A4ume') it "sets a blank value after the equal sign if a key's value is a blank string", -> string = up.params.toQuery({'foo': ''}) expect(string).toEqual('foo=') it 'omits non-primitive values (like Files) from the given params', -> # I would like to construct a File, but IE11 does not support the constructor blob = new Blob([]) string = up.params.toQuery(string: 'foo', blob: blob) expect(string).toEqual('string=foo') it "omits an equal sign if a key's value is null", -> string = up.params.toQuery({'foo': null}) expect(string).toEqual('foo') it 'URL-encodes plus characters', -> string = up.params.toQuery({ 'my+key': 'my+value' }) expect(string).toEqual('my%2Bkey=my%2Bvalue') describeCapability 'canInspectFormData', -> it 'converts a FormData object to a query string', -> fd = new FormData() fd.append('key1', 'value<KEY>') fd.append('key2', 'value<KEY>') string = up.params.toQuery(fd) expect(string).toEqual('key1=value1&key2=value2') describe 'up.params.toArray', -> it 'normalized null to an empty array', -> array = up.params.toArray(null) expect(array).toEqual([]) it 'normalized undefined to an empty array', -> array = up.params.toArray(undefined) expect(array).toEqual([]) it 'normalizes an object hash to an array of objects with { name } and { value } keys', -> array = up.params.toArray( 'foo-key': '<KEY>' 'bar-key': '<KEY>' ) expect(array).toEqual([ { name: 'foo-key', value: 'foo-value' }, { name: 'bar-key', value: 'bar-<KEY>' }, ]) it 'returns a given array without modification', -> array = up.params.toArray([ { name: 'foo-key', value: 'foo-value' }, { name: 'bar-key', value: 'bar-value' }, ]) expect(array).toEqual([ { name: 'foo-key', value: 'foo-value' }, { name: 'bar-key', value: 'bar-value' }, ]) it 'does not URL-encode special characters in keys or values', -> array = up.params.toArray( 'äpfel': 'bäume' ) expect(array).toEqual([ { name: 'ä<NAME>el', value: 'bäume' }, ]) it 'does not URL-encode spaces in keys or values', -> array = up.params.toArray( 'my key': 'my value' ) expect(array).toEqual([ { name: 'my key', value: 'my value' }, ]) it 'does not URL-encode ampersands in keys or values', -> array = up.params.toArray( 'my&key': 'my&value' ) expect(array).toEqual([ { name: 'my&key', value: 'my&value' }, ]) it 'does not URL-encode equal signs in keys or values', -> array = up.params.toArray( 'my=key': 'my=value' ) expect(array).toEqual([ { name: 'my=key', value: 'my=value' }, ]) describeCapability 'canInspectFormData', -> it 'converts a FormData object to an array', -> fd = new FormData() fd.append('key1', 'value1') fd.append('key2', 'value2') array = up.params.toArray(fd) expect(array).toEqual([ { name: 'key1', value: 'value1' }, { name: 'key2', value: 'value2' }, ]) describe 'up.params.toFormData', -> describeCapability 'canInspectFormData', -> it 'converts undefined to an empty FormData object', -> params = undefined formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [] it 'converts null to an empty FormData object', -> params = null formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [] it 'converts an object to a FormData object', -> params = { key1: 'value1', key2: '<KEY>' } formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [ { name: 'key1', value: '<KEY>' }, { name: 'key2', value: '<KEY>' }, ] it 'returns a FormData object unchanged', -> params = new FormData() formData = up.params.toFormData(params) expect(formData).toBe(params) it 'converts a query string to a FormData object', -> params = 'key1=value1&key2=value2' formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [ { name: 'key1', value: '<KEY>' }, { name: 'key2', value: '<KEY>' }, ] it 'unescapes percent-encoded characters from a query string', -> params = 'my%20key=my%20value' formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [ { name: 'my key', value: 'my value' } ] describe 'up.params.toObject', -> it "parses flat key/value pairs", -> expect(up.params.toObject("xfoo")).toEqual("xfoo": null) expect(up.params.toObject("foo=")).toEqual("foo": "") expect(up.params.toObject("foo=bar")).toEqual("foo": "bar") expect(up.params.toObject("foo=\"bar\"")).toEqual("foo": "\"bar\"") expect(up.params.toObject("foo=bar&foo=quux")).toEqual("foo": "quux") expect(up.params.toObject("foo&foo=")).toEqual("foo": "") expect(up.params.toObject("foo=1&bar=2")).toEqual("foo": "1", "bar": "2") expect(up.params.toObject("&foo=1&&bar=2")).toEqual("foo": "1", "bar": "2") expect(up.params.toObject("foo&bar=")).toEqual("foo": null, "bar": "") expect(up.params.toObject("foo=bar&baz=")).toEqual("foo": "bar", "baz": "") it 'URL-decodes keys and values', -> expect(up.params.toObject("my%20weird%20field=q1%212%22%27w%245%267%2Fz8%29%3F")).toEqual("my weird field": "q1!2\"'w$5&7/z8)?") expect(up.params.toObject("a=b&pid%3D1234=1023")).toEqual("pid=1234": "1023", "a": "b") # expect(-> up.params.toObject("foo%81E=1")).toThrowError() # invalid byte sequence in UTF-8 it 'ignores keys that would overwrite an Object prototype property', -> obj = up.params.toObject("foo=bar&hasOwnProperty=baz") expect(obj['foo']).toEqual('bar') expect(u.isFunction obj['hasOwnProperty']).toBe(true) describe 'up.params.add', -> describe '(with object)', -> it 'adds a single key and value', -> obj = { foo: 'one' } obj = up.params.add(obj, 'bar', 'two') expect(obj).toEqual { foo: 'one', bar: 'two' } describe '(with array)', -> it 'adds a single key and value', -> obj = [{ name: 'foo', value: 'one' }] obj = up.params.add(obj, 'bar', 'two') expect(obj).toEqual [{ name: 'foo', value: 'one' }, { name: 'bar', value: 'two' }] describe '(with query string)', -> it 'adds a new key/value pair to the end of a query', -> query = 'foo=one' query = up.params.add(query, 'bar', 'two') expect(query).toEqual('foo=one&bar=two') it 'does not add superfluous ampersands if the previous query was a blank string', -> query = '' query = up.params.add(query, 'bar', 'two') expect(query).toEqual('bar=two') it 'escapes special characters in the new key and value', -> query = 'foo=one' query = up.params.add(query, 'bär', 'twö') expect(query).toEqual('foo=one&b%C3%A4r=tw%C3%B6') describe '(with FormData)', -> describeCapability 'canInspectFormData', -> it 'adds a single entry', -> formData = new FormData() formData.append('key1', 'value1') up.params.add(formData, 'key2', 'value2') expect(up.params.toArray(formData)).toEqual [ { name: 'key1', value: 'value1' }, { name: 'key2', value: 'value2' }, ] describe '(with missing params)', -> it 'returns an object with only the new key and value', -> obj = undefined obj = up.params.add(obj, 'bar', 'two') expect(obj).toEqual { bar: 'two' } describe 'up.params.get', -> describe '(with object)', -> it 'returns the value for the given name', -> obj = { foo: 'one', bar: 'two' } value = up.params.get(obj, 'bar') expect(value).toEqual('two') it 'returns undefined if no value is set for the given name', -> obj = { foo: 'one' } value = up.params.get(obj, 'bar') expect(value).toBeUndefined() it 'returns undefined for names that are also a basic object property', -> obj = {} value = up.params.get(obj, 'hasOwnProperty') expect(value).toBeUndefined() describe '(with array)', -> it 'returns the value of the first entry with the given name', -> array = [ { name: 'foo', value: 'one' } { name: 'bar', value: 'two' } { name: 'foo', value: 'three' } ] value = up.params.get(array, 'foo') expect(value).toEqual('one') it 'returns undefined if there is no entry with the given name', -> array = [ { name: 'foo', value: 'one' } ] value = up.params.get(array, 'bar') expect(value).toBeUndefined() describe '(with query string)', -> it 'returns the query param with the given name', -> query = 'foo=one&bar=two' value = up.params.get(query, 'bar') expect(value).toEqual('two') it 'returns undefined if there is no query param with the given name', -> query = 'foo=one' query = up.params.get(query, 'bar') expect(query).toBeUndefined() it 'unescapes percent-encoded characters in the returned value', -> query = 'foo=one%20two' value = up.params.get(query, 'foo') expect(value).toEqual('one two') describe '(with FormData)', -> describeCapability 'canInspectFormData', -> it 'returns the first entry with the given name', -> formData = new FormData() formData.append('key1', 'value1') formData.append('key2', 'value2') value = up.params.get(formData, 'key2') expect(value).toEqual('value2') it 'returns undefined if there is no entry with the given name', -> formData = new FormData() value = up.params.get(formData, 'key') expect(value).toBeUndefined() describe '(with missing params)', -> it 'returns undefined', -> params = undefined value = up.params.get(params, 'foo') expect(value).toBeUndefined() describe 'up.params.merge', -> describe '(with object)', -> it 'merges a flat object', -> obj = { a: '1', b: '2' } other = { c: '3', d: '4'} obj = up.params.merge(obj, other) expect(obj).toEqual({ a: '1', b: '2', c: '3', d: '4' }) it 'merges an array', -> obj = { a: '1', b: '2' } other = [ { name: 'c', value: '3' }, { name: 'd', value: '4' } ] obj = up.params.merge(obj, other) expect(obj).toEqual({ a: '1', b: '2', c: '3', d: '4' }) it 'merges a query string', -> obj = { a: '1', b: '2' } other = 'c=3&d=4' obj = up.params.merge(obj, other) expect(obj).toEqual({ a: '1', b: '2', c: '3', d: '4' }) it 'does not change or crash when merged with undefined', -> obj = { a: '1', b: '2' } obj = up.params.merge(obj, undefined) expect(obj).toEqual({ a: '1', b: '2' }) describeCapability 'canInspectFormData', -> it 'merges a FormData object', -> obj = { a: '1', b: '2' } formData = new FormData() formData.append('c', '3') formData.append('d', '4') merged = up.params.merge(obj, formData) expect(merged).toEqual({ a: '1', b: '2', c: '3', d: '4' }) describe '(with array)', -> it 'merges a flat object', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] other = { c: '3', d: '4'} array = up.params.merge(array, other) expect(array).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' }, { name: 'c', value: '3' }, { name: 'd', value: '4' } ] it 'merges another array', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] other = [ { name: 'c', value: '3' }, { name: 'd', value: '4' } ] array = up.params.merge(array, other) expect(array).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' }, { name: 'c', value: '3' }, { name: 'd', value: '4' } ] it 'merges a query string', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] other = 'c=3&d=4' array = up.params.merge(array, other) expect(array).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' }, { name: 'c', value: '3' }, { name: 'd', value: '4' } ] it 'does not change or crash when merged with undefined', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] array = up.params.merge(array, undefined) expect(array).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] describeCapability 'canInspectFormData', -> it 'merges a FormData object', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] formData = new FormData() formData.append('c', '3') formData.append('d', '4') merged = up.params.merge(array, formData) expect(merged).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' }, { name: 'c', value: '3' }, { name: 'd', value: '4' } ] describe '(with query)', -> it 'merges a flat object', -> query = 'a=1&b=2' other = { c: '3', d: '4'} query = up.params.merge(query, other) expect(query).toEqual('a=1&b=2&c=3&d=4') it 'merges an array', -> query = 'a=1&b=2' other = [ { name: 'c', value: '3' }, { name: 'd', value: '4' } ] query = up.params.merge(query, other) expect(query).toEqual('a=1&b=2&c=3&d=4') it 'merges another query string', -> query = 'a=1&b=2' other = 'c=3&d=4' query = up.params.merge(query, other) expect(query).toEqual('a=1&b=2&c=3&d=4') it 'does not change or crash when merged with undefined', -> query = 'a=1&b=2' query = up.params.merge(query, undefined) expect(query).toEqual('a=1&b=2') describeCapability 'canInspectFormData', -> it 'merges a FormData object', -> query = 'a=1&b=2' formData = new FormData() formData.append('c', '3') formData.append('d', '4') merged = up.params.merge(query, formData) expect(merged).toEqual('a=1&b=2&c=3&d=4') describe 'up.params.buildURL', -> it 'composes a URL from a base URL (without query section) and a query section', -> base = 'http://foo.bar/path' query = 'key=value' expect(up.params.buildURL(base, query)).toEqual('http://foo.bar/path?key=value') it 'accepts other forms of params (instead of query sections)', -> base = 'http://foo.bar/path' params = { key: 'value' } expect(up.params.buildURL(base, params)).toEqual('http://foo.bar/path?key=value') it 'adds more params to a base URL that already has a query section', -> base = 'http://foo.bar/path?key1=value1' params = { key2: 'value2' } expect(up.params.buildURL(base, params)).toEqual('http://foo.bar/path?key1=value1&key2=value2') it 'does not add a question mark to the base URL if the given params are blank', -> base = 'http://foo.bar/path' params = '' expect(up.params.buildURL(base, params)).toEqual('http://foo.bar/path') describe 'up.params.fromURL', -> it 'returns the query section from an URL, without leading question mark', -> url = 'http://foo.bar/path?key=value' expect(up.params.fromURL(url)).toEqual('key=value') it 'returns undefined if the URL has no query section', -> url = 'http://foo.bar/path' expect(up.params.fromURL(url)).toBeUndefined() describe 'up.params.fromForm', -> it 'serializes a form with multiple inputs', -> $form = affix('form') $form.append('<input name="key1" value="value1">') $form.append('<input name="key2" value="value2">') params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key1', value: 'value1' }, { name: 'key2', value: 'value2' }, ] it 'serializes an <input type="text"> with its default [value]', -> $form = affix('form') $form.append('<input type="text" name="key" value="value-from-attribute">') params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value-from-attribute' } ] it 'serializes an <input type="text"> that had its value property changed by a script', -> $form = affix('form') $input = $('<input type="text" name="key" value="value-from-attribute">').appendTo($form) $input[0].value = 'value-from-script' params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value-from-script' } ] it 'serializes an <input type="hidden"> with its default [value]', -> $form = affix('form') $form.append('<input type="hidden" name="key" value="value-from-attribute">') params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value-from-attribute' } ] it 'serializes an <input type="hidden"> that had its value property changed by a script', -> $form = affix('form') $input = $('<input type="hidden" name="key" value="value-from-attribute">').appendTo($form) $input[0].value = 'value-from-script' params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value-from-script' } ] it 'seralizes a <select> with its default selected option', -> $form = affix('form') $select = $('<select name="key"></select>').appendTo($form) $option1 = $('<option value="value1">').appendTo($select) $option2 = $('<option value="value2" selected>').appendTo($select) $option3 = $('<option value="value3">').appendTo($select) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value2' } ] it 'seralizes a <select> that had its selection changed by a script', -> $form = affix('form') $select = $('<select name="key"></select>').appendTo($form) $option1 = $('<option value="value1">').appendTo($select) $option2 = $('<option value="value2" selected>').appendTo($select) $option3 = $('<option value="value3">').appendTo($select) $option2[0].selected = false $option3[0].selected = true params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value3' } ] it 'serializes a <select multiple> with multiple selected options into multiple params', -> $form = affix('form') $select = $('<select name="key" multiple></select>').appendTo($form) $option1 = $('<option value="value1">').appendTo($select) $option2 = $('<option value="value2" selected>').appendTo($select) $option3 = $('<option value="value3" selected>').appendTo($select) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value2' }, { name: 'key', value: 'value3' } ] it 'serializes an <input type="file">' it 'serializes an <input type="file" multiple> into multiple params' it 'includes an <input type="checkbox"> that was [checked] by default', -> $form = affix('form') $input = $('<input type="checkbox" name="key" value="value" checked>').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value' } ] it 'includes an <input type="checkbox"> that was checked by a script', -> $form = affix('form') $input = $('<input type="checkbox" name="key" value="value">').appendTo($form) $input[0].checked = true params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value' } ] it 'excludes an <input type="checkbox"> that is unchecked', -> $form = affix('form') $input = $('<input type="checkbox" name="key" value="value">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [] it 'includes a checked <input type="radio"> in a radio button group that was [checked] by default', -> $form = affix('form') $button1 = $('<input type="radio" name="key" value="value1">').appendTo($form) $button2 = $('<input type="radio" name="key" value="value2" checked>').appendTo($form) $button3 = $('<input type="radio" name="key" value="value3">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value<KEY>' } ] it 'includes a checked <input type="radio"> in a radio button group that was checked by a script', -> $form = affix('form') $button1 = $('<input type="radio" name="key" value="value1">').appendTo($form) $button2 = $('<input type="radio" name="key" value="value2" checked>').appendTo($form) $button3 = $('<input type="radio" name="key" value="value3">').appendTo($form) $button2[0].checked = false $button3[0].checked = true params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value3' } ] it 'excludes an radio button group if no button is selected', -> $form = affix('form') $button1 = $('<input type="radio" name="key" value="value1">').appendTo($form) $button2 = $('<input type="radio" name="key" value="value2">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [] it 'excludes an <input> that is [disabled] by default', -> $form = affix('form') $input = $('<input type="text" name="key" value="value" disabled>').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [] it 'excludes an <input> that was disabled by a script', -> $form = affix('form') $input = $('<input type="text" name="key" value="value">').appendTo($form) $input[0].disabled = true params = up.params.fromForm($form) expect(params).toEqual [] it 'excludes an <input> without a [name] attribute', -> $form = affix('form') $input = $('<input type="text" value="value">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [] it 'includes an <input readonly>', -> $form = affix('form') $input = $('<input type="text" name="key" value="value" readonly>').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value' } ] it 'includes the focused submit button', -> $form = affix('form') $input = $('<input type="text" name="input-key" value="input-value">').appendTo($form) $submit1 = $('<button type="submit" name="submit1-key" value="submit1-value">').appendTo($form) $submit2 = $('<input type="submit" name="submit2-key" value="submit2-value">').appendTo($form) $submit3 = $('<input type="submit" name="submit3-key" value="submit3-value">').appendTo($form) $submit2.focus() params = up.params.fromForm($form) expect(params).toEqual [ { name: 'input-key', value: 'input-value' }, { name: 'submit2-key', value: 'submit2-value' } ] it 'includes a the first submit button if no button is focused', -> $form = affix('form') $input = $('<input type="text" name="input-key" value="input-value">').appendTo($form) $submit1 = $('<button type="submit" name="submit1-key" value="submit1-value">').appendTo($form) $submit2 = $('<input type="submit" name="submit2-key" value="submit2-value">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'input-key', value: 'input-value' }, { name: 'submit1-key', value: 'submit1-value' } ] it 'excludes a submit button without a [name] attribute', -> $form = affix('form') $input = $('<input type="text" name="input-key" value="input-value">').appendTo($form) $submit = $('<button type="submit" value="submit-value">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'input-key', value: 'input-value' } ]
true
describe 'up.params', -> u = up.util describe 'JavaScript functions', -> encodeBrackets = (str) -> str = str.replace(/\[/g, '%5B') str = str.replace(/\]/g, '%5D') str beforeEach -> jasmine.addMatchers toEqualAfterEncodingBrackets: (util, customEqualityTesters) -> compare: (actual, expected) -> pass: actual == encodeBrackets(expected) describe 'up.params.toQuery', -> # encodedOpeningBracket = '%5B' # encodedClosingBracket = '%5D' encodedSpace = '%20' it 'returns the query section for the given object', -> string = up.params.toQuery('foo-key': 'foo value', 'bar-key': 'bar value') expect(string).toEqual("foo-key=foo#{encodedSpace}value&bar-key=bar#{encodedSpace}value") it 'returns the query section for the given array with { name } and { value } keys', -> string = up.params.toQuery([ { name: 'foo-key', value: 'foo value' }, { name: 'bar-key', value: 'bar value' } ]) expect(string).toEqual("foo-key=foo#{encodedSpace}value&bar-key=bar#{encodedSpace}value") it 'returns a given query string', -> string = up.params.toQuery('foo=bar') expect(string).toEqual('foo=bar') it 'returns an empty string for an empty object', -> string = up.params.toQuery({}) expect(string).toEqual('') it 'returns an empty string for an empty string', -> string = up.params.toQuery('') expect(string).toEqual('') it 'returns an empty string for undefined', -> string = up.params.toQuery(undefined) expect(string).toEqual('') it 'URL-encodes characters in the key and value', -> string = up.params.toQuery({ 'äpfel': 'bäume' }) expect(string).toEqual('%C3%A4pfel=b%C3%A4ume') it "sets a blank value after the equal sign if a key's value is a blank string", -> string = up.params.toQuery({'foo': ''}) expect(string).toEqual('foo=') it 'omits non-primitive values (like Files) from the given params', -> # I would like to construct a File, but IE11 does not support the constructor blob = new Blob([]) string = up.params.toQuery(string: 'foo', blob: blob) expect(string).toEqual('string=foo') it "omits an equal sign if a key's value is null", -> string = up.params.toQuery({'foo': null}) expect(string).toEqual('foo') it 'URL-encodes plus characters', -> string = up.params.toQuery({ 'my+key': 'my+value' }) expect(string).toEqual('my%2Bkey=my%2Bvalue') describeCapability 'canInspectFormData', -> it 'converts a FormData object to a query string', -> fd = new FormData() fd.append('key1', 'valuePI:KEY:<KEY>END_PI') fd.append('key2', 'valuePI:KEY:<KEY>END_PI') string = up.params.toQuery(fd) expect(string).toEqual('key1=value1&key2=value2') describe 'up.params.toArray', -> it 'normalized null to an empty array', -> array = up.params.toArray(null) expect(array).toEqual([]) it 'normalized undefined to an empty array', -> array = up.params.toArray(undefined) expect(array).toEqual([]) it 'normalizes an object hash to an array of objects with { name } and { value } keys', -> array = up.params.toArray( 'foo-key': 'PI:KEY:<KEY>END_PI' 'bar-key': 'PI:KEY:<KEY>END_PI' ) expect(array).toEqual([ { name: 'foo-key', value: 'foo-value' }, { name: 'bar-key', value: 'bar-PI:KEY:<KEY>END_PI' }, ]) it 'returns a given array without modification', -> array = up.params.toArray([ { name: 'foo-key', value: 'foo-value' }, { name: 'bar-key', value: 'bar-value' }, ]) expect(array).toEqual([ { name: 'foo-key', value: 'foo-value' }, { name: 'bar-key', value: 'bar-value' }, ]) it 'does not URL-encode special characters in keys or values', -> array = up.params.toArray( 'äpfel': 'bäume' ) expect(array).toEqual([ { name: 'äPI:NAME:<NAME>END_PIel', value: 'bäume' }, ]) it 'does not URL-encode spaces in keys or values', -> array = up.params.toArray( 'my key': 'my value' ) expect(array).toEqual([ { name: 'my key', value: 'my value' }, ]) it 'does not URL-encode ampersands in keys or values', -> array = up.params.toArray( 'my&key': 'my&value' ) expect(array).toEqual([ { name: 'my&key', value: 'my&value' }, ]) it 'does not URL-encode equal signs in keys or values', -> array = up.params.toArray( 'my=key': 'my=value' ) expect(array).toEqual([ { name: 'my=key', value: 'my=value' }, ]) describeCapability 'canInspectFormData', -> it 'converts a FormData object to an array', -> fd = new FormData() fd.append('key1', 'value1') fd.append('key2', 'value2') array = up.params.toArray(fd) expect(array).toEqual([ { name: 'key1', value: 'value1' }, { name: 'key2', value: 'value2' }, ]) describe 'up.params.toFormData', -> describeCapability 'canInspectFormData', -> it 'converts undefined to an empty FormData object', -> params = undefined formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [] it 'converts null to an empty FormData object', -> params = null formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [] it 'converts an object to a FormData object', -> params = { key1: 'value1', key2: 'PI:KEY:<KEY>END_PI' } formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [ { name: 'key1', value: 'PI:KEY:<KEY>END_PI' }, { name: 'key2', value: 'PI:KEY:<KEY>END_PI' }, ] it 'returns a FormData object unchanged', -> params = new FormData() formData = up.params.toFormData(params) expect(formData).toBe(params) it 'converts a query string to a FormData object', -> params = 'key1=value1&key2=value2' formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [ { name: 'key1', value: 'PI:KEY:<KEY>END_PI' }, { name: 'key2', value: 'PI:KEY:<KEY>END_PI' }, ] it 'unescapes percent-encoded characters from a query string', -> params = 'my%20key=my%20value' formData = up.params.toFormData(params) expect(up.params.toArray(formData)).toEqual [ { name: 'my key', value: 'my value' } ] describe 'up.params.toObject', -> it "parses flat key/value pairs", -> expect(up.params.toObject("xfoo")).toEqual("xfoo": null) expect(up.params.toObject("foo=")).toEqual("foo": "") expect(up.params.toObject("foo=bar")).toEqual("foo": "bar") expect(up.params.toObject("foo=\"bar\"")).toEqual("foo": "\"bar\"") expect(up.params.toObject("foo=bar&foo=quux")).toEqual("foo": "quux") expect(up.params.toObject("foo&foo=")).toEqual("foo": "") expect(up.params.toObject("foo=1&bar=2")).toEqual("foo": "1", "bar": "2") expect(up.params.toObject("&foo=1&&bar=2")).toEqual("foo": "1", "bar": "2") expect(up.params.toObject("foo&bar=")).toEqual("foo": null, "bar": "") expect(up.params.toObject("foo=bar&baz=")).toEqual("foo": "bar", "baz": "") it 'URL-decodes keys and values', -> expect(up.params.toObject("my%20weird%20field=q1%212%22%27w%245%267%2Fz8%29%3F")).toEqual("my weird field": "q1!2\"'w$5&7/z8)?") expect(up.params.toObject("a=b&pid%3D1234=1023")).toEqual("pid=1234": "1023", "a": "b") # expect(-> up.params.toObject("foo%81E=1")).toThrowError() # invalid byte sequence in UTF-8 it 'ignores keys that would overwrite an Object prototype property', -> obj = up.params.toObject("foo=bar&hasOwnProperty=baz") expect(obj['foo']).toEqual('bar') expect(u.isFunction obj['hasOwnProperty']).toBe(true) describe 'up.params.add', -> describe '(with object)', -> it 'adds a single key and value', -> obj = { foo: 'one' } obj = up.params.add(obj, 'bar', 'two') expect(obj).toEqual { foo: 'one', bar: 'two' } describe '(with array)', -> it 'adds a single key and value', -> obj = [{ name: 'foo', value: 'one' }] obj = up.params.add(obj, 'bar', 'two') expect(obj).toEqual [{ name: 'foo', value: 'one' }, { name: 'bar', value: 'two' }] describe '(with query string)', -> it 'adds a new key/value pair to the end of a query', -> query = 'foo=one' query = up.params.add(query, 'bar', 'two') expect(query).toEqual('foo=one&bar=two') it 'does not add superfluous ampersands if the previous query was a blank string', -> query = '' query = up.params.add(query, 'bar', 'two') expect(query).toEqual('bar=two') it 'escapes special characters in the new key and value', -> query = 'foo=one' query = up.params.add(query, 'bär', 'twö') expect(query).toEqual('foo=one&b%C3%A4r=tw%C3%B6') describe '(with FormData)', -> describeCapability 'canInspectFormData', -> it 'adds a single entry', -> formData = new FormData() formData.append('key1', 'value1') up.params.add(formData, 'key2', 'value2') expect(up.params.toArray(formData)).toEqual [ { name: 'key1', value: 'value1' }, { name: 'key2', value: 'value2' }, ] describe '(with missing params)', -> it 'returns an object with only the new key and value', -> obj = undefined obj = up.params.add(obj, 'bar', 'two') expect(obj).toEqual { bar: 'two' } describe 'up.params.get', -> describe '(with object)', -> it 'returns the value for the given name', -> obj = { foo: 'one', bar: 'two' } value = up.params.get(obj, 'bar') expect(value).toEqual('two') it 'returns undefined if no value is set for the given name', -> obj = { foo: 'one' } value = up.params.get(obj, 'bar') expect(value).toBeUndefined() it 'returns undefined for names that are also a basic object property', -> obj = {} value = up.params.get(obj, 'hasOwnProperty') expect(value).toBeUndefined() describe '(with array)', -> it 'returns the value of the first entry with the given name', -> array = [ { name: 'foo', value: 'one' } { name: 'bar', value: 'two' } { name: 'foo', value: 'three' } ] value = up.params.get(array, 'foo') expect(value).toEqual('one') it 'returns undefined if there is no entry with the given name', -> array = [ { name: 'foo', value: 'one' } ] value = up.params.get(array, 'bar') expect(value).toBeUndefined() describe '(with query string)', -> it 'returns the query param with the given name', -> query = 'foo=one&bar=two' value = up.params.get(query, 'bar') expect(value).toEqual('two') it 'returns undefined if there is no query param with the given name', -> query = 'foo=one' query = up.params.get(query, 'bar') expect(query).toBeUndefined() it 'unescapes percent-encoded characters in the returned value', -> query = 'foo=one%20two' value = up.params.get(query, 'foo') expect(value).toEqual('one two') describe '(with FormData)', -> describeCapability 'canInspectFormData', -> it 'returns the first entry with the given name', -> formData = new FormData() formData.append('key1', 'value1') formData.append('key2', 'value2') value = up.params.get(formData, 'key2') expect(value).toEqual('value2') it 'returns undefined if there is no entry with the given name', -> formData = new FormData() value = up.params.get(formData, 'key') expect(value).toBeUndefined() describe '(with missing params)', -> it 'returns undefined', -> params = undefined value = up.params.get(params, 'foo') expect(value).toBeUndefined() describe 'up.params.merge', -> describe '(with object)', -> it 'merges a flat object', -> obj = { a: '1', b: '2' } other = { c: '3', d: '4'} obj = up.params.merge(obj, other) expect(obj).toEqual({ a: '1', b: '2', c: '3', d: '4' }) it 'merges an array', -> obj = { a: '1', b: '2' } other = [ { name: 'c', value: '3' }, { name: 'd', value: '4' } ] obj = up.params.merge(obj, other) expect(obj).toEqual({ a: '1', b: '2', c: '3', d: '4' }) it 'merges a query string', -> obj = { a: '1', b: '2' } other = 'c=3&d=4' obj = up.params.merge(obj, other) expect(obj).toEqual({ a: '1', b: '2', c: '3', d: '4' }) it 'does not change or crash when merged with undefined', -> obj = { a: '1', b: '2' } obj = up.params.merge(obj, undefined) expect(obj).toEqual({ a: '1', b: '2' }) describeCapability 'canInspectFormData', -> it 'merges a FormData object', -> obj = { a: '1', b: '2' } formData = new FormData() formData.append('c', '3') formData.append('d', '4') merged = up.params.merge(obj, formData) expect(merged).toEqual({ a: '1', b: '2', c: '3', d: '4' }) describe '(with array)', -> it 'merges a flat object', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] other = { c: '3', d: '4'} array = up.params.merge(array, other) expect(array).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' }, { name: 'c', value: '3' }, { name: 'd', value: '4' } ] it 'merges another array', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] other = [ { name: 'c', value: '3' }, { name: 'd', value: '4' } ] array = up.params.merge(array, other) expect(array).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' }, { name: 'c', value: '3' }, { name: 'd', value: '4' } ] it 'merges a query string', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] other = 'c=3&d=4' array = up.params.merge(array, other) expect(array).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' }, { name: 'c', value: '3' }, { name: 'd', value: '4' } ] it 'does not change or crash when merged with undefined', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] array = up.params.merge(array, undefined) expect(array).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] describeCapability 'canInspectFormData', -> it 'merges a FormData object', -> array = [ { name: 'a', value: '1' }, { name: 'b', value: '2' } ] formData = new FormData() formData.append('c', '3') formData.append('d', '4') merged = up.params.merge(array, formData) expect(merged).toEqual [ { name: 'a', value: '1' }, { name: 'b', value: '2' }, { name: 'c', value: '3' }, { name: 'd', value: '4' } ] describe '(with query)', -> it 'merges a flat object', -> query = 'a=1&b=2' other = { c: '3', d: '4'} query = up.params.merge(query, other) expect(query).toEqual('a=1&b=2&c=3&d=4') it 'merges an array', -> query = 'a=1&b=2' other = [ { name: 'c', value: '3' }, { name: 'd', value: '4' } ] query = up.params.merge(query, other) expect(query).toEqual('a=1&b=2&c=3&d=4') it 'merges another query string', -> query = 'a=1&b=2' other = 'c=3&d=4' query = up.params.merge(query, other) expect(query).toEqual('a=1&b=2&c=3&d=4') it 'does not change or crash when merged with undefined', -> query = 'a=1&b=2' query = up.params.merge(query, undefined) expect(query).toEqual('a=1&b=2') describeCapability 'canInspectFormData', -> it 'merges a FormData object', -> query = 'a=1&b=2' formData = new FormData() formData.append('c', '3') formData.append('d', '4') merged = up.params.merge(query, formData) expect(merged).toEqual('a=1&b=2&c=3&d=4') describe 'up.params.buildURL', -> it 'composes a URL from a base URL (without query section) and a query section', -> base = 'http://foo.bar/path' query = 'key=value' expect(up.params.buildURL(base, query)).toEqual('http://foo.bar/path?key=value') it 'accepts other forms of params (instead of query sections)', -> base = 'http://foo.bar/path' params = { key: 'value' } expect(up.params.buildURL(base, params)).toEqual('http://foo.bar/path?key=value') it 'adds more params to a base URL that already has a query section', -> base = 'http://foo.bar/path?key1=value1' params = { key2: 'value2' } expect(up.params.buildURL(base, params)).toEqual('http://foo.bar/path?key1=value1&key2=value2') it 'does not add a question mark to the base URL if the given params are blank', -> base = 'http://foo.bar/path' params = '' expect(up.params.buildURL(base, params)).toEqual('http://foo.bar/path') describe 'up.params.fromURL', -> it 'returns the query section from an URL, without leading question mark', -> url = 'http://foo.bar/path?key=value' expect(up.params.fromURL(url)).toEqual('key=value') it 'returns undefined if the URL has no query section', -> url = 'http://foo.bar/path' expect(up.params.fromURL(url)).toBeUndefined() describe 'up.params.fromForm', -> it 'serializes a form with multiple inputs', -> $form = affix('form') $form.append('<input name="key1" value="value1">') $form.append('<input name="key2" value="value2">') params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key1', value: 'value1' }, { name: 'key2', value: 'value2' }, ] it 'serializes an <input type="text"> with its default [value]', -> $form = affix('form') $form.append('<input type="text" name="key" value="value-from-attribute">') params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value-from-attribute' } ] it 'serializes an <input type="text"> that had its value property changed by a script', -> $form = affix('form') $input = $('<input type="text" name="key" value="value-from-attribute">').appendTo($form) $input[0].value = 'value-from-script' params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value-from-script' } ] it 'serializes an <input type="hidden"> with its default [value]', -> $form = affix('form') $form.append('<input type="hidden" name="key" value="value-from-attribute">') params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value-from-attribute' } ] it 'serializes an <input type="hidden"> that had its value property changed by a script', -> $form = affix('form') $input = $('<input type="hidden" name="key" value="value-from-attribute">').appendTo($form) $input[0].value = 'value-from-script' params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value-from-script' } ] it 'seralizes a <select> with its default selected option', -> $form = affix('form') $select = $('<select name="key"></select>').appendTo($form) $option1 = $('<option value="value1">').appendTo($select) $option2 = $('<option value="value2" selected>').appendTo($select) $option3 = $('<option value="value3">').appendTo($select) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value2' } ] it 'seralizes a <select> that had its selection changed by a script', -> $form = affix('form') $select = $('<select name="key"></select>').appendTo($form) $option1 = $('<option value="value1">').appendTo($select) $option2 = $('<option value="value2" selected>').appendTo($select) $option3 = $('<option value="value3">').appendTo($select) $option2[0].selected = false $option3[0].selected = true params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value3' } ] it 'serializes a <select multiple> with multiple selected options into multiple params', -> $form = affix('form') $select = $('<select name="key" multiple></select>').appendTo($form) $option1 = $('<option value="value1">').appendTo($select) $option2 = $('<option value="value2" selected>').appendTo($select) $option3 = $('<option value="value3" selected>').appendTo($select) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value2' }, { name: 'key', value: 'value3' } ] it 'serializes an <input type="file">' it 'serializes an <input type="file" multiple> into multiple params' it 'includes an <input type="checkbox"> that was [checked] by default', -> $form = affix('form') $input = $('<input type="checkbox" name="key" value="value" checked>').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value' } ] it 'includes an <input type="checkbox"> that was checked by a script', -> $form = affix('form') $input = $('<input type="checkbox" name="key" value="value">').appendTo($form) $input[0].checked = true params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value' } ] it 'excludes an <input type="checkbox"> that is unchecked', -> $form = affix('form') $input = $('<input type="checkbox" name="key" value="value">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [] it 'includes a checked <input type="radio"> in a radio button group that was [checked] by default', -> $form = affix('form') $button1 = $('<input type="radio" name="key" value="value1">').appendTo($form) $button2 = $('<input type="radio" name="key" value="value2" checked>').appendTo($form) $button3 = $('<input type="radio" name="key" value="value3">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'valuePI:KEY:<KEY>END_PI' } ] it 'includes a checked <input type="radio"> in a radio button group that was checked by a script', -> $form = affix('form') $button1 = $('<input type="radio" name="key" value="value1">').appendTo($form) $button2 = $('<input type="radio" name="key" value="value2" checked>').appendTo($form) $button3 = $('<input type="radio" name="key" value="value3">').appendTo($form) $button2[0].checked = false $button3[0].checked = true params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value3' } ] it 'excludes an radio button group if no button is selected', -> $form = affix('form') $button1 = $('<input type="radio" name="key" value="value1">').appendTo($form) $button2 = $('<input type="radio" name="key" value="value2">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [] it 'excludes an <input> that is [disabled] by default', -> $form = affix('form') $input = $('<input type="text" name="key" value="value" disabled>').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [] it 'excludes an <input> that was disabled by a script', -> $form = affix('form') $input = $('<input type="text" name="key" value="value">').appendTo($form) $input[0].disabled = true params = up.params.fromForm($form) expect(params).toEqual [] it 'excludes an <input> without a [name] attribute', -> $form = affix('form') $input = $('<input type="text" value="value">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [] it 'includes an <input readonly>', -> $form = affix('form') $input = $('<input type="text" name="key" value="value" readonly>').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'key', value: 'value' } ] it 'includes the focused submit button', -> $form = affix('form') $input = $('<input type="text" name="input-key" value="input-value">').appendTo($form) $submit1 = $('<button type="submit" name="submit1-key" value="submit1-value">').appendTo($form) $submit2 = $('<input type="submit" name="submit2-key" value="submit2-value">').appendTo($form) $submit3 = $('<input type="submit" name="submit3-key" value="submit3-value">').appendTo($form) $submit2.focus() params = up.params.fromForm($form) expect(params).toEqual [ { name: 'input-key', value: 'input-value' }, { name: 'submit2-key', value: 'submit2-value' } ] it 'includes a the first submit button if no button is focused', -> $form = affix('form') $input = $('<input type="text" name="input-key" value="input-value">').appendTo($form) $submit1 = $('<button type="submit" name="submit1-key" value="submit1-value">').appendTo($form) $submit2 = $('<input type="submit" name="submit2-key" value="submit2-value">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'input-key', value: 'input-value' }, { name: 'submit1-key', value: 'submit1-value' } ] it 'excludes a submit button without a [name] attribute', -> $form = affix('form') $input = $('<input type="text" name="input-key" value="input-value">').appendTo($form) $submit = $('<button type="submit" value="submit-value">').appendTo($form) params = up.params.fromForm($form) expect(params).toEqual [ { name: 'input-key', value: 'input-value' } ]
[ { "context": "###\nTranslation of gist https://gist.github.com/nimasdj/801b0b1a50112ea6a997\nTotal: 1223 extensions as of", "end": 55, "score": 0.9994850754737854, "start": 48, "tag": "USERNAME", "value": "nimasdj" }, { "context": "']\n 'ttl' : ['text/turtle']\n 'turbot' : ['image/florian']\n 'twd' : ['application/vnd.simtech-mindmapper'", "end": 41035, "score": 0.9004080891609192, "start": 41028, "tag": "NAME", "value": "florian" } ]
src/kermit/util/mimetypes.coffee
open-medicine-initiative/webcherries
6
### Translation of gist https://gist.github.com/nimasdj/801b0b1a50112ea6a997 Total: 1223 extensions as of 16 November 2015 ### byFileExtension = '3dm' : ['x-world/x-3dmf'] '3dmf' : ['x-world/x-3dmf'] '3dml' : ['text/vnd.in3d.3dml'] '3ds' : ['image/x-3ds'] '3g2' : ['video/3gpp2'] '3gp' : ['video/3gpp'] '7z' : ['application/x-7z-compressed'] 'a' : ['application/octet-stream'] 'aab' : ['application/x-authorware-bin'] 'aac' : ['audio/x-aac'] 'aam' : ['application/x-authorware-map'] 'aas' : ['application/x-authorware-seg'] 'abc' : ['text/vnd.abc'] 'abw' : ['application/x-abiword'] 'ac' : ['application/pkix-attr-cert'] 'acc' : ['application/vnd.americandynamics.acc'] 'ace' : ['application/x-ace-compressed'] 'acgi' : ['text/html'] 'acu' : ['application/vnd.acucobol'] 'acutc' : ['application/vnd.acucorp'] 'adp' : ['audio/adpcm'] 'aep' : ['application/vnd.audiograph'] 'afl' : ['video/animaflex'] 'afm' : ['application/x-font-type1'] 'afp' : ['application/vnd.ibm.modcap'] 'ahead' : ['application/vnd.ahead.space'] 'ai' : ['application/postscript'] 'aif' : ['audio/aiff', 'audio/x-aiff'] 'aifc' : ['audio/aiff', 'audio/x-aiff'] 'aiff' : ['audio/aiff', 'audio/x-aiff'] 'aim' : ['application/x-aim'] 'aip' : ['text/x-audiosoft-intra'] 'air' : ['application/vnd.adobe.air-application-installer-package+zip'] 'ait' : ['application/vnd.dvb.ait'] 'ami' : ['application/vnd.amiga.ami'] 'ani' : ['application/x-navi-animation'] 'aos' : ['application/x-nokia-9000-communicator-add-on-software'] 'apk' : ['application/vnd.android.package-archive'] 'appcache' : ['text/cache-manifest'] 'application' : ['application/x-ms-application'] 'apr' : ['application/vnd.lotus-approach'] 'aps' : ['application/mime'] 'arc' : ['application/x-freearc'] 'arj' : ['application/arj', 'application/octet-stream'] 'art' : ['image/x-jg'] 'asc' : ['application/pgp-signature'] 'asf' : ['video/x-ms-asf'] 'asm' : ['text/x-asm'] 'aso' : ['application/vnd.accpac.simply.aso'] 'asp' : ['text/asp'] 'asx' : ['application/x-mplayer2', 'video/x-ms-asf', 'video/x-ms-asf-plugin'] 'atc' : ['application/vnd.acucorp'] 'atom' : ['application/atom+xml'] 'atomcat' : ['application/atomcat+xml'] 'atomsvc' : ['application/atomsvc+xml'] 'atx' : ['application/vnd.antix.game-component'] 'au' : ['audio/basic'] 'avi' : ['application/x-troff-msvideo', 'video/avi', 'video/msvideo', 'video/x-msvideo'] 'avs' : ['video/avs-video'] 'aw' : ['application/applixware'] 'azf' : ['application/vnd.airzip.filesecure.azf'] 'azs' : ['application/vnd.airzip.filesecure.azs'] 'azw' : ['application/vnd.amazon.ebook'] 'bat' : ['application/x-msdownload'] 'bcpio' : ['application/x-bcpio'] 'bdf' : ['application/x-font-bdf'] 'bdm' : ['application/vnd.syncml.dm+wbxml'] 'bed' : ['application/vnd.realvnc.bed'] 'bh2' : ['application/vnd.fujitsu.oasysprs'] 'bin' : ['application/mac-binary', 'application/macbinary', 'application/octet-stream', 'application/x-binary', 'application/x-macbinary'] 'blb' : ['application/x-blorb'] 'blorb' : ['application/x-blorb'] 'bm' : ['image/bmp'] 'bmi' : ['application/vnd.bmi'] 'bmp' : ['image/bmp', 'image/x-windows-bmp'] 'boo' : ['application/book'] 'book' : ['application/vnd.framemaker'] 'box' : ['application/vnd.previewsystems.box'] 'boz' : ['application/x-bzip2'] 'bpk' : ['application/octet-stream'] 'bsh' : ['application/x-bsh'] 'btif' : ['image/prs.btif'] 'buffer' : ['application/octet-stream'] 'bz' : ['application/x-bzip'] 'bz2' : ['application/x-bzip2'] 'c' : ['text/x-c'] 'c++' : ['text/plain'] 'c11amc' : ['application/vnd.cluetrust.cartomobile-config'] 'c11amz' : ['application/vnd.cluetrust.cartomobile-config-pkg'] 'c4d' : ['application/vnd.clonk.c4group'] 'c4f' : ['application/vnd.clonk.c4group'] 'c4g' : ['application/vnd.clonk.c4group'] 'c4p' : ['application/vnd.clonk.c4group'] 'c4u' : ['application/vnd.clonk.c4group'] 'cab' : ['application/vnd.ms-cab-compressed'] 'caf' : ['audio/x-caf'] 'cap' : ['application/vnd.tcpdump.pcap'] 'car' : ['application/vnd.curl.car'] 'cat' : ['application/vnd.ms-pki.seccat'] 'cb7' : ['application/x-cbr'] 'cba' : ['application/x-cbr'] 'cbr' : ['application/x-cbr'] 'cbt' : ['application/x-cbr'] 'cbz' : ['application/x-cbr'] 'cc' : ['text/plain', 'text/x-c'] 'ccad' : ['application/clariscad'] 'cco' : ['application/x-cocoa'] 'cct' : ['application/x-director'] 'ccxml' : ['application/ccxml+xml'] 'cdbcmsg' : ['application/vnd.contact.cmsg'] 'cdf' : ['application/cdf', 'application/x-cdf', 'application/x-netcdf'] 'cdkey' : ['application/vnd.mediastation.cdkey'] 'cdmia' : ['application/cdmi-capability'] 'cdmic' : ['application/cdmi-container'] 'cdmid' : ['application/cdmi-domain'] 'cdmio' : ['application/cdmi-object'] 'cdmiq' : ['application/cdmi-queue'] 'cdx' : ['chemical/x-cdx'] 'cdxml' : ['application/vnd.chemdraw+xml'] 'cdy' : ['application/vnd.cinderella'] 'cer' : ['application/pkix-cert', 'application/x-x509-ca-cert'] 'cfs' : ['application/x-cfs-compressed'] 'cgm' : ['image/cgm'] 'cha' : ['application/x-chat'] 'chat' : ['application/x-chat'] 'chm' : ['application/vnd.ms-htmlhelp'] 'chrt' : ['application/vnd.kde.kchart'] 'cif' : ['chemical/x-cif'] 'cii' : ['application/vnd.anser-web-certificate-issue-initiation'] 'cil' : ['application/vnd.ms-artgalry'] 'cla' : ['application/vnd.claymore'] 'class' : ['application/java', 'application/java-byte-code', 'application/x-java-class'] 'clkk' : ['application/vnd.crick.clicker.keyboard'] 'clkp' : ['application/vnd.crick.clicker.palette'] 'clkt' : ['application/vnd.crick.clicker.template'] 'clkw' : ['application/vnd.crick.clicker.wordbank'] 'clkx' : ['application/vnd.crick.clicker'] 'clp' : ['application/x-msclip'] 'cmc' : ['application/vnd.cosmocaller'] 'cmdf' : ['chemical/x-cmdf'] 'cml' : ['chemical/x-cml'] 'cmp' : ['application/vnd.yellowriver-custom-menu'] 'cmx' : ['image/x-cmx'] 'cod' : ['application/vnd.rim.cod'] 'com' : ['application/octet-stream', 'text/plain'] 'conf' : ['text/plain'] 'cpio' : ['application/x-cpio'] 'cpp' : ['text/x-c'] 'cpt' : ['application/x-compactpro', 'application/x-cpt'] 'crd' : ['application/x-mscardfile'] 'crl' : ['application/pkcs-crl', 'application/pkix-crl'] 'crt' : ['application/pkix-cert', 'application/x-x509-ca-cert', 'application/x-x509-user-cert'] 'crx' : ['application/x-chrome-extension'] 'cryptonote' : ['application/vnd.rig.cryptonote'] 'csh' : ['application/x-csh', 'text/x-script.csh'] 'csml' : ['chemical/x-csml'] 'csp' : ['application/vnd.commonspace'] 'css' : ['application/x-pointplus', 'text/css'] 'cst' : ['application/x-director'] 'csv' : ['text/csv'] 'cu' : ['application/cu-seeme'] 'curl' : ['text/vnd.curl'] 'cww' : ['application/prs.cww'] 'cxt' : ['application/x-director'] 'cxx' : ['text/x-c'] 'dae' : ['model/vnd.collada+xml'] 'daf' : ['application/vnd.mobius.daf'] 'dart' : ['application/vnd.dart'] 'dataless' : ['application/vnd.fdsn.seed'] 'davmount' : ['application/davmount+xml'] 'dbk' : ['application/docbook+xml'] 'dcr' : ['application/x-director'] 'dcurl' : ['text/vnd.curl.dcurl'] 'dd2' : ['application/vnd.oma.dd2+xml'] 'ddd' : ['application/vnd.fujixerox.ddd'] 'deb' : ['application/x-debian-package'] 'deepv' : ['application/x-deepv'] 'def' : ['text/plain'] 'deploy' : ['application/octet-stream'] 'der' : ['application/x-x509-ca-cert'] 'dfac' : ['application/vnd.dreamfactory'] 'dgc' : ['application/x-dgc-compressed'] 'dic' : ['text/x-c'] 'dif' : ['video/x-dv'] 'diff' : ['text/plain'] 'dir' : ['application/x-director'] 'dis' : ['application/vnd.mobius.dis'] 'dist' : ['application/octet-stream'] 'distz' : ['application/octet-stream'] 'djv' : ['image/vnd.djvu'] 'djvu' : ['image/vnd.djvu'] 'dl' : ['video/dl', 'video/x-dl'] 'dll' : ['application/x-msdownload'] 'dmg' : ['application/x-apple-diskimage'] 'dmp' : ['application/vnd.tcpdump.pcap'] 'dms' : ['application/octet-stream'] 'dna' : ['application/vnd.dna'] 'doc' : ['application/msword'] 'docm' : ['application/vnd.ms-word.document.macroenabled.12'] 'docx' : ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'] 'dot' : ['application/msword'] 'dotm' : ['application/vnd.ms-word.template.macroenabled.12'] 'dotx' : ['application/vnd.openxmlformats-officedocument.wordprocessingml.template'] 'dp' : ['application/vnd.osgi.dp'] 'dpg' : ['application/vnd.dpgraph'] 'dra' : ['audio/vnd.dra'] 'drw' : ['application/drafting'] 'dsc' : ['text/prs.lines.tag'] 'dssc' : ['application/dssc+der'] 'dtb' : ['application/x-dtbook+xml'] 'dtd' : ['application/xml-dtd'] 'dts' : ['audio/vnd.dts'] 'dtshd' : ['audio/vnd.dts.hd'] 'dump' : ['application/octet-stream'] 'dv' : ['video/x-dv'] 'dvb' : ['video/vnd.dvb.file'] 'dvi' : ['application/x-dvi'] 'dwf' : ['drawing/x-dwf (old)', 'model/vnd.dwf'] 'dwg' : ['application/acad', 'image/vnd.dwg', 'image/x-dwg'] 'dxf' : ['image/vnd.dxf'] 'dxp' : ['application/vnd.spotfire.dxp'] 'dxr' : ['application/x-director'] 'ecelp4800' : ['audio/vnd.nuera.ecelp4800'] 'ecelp7470' : ['audio/vnd.nuera.ecelp7470'] 'ecelp9600' : ['audio/vnd.nuera.ecelp9600'] 'ecma' : ['application/ecmascript'] 'edm' : ['application/vnd.novadigm.edm'] 'edx' : ['application/vnd.novadigm.edx'] 'efif' : ['application/vnd.picsel'] 'ei6' : ['application/vnd.pg.osasli'] 'el' : ['text/x-script.elisp'] 'elc' : ['application/x-bytecode.elisp (compiled elisp)', 'application/x-elc'] 'emf' : ['application/x-msmetafile'] 'eml' : ['message/rfc822'] 'emma' : ['application/emma+xml'] 'emz' : ['application/x-msmetafile'] 'env' : ['application/x-envoy'] 'eol' : ['audio/vnd.digital-winds'] 'eot' : ['application/vnd.ms-fontobject'] 'eps' : ['application/postscript'] 'epub' : ['application/epub+zip'] 'es' : ['application/x-esrehber'] 'es3' : ['application/vnd.eszigno3+xml'] 'esa' : ['application/vnd.osgi.subsystem'] 'esf' : ['application/vnd.epson.esf'] 'et3' : ['application/vnd.eszigno3+xml'] 'etx' : ['text/x-setext'] 'eva' : ['application/x-eva'] 'event-stream' : ['text/event-stream'] 'evy' : ['application/envoy', 'application/x-envoy'] 'exe' : ['application/x-msdownload'] 'exi' : ['application/exi'] 'ext' : ['application/vnd.novadigm.ext'] 'ez' : ['application/andrew-inset'] 'ez2' : ['application/vnd.ezpix-album'] 'ez3' : ['application/vnd.ezpix-package'] 'f' : ['text/plain', 'text/x-fortran'] 'f4v' : ['video/x-f4v'] 'f77' : ['text/x-fortran'] 'f90' : ['text/plain', 'text/x-fortran'] 'fbs' : ['image/vnd.fastbidsheet'] 'fcdt' : ['application/vnd.adobe.formscentral.fcdt'] 'fcs' : ['application/vnd.isac.fcs'] 'fdf' : ['application/vnd.fdf'] 'fe_launch' : ['application/vnd.denovo.fcselayout-link'] 'fg5' : ['application/vnd.fujitsu.oasysgp'] 'fgd' : ['application/x-director'] 'fh' : ['image/x-freehand'] 'fh4' : ['image/x-freehand'] 'fh5' : ['image/x-freehand'] 'fh7' : ['image/x-freehand'] 'fhc' : ['image/x-freehand'] 'fif' : ['application/fractals', 'image/fif'] 'fig' : ['application/x-xfig'] 'flac' : ['audio/flac'] 'fli' : ['video/fli', 'video/x-fli'] 'flo' : ['application/vnd.micrografx.flo'] 'flv' : ['video/x-flv'] 'flw' : ['application/vnd.kde.kivio'] 'flx' : ['text/vnd.fmi.flexstor'] 'fly' : ['text/vnd.fly'] 'fm' : ['application/vnd.framemaker'] 'fmf' : ['video/x-atomic3d-feature'] 'fnc' : ['application/vnd.frogans.fnc'] 'for' : ['text/plain', 'text/x-fortran'] 'fpx' : ['image/vnd.fpx', 'image/vnd.net-fpx'] 'frame' : ['application/vnd.framemaker'] 'frl' : ['application/freeloader'] 'fsc' : ['application/vnd.fsc.weblaunch'] 'fst' : ['image/vnd.fst'] 'ftc' : ['application/vnd.fluxtime.clip'] 'fti' : ['application/vnd.anser-web-funds-transfer-initiation'] 'funk' : ['audio/make'] 'fvt' : ['video/vnd.fvt'] 'fxp' : ['application/vnd.adobe.fxp'] 'fxpl' : ['application/vnd.adobe.fxp'] 'fzs' : ['application/vnd.fuzzysheet'] 'g' : ['text/plain'] 'g2w' : ['application/vnd.geoplan'] 'g3' : ['image/g3fax'] 'g3w' : ['application/vnd.geospace'] 'gac' : ['application/vnd.groove-account'] 'gam' : ['application/x-tads'] 'gbr' : ['application/rpki-ghostbusters'] 'gca' : ['application/x-gca-compressed'] 'gdl' : ['model/vnd.gdl'] 'geo' : ['application/vnd.dynageo'] 'gex' : ['application/vnd.geometry-explorer'] 'ggb' : ['application/vnd.geogebra.file'] 'ggt' : ['application/vnd.geogebra.tool'] 'ghf' : ['application/vnd.groove-help'] 'gif' : ['image/gif'] 'gim' : ['application/vnd.groove-identity-message'] 'gl' : ['video/gl', 'video/x-gl'] 'gml' : ['application/gml+xml'] 'gmx' : ['application/vnd.gmx'] 'gnumeric' : ['application/x-gnumeric'] 'gph' : ['application/vnd.flographit'] 'gpx' : ['application/gpx+xml'] 'gqf' : ['application/vnd.grafeq'] 'gqs' : ['application/vnd.grafeq'] 'gram' : ['application/srgs'] 'gramps' : ['application/x-gramps-xml'] 'gre' : ['application/vnd.geometry-explorer'] 'grv' : ['application/vnd.groove-injector'] 'grxml' : ['application/srgs+xml'] 'gsd' : ['audio/x-gsm'] 'gsf' : ['application/x-font-ghostscript'] 'gsm' : ['audio/x-gsm'] 'gsp' : ['application/x-gsp'] 'gss' : ['application/x-gss'] 'gtar' : ['application/x-gtar'] 'gtm' : ['application/vnd.groove-tool-message'] 'gtw' : ['model/vnd.gtw'] 'gv' : ['text/vnd.graphviz'] 'gxf' : ['application/gxf'] 'gxt' : ['application/vnd.geonext'] 'gz' : ['application/x-compressed', 'application/x-gzip'] 'gzip' : ['application/x-gzip', 'multipart/x-gzip'] 'h' : ['text/plain', 'text/x-h'] 'h261' : ['video/h261'] 'h263' : ['video/h263'] 'h264' : ['video/h264'] 'hal' : ['application/vnd.hal+xml'] 'hbci' : ['application/vnd.hbci'] 'hdf' : ['application/x-hdf'] 'help' : ['application/x-helpfile'] 'hgl' : ['application/vnd.hp-hpgl'] 'hh' : ['text/plain', 'text/x-h'] 'hlb' : ['text/x-script'] 'hlp' : ['application/hlp', 'application/x-helpfile', 'application/x-winhelp'] 'hpg' : ['application/vnd.hp-hpgl'] 'hpgl' : ['application/vnd.hp-hpgl'] 'hpid' : ['application/vnd.hp-hpid'] 'hps' : ['application/vnd.hp-hps'] 'hqx' : ['application/binhex', 'application/binhex4', 'application/mac-binhex', 'application/mac-binhex40', 'application/x-binhex40', 'application/x-mac-binhex40'] 'hta' : ['application/hta'] 'htc' : ['text/x-component'] 'htke' : ['application/vnd.kenameaapp'] 'htm' : ['text/html'] 'html' : ['text/html'] 'htmls' : ['text/html'] 'htt' : ['text/webviewhtml'] 'htx' : ['text/html'] 'hvd' : ['application/vnd.yamaha.hv-dic'] 'hvp' : ['application/vnd.yamaha.hv-voice'] 'hvs' : ['application/vnd.yamaha.hv-script'] 'i2g' : ['application/vnd.intergeo'] 'icc' : ['application/vnd.iccprofile'] 'ice' : ['x-conference/x-cooltalk'] 'icm' : ['application/vnd.iccprofile'] 'ico' : ['image/x-icon'] 'ics' : ['text/calendar'] 'idc' : ['text/plain'] 'ief' : ['image/ief'] 'iefs' : ['image/ief'] 'ifb' : ['text/calendar'] 'ifm' : ['application/vnd.shana.informed.formdata'] 'iges' : ['application/iges', 'model/iges'] 'igl' : ['application/vnd.igloader'] 'igm' : ['application/vnd.insors.igm'] 'igs' : ['application/iges', 'model/iges'] 'igx' : ['application/vnd.micrografx.igx'] 'iif' : ['application/vnd.shana.informed.interchange'] 'ima' : ['application/x-ima'] 'imap' : ['application/x-httpd-imap'] 'imp' : ['application/vnd.accpac.simply.imp'] 'ims' : ['application/vnd.ms-ims'] 'in' : ['text/plain'] 'inf' : ['application/inf'] 'ink' : ['application/inkml+xml'] 'inkml' : ['application/inkml+xml'] 'ins' : ['application/x-internett-signup'] 'install' : ['application/x-install-instructions'] 'iota' : ['application/vnd.astraea-software.iota'] 'ip' : ['application/x-ip2'] 'ipfix' : ['application/ipfix'] 'ipk' : ['application/vnd.shana.informed.package'] 'irm' : ['application/vnd.ibm.rights-management'] 'irp' : ['application/vnd.irepository.package+xml'] 'iso' : ['application/x-iso9660-image'] 'isu' : ['video/x-isvideo'] 'it' : ['audio/it'] 'itp' : ['application/vnd.shana.informed.formtemplate'] 'iv' : ['application/x-inventor'] 'ivp' : ['application/vnd.immervision-ivp'] 'ivr' : ['i-world/i-vrml'] 'ivu' : ['application/vnd.immervision-ivu'] 'ivy' : ['application/x-livescreen'] 'jad' : ['text/vnd.sun.j2me.app-descriptor'] 'jam' : ['application/vnd.jam'] 'jar' : ['application/java-archive'] 'jav' : ['text/plain', 'text/x-java-source'] 'java' : ['text/plain', 'text/x-java-source'] 'jcm' : ['application/x-java-commerce'] 'jfif' : ['image/jpeg', 'image/pjpeg'] 'jfif-tbnl' : ['image/jpeg'] 'jisp' : ['application/vnd.jisp'] 'jlt' : ['application/vnd.hp-jlyt'] 'jnlp' : ['application/x-java-jnlp-file'] 'joda' : ['application/vnd.joost.joda-archive'] 'jpe' : ['image/jpeg', 'image/pjpeg'] 'jpeg' : ['image/jpeg', 'image/pjpeg'] 'jpg' : ['image/jpeg', 'image/pjpeg'] 'jpgm' : ['video/jpm'] 'jpgv' : ['video/jpeg'] 'jpm' : ['video/jpm'] 'jps' : ['image/x-jps'] 'js' : ['application/javascript'] 'json' : ['application/json', 'text/plain'] 'jsonml' : ['application/jsonml+json'] 'jut' : ['image/jutvision'] 'kar' : ['audio/midi', 'music/x-karaoke'] 'karbon' : ['application/vnd.kde.karbon'] 'kfo' : ['application/vnd.kde.kformula'] 'kia' : ['application/vnd.kidspiration'] 'kil' : ['application/x-killustrator'] 'kml' : ['application/vnd.google-earth.kml+xml'] 'kmz' : ['application/vnd.google-earth.kmz'] 'kne' : ['application/vnd.kinar'] 'knp' : ['application/vnd.kinar'] 'kon' : ['application/vnd.kde.kontour'] 'kpr' : ['application/vnd.kde.kpresenter'] 'kpt' : ['application/vnd.kde.kpresenter'] 'kpxx' : ['application/vnd.ds-keypoint'] 'ksh' : ['application/x-ksh', 'text/x-script.ksh'] 'ksp' : ['application/vnd.kde.kspread'] 'ktr' : ['application/vnd.kahootz'] 'ktx' : ['image/ktx'] 'ktz' : ['application/vnd.kahootz'] 'kwd' : ['application/vnd.kde.kword'] 'kwt' : ['application/vnd.kde.kword'] 'la' : ['audio/nspaudio', 'audio/x-nspaudio'] 'lam' : ['audio/x-liveaudio'] 'lasxml' : ['application/vnd.las.las+xml'] 'latex' : ['application/x-latex'] 'lbd' : ['application/vnd.llamagraphics.life-balance.desktop'] 'lbe' : ['application/vnd.llamagraphics.life-balance.exchange+xml'] 'les' : ['application/vnd.hhe.lesson-player'] 'lha' : ['application/lha', 'application/octet-stream', 'application/x-lha'] 'lhx' : ['application/octet-stream'] 'link66' : ['application/vnd.route66.link66+xml'] 'list' : ['text/plain'] 'list3820' : ['application/vnd.ibm.modcap'] 'listafp' : ['application/vnd.ibm.modcap'] 'lma' : ['audio/nspaudio', 'audio/x-nspaudio'] 'lnk' : ['application/x-ms-shortcut'] 'log' : ['text/plain'] 'lostxml' : ['application/lost+xml'] 'lrf' : ['application/octet-stream'] 'lrm' : ['application/vnd.ms-lrm'] 'lsp' : ['application/x-lisp', 'text/x-script.lisp'] 'lst' : ['text/plain'] 'lsx' : ['text/x-la-asf'] 'ltf' : ['application/vnd.frogans.ltf'] 'ltx' : ['application/x-latex'] 'lua' : ['text/x-lua'] 'luac' : ['application/x-lua-bytecode'] 'lvp' : ['audio/vnd.lucent.voice'] 'lwp' : ['application/vnd.lotus-wordpro'] 'lzh' : ['application/octet-stream', 'application/x-lzh'] 'lzx' : ['application/lzx', 'application/octet-stream', 'application/x-lzx'] 'm' : ['text/plain', 'text/x-m'] 'm13' : ['application/x-msmediaview'] 'm14' : ['application/x-msmediaview'] 'm1v' : ['video/mpeg'] 'm21' : ['application/mp21'] 'm2a' : ['audio/mpeg'] 'm2v' : ['video/mpeg'] 'm3a' : ['audio/mpeg'] 'm3u' : ['audio/x-mpegurl'] 'm3u8' : ['application/x-mpegURL'] 'm4a' : ['audio/mp4'] 'm4p' : ['application/mp4'] 'm4u' : ['video/vnd.mpegurl'] 'm4v' : ['video/x-m4v'] 'ma' : ['application/mathematica'] 'mads' : ['application/mads+xml'] 'mag' : ['application/vnd.ecowin.chart'] 'maker' : ['application/vnd.framemaker'] 'man' : ['text/troff'] 'manifest' : ['text/cache-manifest'] 'map' : ['application/x-navimap'] 'mar' : ['application/octet-stream'] 'markdown' : ['text/x-markdown'] 'mathml' : ['application/mathml+xml'] 'mb' : ['application/mathematica'] 'mbd' : ['application/mbedlet'] 'mbk' : ['application/vnd.mobius.mbk'] 'mbox' : ['application/mbox'] 'mc' : ['application/x-magic-cap-package-1.0'] 'mc1' : ['application/vnd.medcalcdata'] 'mcd' : ['application/mcad', 'application/x-mathcad'] 'mcf' : ['image/vasa', 'text/mcf'] 'mcp' : ['application/netmc'] 'mcurl' : ['text/vnd.curl.mcurl'] 'md' : ['text/x-markdown'] 'mdb' : ['application/x-msaccess'] 'mdi' : ['image/vnd.ms-modi'] 'me' : ['text/troff'] 'mesh' : ['model/mesh'] 'meta4' : ['application/metalink4+xml'] 'metalink' : ['application/metalink+xml'] 'mets' : ['application/mets+xml'] 'mfm' : ['application/vnd.mfmp'] 'mft' : ['application/rpki-manifest'] 'mgp' : ['application/vnd.osgeo.mapguide.package'] 'mgz' : ['application/vnd.proteus.magazine'] 'mht' : ['message/rfc822'] 'mhtml' : ['message/rfc822'] 'mid' : ['application/x-midi', 'audio/midi', 'audio/x-mid', 'audio/x-midi', 'music/crescendo', 'x-music/x-midi'] 'midi' : ['application/x-midi', 'audio/midi', 'audio/x-mid', 'audio/x-midi', 'music/crescendo', 'x-music/x-midi'] 'mie' : ['application/x-mie'] 'mif' : ['application/x-frame', 'application/x-mif'] 'mime' : ['message/rfc822', 'www/mime'] 'mj2' : ['video/mj2'] 'mjf' : ['audio/x-vnd.audioexplosion.mjuicemediafile'] 'mjp2' : ['video/mj2'] 'mjpg' : ['video/x-motion-jpeg'] 'mk3d' : ['video/x-matroska'] 'mka' : ['audio/x-matroska'] 'mkd' : ['text/x-markdown'] 'mks' : ['video/x-matroska'] 'mkv' : ['video/x-matroska'] 'mlp' : ['application/vnd.dolby.mlp'] 'mm' : ['application/base64', 'application/x-meme'] 'mmd' : ['application/vnd.chipnuts.karaoke-mmd'] 'mme' : ['application/base64'] 'mmf' : ['application/vnd.smaf'] 'mmr' : ['image/vnd.fujixerox.edmics-mmr'] 'mng' : ['video/x-mng'] 'mny' : ['application/x-msmoney'] 'mobi' : ['application/x-mobipocket-ebook'] 'mod' : ['audio/mod', 'audio/x-mod'] 'mods' : ['application/mods+xml'] 'moov' : ['video/quicktime'] 'mov' : ['video/quicktime'] 'movie' : ['video/x-sgi-movie'] 'mp2' : ['audio/mpeg', 'audio/x-mpeg', 'video/mpeg', 'video/x-mpeg', 'video/x-mpeq2a'] 'mp21' : ['application/mp21'] 'mp2a' : ['audio/mpeg'] 'mp3' : ['audio/mpeg3', 'audio/x-mpeg-3', 'video/mpeg', 'video/x-mpeg'] 'mp4' : ['video/mp4'] 'mp4a' : ['audio/mp4'] 'mp4s' : ['application/mp4'] 'mp4v' : ['video/mp4'] 'mpa' : ['audio/mpeg', 'video/mpeg'] 'mpc' : ['application/vnd.mophun.certificate'] 'mpe' : ['video/mpeg'] 'mpeg' : ['video/mpeg'] 'mpg' : ['audio/mpeg', 'video/mpeg'] 'mpg4' : ['video/mp4'] 'mpga' : ['audio/mpeg'] 'mpkg' : ['application/vnd.apple.installer+xml'] 'mpm' : ['application/vnd.blueice.multipass'] 'mpn' : ['application/vnd.mophun.application'] 'mpp' : ['application/vnd.ms-project'] 'mpt' : ['application/vnd.ms-project'] 'mpv' : ['application/x-project'] 'mpx' : ['application/x-project'] 'mpy' : ['application/vnd.ibm.minipay'] 'mqy' : ['application/vnd.mobius.mqy'] 'mrc' : ['application/marc'] 'mrcx' : ['application/marcxml+xml'] 'ms' : ['text/troff'] 'mscml' : ['application/mediaservercontrol+xml'] 'mseed' : ['application/vnd.fdsn.mseed'] 'mseq' : ['application/vnd.mseq'] 'msf' : ['application/vnd.epson.msf'] 'msh' : ['model/mesh'] 'msi' : ['application/x-msdownload'] 'msl' : ['application/vnd.mobius.msl'] 'msty' : ['application/vnd.muvee.style'] 'mts' : ['model/vnd.mts'] 'mus' : ['application/vnd.musician'] 'musicxml' : ['application/vnd.recordare.musicxml+xml'] 'mv' : ['video/x-sgi-movie'] 'mvb' : ['application/x-msmediaview'] 'mwf' : ['application/vnd.mfer'] 'mxf' : ['application/mxf'] 'mxl' : ['application/vnd.recordare.musicxml'] 'mxml' : ['application/xv+xml'] 'mxs' : ['application/vnd.triscape.mxs'] 'mxu' : ['video/vnd.mpegurl'] 'my' : ['audio/make'] 'mzz' : ['application/x-vnd.audioexplosion.mzz'] 'n-gage' : ['application/vnd.nokia.n-gage.symbian.install'] 'n3' : ['text/n3'] 'nap' : ['image/naplps'] 'naplps' : ['image/naplps'] 'nb' : ['application/mathematica'] 'nbp' : ['application/vnd.wolfram.player'] 'nc' : ['application/x-netcdf'] 'ncm' : ['application/vnd.nokia.configuration-message'] 'ncx' : ['application/x-dtbncx+xml'] 'nfo' : ['text/x-nfo'] 'ngdat' : ['application/vnd.nokia.n-gage.data'] 'nif' : ['image/x-niff'] 'niff' : ['image/x-niff'] 'nitf' : ['application/vnd.nitf'] 'nix' : ['application/x-mix-transfer'] 'nlu' : ['application/vnd.neurolanguage.nlu'] 'nml' : ['application/vnd.enliven'] 'nnd' : ['application/vnd.noblenet-directory'] 'nns' : ['application/vnd.noblenet-sealer'] 'nnw' : ['application/vnd.noblenet-web'] 'npx' : ['image/vnd.net-fpx'] 'nsc' : ['application/x-conference'] 'nsf' : ['application/vnd.lotus-notes'] 'ntf' : ['application/vnd.nitf'] 'nvd' : ['application/x-navidoc'] 'nws' : ['message/rfc822'] 'nzb' : ['application/x-nzb'] 'o' : ['application/octet-stream'] 'oa2' : ['application/vnd.fujitsu.oasys2'] 'oa3' : ['application/vnd.fujitsu.oasys3'] 'oas' : ['application/vnd.fujitsu.oasys'] 'obd' : ['application/x-msbinder'] 'obj' : ['application/x-tgif'] 'oda' : ['application/oda'] 'odb' : ['application/vnd.oasis.opendocument.database'] 'odc' : ['application/vnd.oasis.opendocument.chart'] 'odf' : ['application/vnd.oasis.opendocument.formula'] 'odft' : ['application/vnd.oasis.opendocument.formula-template'] 'odg' : ['application/vnd.oasis.opendocument.graphics'] 'odi' : ['application/vnd.oasis.opendocument.image'] 'odm' : ['application/vnd.oasis.opendocument.text-master'] 'odp' : ['application/vnd.oasis.opendocument.presentation'] 'ods' : ['application/vnd.oasis.opendocument.spreadsheet'] 'odt' : ['application/vnd.oasis.opendocument.text'] 'oga' : ['audio/ogg'] 'ogg' : ['audio/ogg'] 'ogv' : ['video/ogg'] 'ogx' : ['application/ogg'] 'omc' : ['application/x-omc'] 'omcd' : ['application/x-omcdatamaker'] 'omcr' : ['application/x-omcregerator'] 'omdoc' : ['application/omdoc+xml'] 'onepkg' : ['application/onenote'] 'onetmp' : ['application/onenote'] 'onetoc' : ['application/onenote'] 'onetoc2' : ['application/onenote'] 'opf' : ['application/oebps-package+xml'] 'opml' : ['text/x-opml'] 'oprc' : ['application/vnd.palm'] 'org' : ['application/vnd.lotus-organizer'] 'osf' : ['application/vnd.yamaha.openscoreformat'] 'osfpvg' : ['application/vnd.yamaha.openscoreformat.osfpvg+xml'] 'otc' : ['application/vnd.oasis.opendocument.chart-template'] 'otf' : ['font/opentype'] 'otg' : ['application/vnd.oasis.opendocument.graphics-template'] 'oth' : ['application/vnd.oasis.opendocument.text-web'] 'oti' : ['application/vnd.oasis.opendocument.image-template'] 'otm' : ['application/vnd.oasis.opendocument.text-master'] 'otp' : ['application/vnd.oasis.opendocument.presentation-template'] 'ots' : ['application/vnd.oasis.opendocument.spreadsheet-template'] 'ott' : ['application/vnd.oasis.opendocument.text-template'] 'oxps' : ['application/oxps'] 'oxt' : ['application/vnd.openofficeorg.extension'] 'p' : ['text/x-pascal'] 'p10' : ['application/pkcs10', 'application/x-pkcs10'] 'p12' : ['application/pkcs-12', 'application/x-pkcs12'] 'p7a' : ['application/x-pkcs7-signature'] 'p7b' : ['application/x-pkcs7-certificates'] 'p7c' : ['application/pkcs7-mime', 'application/x-pkcs7-mime'] 'p7m' : ['application/pkcs7-mime', 'application/x-pkcs7-mime'] 'p7r' : ['application/x-pkcs7-certreqresp'] 'p7s' : ['application/pkcs7-signature'] 'p8' : ['application/pkcs8'] 'part' : ['application/pro_eng'] 'pas' : ['text/x-pascal'] 'paw' : ['application/vnd.pawaafile'] 'pbd' : ['application/vnd.powerbuilder6'] 'pbm' : ['image/x-portable-bitmap'] 'pcap' : ['application/vnd.tcpdump.pcap'] 'pcf' : ['application/x-font-pcf'] 'pcl' : ['application/vnd.hp-pcl', 'application/x-pcl'] 'pclxl' : ['application/vnd.hp-pclxl'] 'pct' : ['image/x-pict'] 'pcurl' : ['application/vnd.curl.pcurl'] 'pcx' : ['image/x-pcx'] 'pdb' : ['application/vnd.palm'] 'pdf' : ['application/pdf'] 'pfa' : ['application/x-font-type1'] 'pfb' : ['application/x-font-type1'] 'pfm' : ['application/x-font-type1'] 'pfr' : ['application/font-tdpfr'] 'pfunk' : ['audio/make'] 'pfx' : ['application/x-pkcs12'] 'pgm' : ['image/x-portable-graymap'] 'pgn' : ['application/x-chess-pgn'] 'pgp' : ['application/pgp-encrypted'] 'php' : ['text/x-php'] 'pic' : ['image/x-pict'] 'pict' : ['image/pict'] 'pkg' : ['application/octet-stream'] 'pki' : ['application/pkixcmp'] 'pkipath' : ['application/pkix-pkipath'] 'pko' : ['application/vnd.ms-pki.pko'] 'pl' : ['text/plain', 'text/x-script.perl'] 'plb' : ['application/vnd.3gpp.pic-bw-large'] 'plc' : ['application/vnd.mobius.plc'] 'plf' : ['application/vnd.pocketlearn'] 'pls' : ['application/pls+xml'] 'plx' : ['application/x-pixclscript'] 'pm' : ['image/x-xpixmap', 'text/x-script.perl-module'] 'pm4' : ['application/x-pagemaker'] 'pm5' : ['application/x-pagemaker'] 'pml' : ['application/vnd.ctc-posml'] 'png' : ['image/png'] 'pnm' : ['application/x-portable-anymap', 'image/x-portable-anymap'] 'portpkg' : ['application/vnd.macports.portpkg'] 'pot' : ['application/mspowerpoint', 'application/vnd.ms-powerpoint'] 'potm' : ['application/vnd.ms-powerpoint.template.macroenabled.12'] 'potx' : ['application/vnd.openxmlformats-officedocument.presentationml.template'] 'pov' : ['model/x-pov'] 'ppa' : ['application/vnd.ms-powerpoint'] 'ppam' : ['application/vnd.ms-powerpoint.addin.macroenabled.12'] 'ppd' : ['application/vnd.cups-ppd'] 'ppm' : ['image/x-portable-pixmap'] 'pps' : ['application/mspowerpoint', 'application/vnd.ms-powerpoint'] 'ppsm' : ['application/vnd.ms-powerpoint.slideshow.macroenabled.12'] 'ppsx' : ['application/vnd.openxmlformats-officedocument.presentationml.slideshow'] 'ppt' : ['application/mspowerpoint', 'application/powerpoint', 'application/vnd.ms-powerpoint', 'application/x-mspowerpoint'] 'pptm' : ['application/vnd.ms-powerpoint.presentation.macroenabled.12'] 'pptx' : ['application/vnd.openxmlformats-officedocument.presentationml.presentation'] 'ppz' : ['application/mspowerpoint'] 'pqa' : ['application/vnd.palm'] 'prc' : ['application/x-mobipocket-ebook'] 'pre' : ['application/vnd.lotus-freelance'] 'prf' : ['application/pics-rules'] 'prt' : ['application/pro_eng'] 'ps' : ['application/postscript'] 'psb' : ['application/vnd.3gpp.pic-bw-small'] 'psd' : ['image/vnd.adobe.photoshop'] 'psf' : ['application/x-font-linux-psf'] 'pskcxml' : ['application/pskc+xml'] 'ptid' : ['application/vnd.pvi.ptid1'] 'pub' : ['application/x-mspublisher'] 'pvb' : ['application/vnd.3gpp.pic-bw-var'] 'pvu' : ['paleovu/x-pv'] 'pwn' : ['application/vnd.3m.post-it-notes'] 'pwz' : ['application/vnd.ms-powerpoint'] 'py' : ['text/x-script.phyton'] 'pya' : ['audio/vnd.ms-playready.media.pya'] 'pyc' : ['applicaiton/x-bytecode.python'] 'pyo' : ['application/x-python-code'] 'pyv' : ['video/vnd.ms-playready.media.pyv'] 'qam' : ['application/vnd.epson.quickanime'] 'qbo' : ['application/vnd.intu.qbo'] 'qcp' : ['audio/vnd.qcelp'] 'qd3' : ['x-world/x-3dmf'] 'qd3d' : ['x-world/x-3dmf'] 'qfx' : ['application/vnd.intu.qfx'] 'qif' : ['image/x-quicktime'] 'qps' : ['application/vnd.publishare-delta-tree'] 'qt' : ['video/quicktime'] 'qtc' : ['video/x-qtc'] 'qti' : ['image/x-quicktime'] 'qtif' : ['image/x-quicktime'] 'qwd' : ['application/vnd.quark.quarkxpress'] 'qwt' : ['application/vnd.quark.quarkxpress'] 'qxb' : ['application/vnd.quark.quarkxpress'] 'qxd' : ['application/vnd.quark.quarkxpress'] 'qxl' : ['application/vnd.quark.quarkxpress'] 'qxt' : ['application/vnd.quark.quarkxpress'] 'ra' : ['audio/x-pn-realaudio', 'audio/x-pn-realaudio-plugin', 'audio/x-realaudio'] 'ram' : ['audio/x-pn-realaudio'] 'rar' : ['application/x-rar-compressed'] 'ras' : ['application/x-cmu-raster', 'image/cmu-raster', 'image/x-cmu-raster'] 'rast' : ['image/cmu-raster'] 'rcprofile' : ['application/vnd.ipunplugged.rcprofile'] 'rdf' : ['application/rdf+xml'] 'rdz' : ['application/vnd.data-vision.rdz'] 'rep' : ['application/vnd.businessobjects'] 'res' : ['application/x-dtbresource+xml'] 'rexx' : ['text/x-script.rexx'] 'rf' : ['image/vnd.rn-realflash'] 'rgb' : ['image/x-rgb'] 'rif' : ['application/reginfo+xml'] 'rip' : ['audio/vnd.rip'] 'ris' : ['application/x-research-info-systems'] 'rl' : ['application/resource-lists+xml'] 'rlc' : ['image/vnd.fujixerox.edmics-rlc'] 'rld' : ['application/resource-lists-diff+xml'] 'rm' : ['application/vnd.rn-realmedia', 'audio/x-pn-realaudio'] 'rmi' : ['audio/midi'] 'rmm' : ['audio/x-pn-realaudio'] 'rmp' : ['audio/x-pn-realaudio', 'audio/x-pn-realaudio-plugin'] 'rms' : ['application/vnd.jcp.javame.midlet-rms'] 'rmvb' : ['application/vnd.rn-realmedia-vbr'] 'rnc' : ['application/relax-ng-compact-syntax'] 'rng' : ['application/ringing-tones', 'application/vnd.nokia.ringing-tone'] 'rnx' : ['application/vnd.rn-realplayer'] 'roa' : ['application/rpki-roa'] 'roff' : ['text/troff'] 'rp' : ['image/vnd.rn-realpix'] 'rp9' : ['application/vnd.cloanto.rp9'] 'rpm' : ['audio/x-pn-realaudio-plugin'] 'rpss' : ['application/vnd.nokia.radio-presets'] 'rpst' : ['application/vnd.nokia.radio-preset'] 'rq' : ['application/sparql-query'] 'rs' : ['application/rls-services+xml'] 'rsd' : ['application/rsd+xml'] 'rss' : ['application/rss+xml'] 'rt' : ['text/richtext', 'text/vnd.rn-realtext'] 'rtf' : ['application/rtf', 'application/x-rtf', 'text/richtext'] 'rtx' : ['application/rtf', 'text/richtext'] 'rv' : ['video/vnd.rn-realvideo'] 's' : ['text/x-asm'] 's3m' : ['audio/s3m'] 'saf' : ['application/vnd.yamaha.smaf-audio'] 'saveme' : ['aapplication/octet-stream'] 'sbk' : ['application/x-tbook'] 'sbml' : ['application/sbml+xml'] 'sc' : ['application/vnd.ibm.secure-container'] 'scd' : ['application/x-msschedule'] 'scm' : ['application/x-lotusscreencam', 'text/x-script.guile', 'text/x-script.scheme', 'video/x-scm'] 'scq' : ['application/scvp-cv-item'] 'scs' : ['application/scvp-cv-response'] 'scurl' : ['text/vnd.curl.scurl'] 'sda' : ['application/vnd.stardivision.draw'] 'sdc' : ['application/vnd.stardivision.calc'] 'sdd' : ['application/vnd.stardivision.impress'] 'sdkd' : ['application/vnd.solent.sdkm+xml'] 'sdkm' : ['application/vnd.solent.sdkm+xml'] 'sdml' : ['text/plain'] 'sdp' : ['application/sdp', 'application/x-sdp'] 'sdr' : ['application/sounder'] 'sdw' : ['application/vnd.stardivision.writer'] 'sea' : ['application/sea', 'application/x-sea'] 'see' : ['application/vnd.seemail'] 'seed' : ['application/vnd.fdsn.seed'] 'sema' : ['application/vnd.sema'] 'semd' : ['application/vnd.semd'] 'semf' : ['application/vnd.semf'] 'ser' : ['application/java-serialized-object'] 'set' : ['application/set'] 'setpay' : ['application/set-payment-initiation'] 'setreg' : ['application/set-registration-initiation'] 'sfd-hdstx' : ['application/vnd.hydrostatix.sof-data'] 'sfs' : ['application/vnd.spotfire.sfs'] 'sfv' : ['text/x-sfv'] 'sgi' : ['image/sgi'] 'sgl' : ['application/vnd.stardivision.writer-global'] 'sgm' : ['text/sgml', 'text/x-sgml'] 'sgml' : ['text/sgml', 'text/x-sgml'] 'sh' : ['application/x-bsh', 'application/x-sh', 'application/x-shar', 'text/x-script.sh'] 'shar' : ['application/x-bsh', 'application/x-shar'] 'shf' : ['application/shf+xml'] 'shtml' : ['text/html', 'text/x-server-parsed-html'] 'si' : ['text/vnd.wap.si'] 'sic' : ['application/vnd.wap.sic'] 'sid' : ['image/x-mrsid-image'] 'sig' : ['application/pgp-signature'] 'sil' : ['audio/silk'] 'silo' : ['model/mesh'] 'sis' : ['application/vnd.symbian.install'] 'sisx' : ['application/vnd.symbian.install'] 'sit' : ['application/x-sit', 'application/x-stuffit'] 'sitx' : ['application/x-stuffitx'] 'skd' : ['application/vnd.koan'] 'skm' : ['application/vnd.koan'] 'skp' : ['application/vnd.koan'] 'skt' : ['application/vnd.koan'] 'sl' : ['application/x-seelogo'] 'slc' : ['application/vnd.wap.slc'] 'sldm' : ['application/vnd.ms-powerpoint.slide.macroenabled.12'] 'sldx' : ['application/vnd.openxmlformats-officedocument.presentationml.slide'] 'slt' : ['application/vnd.epson.salt'] 'sm' : ['application/vnd.stepmania.stepchart'] 'smf' : ['application/vnd.stardivision.math'] 'smi' : ['application/smil+xml'] 'smil' : ['application/smil+xml'] 'smv' : ['video/x-smv'] 'smzip' : ['application/vnd.stepmania.package'] 'snd' : ['audio/basic', 'audio/x-adpcm'] 'snf' : ['application/x-font-snf'] 'so' : ['application/octet-stream'] 'sol' : ['application/solids'] 'spc' : ['application/x-pkcs7-certificates', 'text/x-speech'] 'spf' : ['application/vnd.yamaha.smaf-phrase'] 'spl' : ['application/x-futuresplash'] 'spot' : ['text/vnd.in3d.spot'] 'spp' : ['application/scvp-vp-response'] 'spq' : ['application/scvp-vp-item'] 'spr' : ['application/x-sprite'] 'sprite' : ['application/x-sprite'] 'spx' : ['audio/ogg'] 'sql' : ['application/x-sql'] 'src' : ['application/x-wais-source'] 'srt' : ['application/x-subrip'] 'sru' : ['application/sru+xml'] 'srx' : ['application/sparql-results+xml'] 'ssdl' : ['application/ssdl+xml'] 'sse' : ['application/vnd.kodak-descriptor'] 'ssf' : ['application/vnd.epson.ssf'] 'ssi' : ['text/x-server-parsed-html'] 'ssm' : ['application/streamingmedia'] 'ssml' : ['application/ssml+xml'] 'sst' : ['application/vnd.ms-pki.certstore'] 'st' : ['application/vnd.sailingtracker.track'] 'stc' : ['application/vnd.sun.xml.calc.template'] 'std' : ['application/vnd.sun.xml.draw.template'] 'step' : ['application/step'] 'stf' : ['application/vnd.wt.stf'] 'sti' : ['application/vnd.sun.xml.impress.template'] 'stk' : ['application/hyperstudio'] 'stl' : ['application/sla', 'application/vnd.ms-pki.stl', 'application/x-navistyle'] 'stp' : ['application/step'] 'str' : ['application/vnd.pg.format'] 'stw' : ['application/vnd.sun.xml.writer.template'] 'sub' : ['text/vnd.dvb.subtitle'] 'sus' : ['application/vnd.sus-calendar'] 'susp' : ['application/vnd.sus-calendar'] 'sv4cpio' : ['application/x-sv4cpio'] 'sv4crc' : ['application/x-sv4crc'] 'svc' : ['application/vnd.dvb.service'] 'svd' : ['application/vnd.svd'] 'svf' : ['image/vnd.dwg', 'image/x-dwg'] 'svg' : ['image/svg+xml'] 'svgz' : ['image/svg+xml'] 'svr' : ['application/x-world', 'x-world/x-svr'] 'swa' : ['application/x-director'] 'swf' : ['application/x-shockwave-flash'] 'swi' : ['application/vnd.aristanetworks.swi'] 'sxc' : ['application/vnd.sun.xml.calc'] 'sxd' : ['application/vnd.sun.xml.draw'] 'sxg' : ['application/vnd.sun.xml.writer.global'] 'sxi' : ['application/vnd.sun.xml.impress'] 'sxm' : ['application/vnd.sun.xml.math'] 'sxw' : ['application/vnd.sun.xml.writer'] 't' : ['text/troff'] 't3' : ['application/x-t3vm-image'] 'taglet' : ['application/vnd.mynfc'] 'talk' : ['text/x-speech'] 'tao' : ['application/vnd.tao.intent-module-archive'] 'tar' : ['application/x-tar'] 'tbk' : ['application/toolbook', 'application/x-tbook'] 'tcap' : ['application/vnd.3gpp2.tcap'] 'tcl' : ['application/x-tcl', 'text/x-script.tcl'] 'tcsh' : ['text/x-script.tcsh'] 'teacher' : ['application/vnd.smart.teacher'] 'tei' : ['application/tei+xml'] 'teicorpus' : ['application/tei+xml'] 'tex' : ['application/x-tex'] 'texi' : ['application/x-texinfo'] 'texinfo' : ['application/x-texinfo'] 'text' : ['application/plain', 'text/plain'] 'tfi' : ['application/thraud+xml'] 'tfm' : ['application/x-tex-tfm'] 'tga' : ['image/x-tga'] 'tgz' : ['application/gnutar', 'application/x-compressed'] 'thmx' : ['application/vnd.ms-officetheme'] 'tif' : ['image/tiff', 'image/x-tiff'] 'tiff' : ['image/tiff', 'image/x-tiff'] 'tmo' : ['application/vnd.tmobile-livetv'] 'torrent' : ['application/x-bittorrent'] 'tpl' : ['application/vnd.groove-tool-template'] 'tpt' : ['application/vnd.trid.tpt'] 'tr' : ['text/troff'] 'tra' : ['application/vnd.trueapp'] 'trm' : ['application/x-msterminal'] 'ts' : ['video/MP2T'] 'tsd' : ['application/timestamped-data'] 'tsi' : ['audio/tsp-audio'] 'tsp' : ['application/dsptype', 'audio/tsplayer'] 'tsv' : ['text/tab-separated-values'] 'ttc' : ['application/x-font-ttf'] 'ttf' : ['application/x-font-ttf'] 'ttl' : ['text/turtle'] 'turbot' : ['image/florian'] 'twd' : ['application/vnd.simtech-mindmapper'] 'twds' : ['application/vnd.simtech-mindmapper'] 'txd' : ['application/vnd.genomatix.tuxedo'] 'txf' : ['application/vnd.mobius.txf'] 'txt' : ['text/plain'] 'u32' : ['application/x-authorware-bin'] 'udeb' : ['application/x-debian-package'] 'ufd' : ['application/vnd.ufdl'] 'ufdl' : ['application/vnd.ufdl'] 'uil' : ['text/x-uil'] 'ulx' : ['application/x-glulx'] 'umj' : ['application/vnd.umajin'] 'uni' : ['text/uri-list'] 'unis' : ['text/uri-list'] 'unityweb' : ['application/vnd.unity'] 'unv' : ['application/i-deas'] 'uoml' : ['application/vnd.uoml+xml'] 'uri' : ['text/uri-list'] 'uris' : ['text/uri-list'] 'urls' : ['text/uri-list'] 'ustar' : ['application/x-ustar', 'multipart/x-ustar'] 'utz' : ['application/vnd.uiq.theme'] 'uu' : ['application/octet-stream', 'text/x-uuencode'] 'uue' : ['text/x-uuencode'] 'uva' : ['audio/vnd.dece.audio'] 'uvd' : ['application/vnd.dece.data'] 'uvf' : ['application/vnd.dece.data'] 'uvg' : ['image/vnd.dece.graphic'] 'uvh' : ['video/vnd.dece.hd'] 'uvi' : ['image/vnd.dece.graphic'] 'uvm' : ['video/vnd.dece.mobile'] 'uvp' : ['video/vnd.dece.pd'] 'uvs' : ['video/vnd.dece.sd'] 'uvt' : ['application/vnd.dece.ttml+xml'] 'uvu' : ['video/vnd.uvvu.mp4'] 'uvv' : ['video/vnd.dece.video'] 'uvva' : ['audio/vnd.dece.audio'] 'uvvd' : ['application/vnd.dece.data'] 'uvvf' : ['application/vnd.dece.data'] 'uvvg' : ['image/vnd.dece.graphic'] 'uvvh' : ['video/vnd.dece.hd'] 'uvvi' : ['image/vnd.dece.graphic'] 'uvvm' : ['video/vnd.dece.mobile'] 'uvvp' : ['video/vnd.dece.pd'] 'uvvs' : ['video/vnd.dece.sd'] 'uvvt' : ['application/vnd.dece.ttml+xml'] 'uvvu' : ['video/vnd.uvvu.mp4'] 'uvvv' : ['video/vnd.dece.video'] 'uvvx' : ['application/vnd.dece.unspecified'] 'uvvz' : ['application/vnd.dece.zip'] 'uvx' : ['application/vnd.dece.unspecified'] 'uvz' : ['application/vnd.dece.zip'] 'vcard' : ['text/vcard'] 'vcd' : ['application/x-cdlink'] 'vcf' : ['text/x-vcard'] 'vcg' : ['application/vnd.groove-vcard'] 'vcs' : ['text/x-vcalendar'] 'vcx' : ['application/vnd.vcx'] 'vda' : ['application/vda'] 'vdo' : ['video/vdo'] 'vew' : ['application/groupwise'] 'vis' : ['application/vnd.visionary'] 'viv' : ['video/vivo', 'video/vnd.vivo'] 'vivo' : ['video/vivo', 'video/vnd.vivo'] 'vmd' : ['application/vocaltec-media-desc'] 'vmf' : ['application/vocaltec-media-file'] 'vob' : ['video/x-ms-vob'] 'voc' : ['audio/voc', 'audio/x-voc'] 'vor' : ['application/vnd.stardivision.writer'] 'vos' : ['video/vosaic'] 'vox' : ['application/x-authorware-bin'] 'vqe' : ['audio/x-twinvq-plugin'] 'vqf' : ['audio/x-twinvq'] 'vql' : ['audio/x-twinvq-plugin'] 'vrml' : ['application/x-vrml', 'model/vrml', 'x-world/x-vrml'] 'vrt' : ['x-world/x-vrt'] 'vsd' : ['application/vnd.visio'] 'vsf' : ['application/vnd.vsf'] 'vss' : ['application/vnd.visio'] 'vst' : ['application/vnd.visio'] 'vsw' : ['application/vnd.visio'] 'vtt' : ['text/vtt'] 'vtu' : ['model/vnd.vtu'] 'vxml' : ['application/voicexml+xml'] 'w3d' : ['application/x-director'] 'w60' : ['application/wordperfect6.0'] 'w61' : ['application/wordperfect6.1'] 'w6w' : ['application/msword'] 'wad' : ['application/x-doom'] 'wav' : ['audio/wav', 'audio/x-wav'] 'wax' : ['audio/x-ms-wax'] 'wb1' : ['application/x-qpro'] 'wbmp' : ['image/vnd.wap.wbmp'] 'wbs' : ['application/vnd.criticaltools.wbs+xml'] 'wbxml' : ['application/vnd.wap.wbxml'] 'wcm' : ['application/vnd.ms-works'] 'wdb' : ['application/vnd.ms-works'] 'wdp' : ['image/vnd.ms-photo'] 'web' : ['application/vnd.xara'] 'weba' : ['audio/webm'] 'webapp' : ['application/x-web-app-manifest+json'] 'webm' : ['video/webm'] 'webp' : ['image/webp'] 'wg' : ['application/vnd.pmi.widget'] 'wgt' : ['application/widget'] 'wiz' : ['application/msword'] 'wk1' : ['application/x-123'] 'wks' : ['application/vnd.ms-works'] 'wm' : ['video/x-ms-wm'] 'wma' : ['audio/x-ms-wma'] 'wmd' : ['application/x-ms-wmd'] 'wmf' : ['application/x-msmetafile'] 'wml' : ['text/vnd.wap.wml'] 'wmlc' : ['application/vnd.wap.wmlc'] 'wmls' : ['text/vnd.wap.wmlscript'] 'wmlsc' : ['application/vnd.wap.wmlscriptc'] 'wmv' : ['video/x-ms-wmv'] 'wmx' : ['video/x-ms-wmx'] 'wmz' : ['application/x-msmetafile'] 'woff' : ['application/x-font-woff'] 'word' : ['application/msword'] 'wp' : ['application/wordperfect'] 'wp5' : ['application/wordperfect', 'application/wordperfect6.0'] 'wp6' : ['application/wordperfect'] 'wpd' : ['application/wordperfect', 'application/x-wpwin'] 'wpl' : ['application/vnd.ms-wpl'] 'wps' : ['application/vnd.ms-works'] 'wq1' : ['application/x-lotus'] 'wqd' : ['application/vnd.wqd'] 'wri' : ['application/mswrite', 'application/x-wri'] 'wrl' : ['application/x-world', 'model/vrml', 'x-world/x-vrml'] 'wrz' : ['model/vrml', 'x-world/x-vrml'] 'wsc' : ['text/scriplet'] 'wsdl' : ['application/wsdl+xml'] 'wspolicy' : ['application/wspolicy+xml'] 'wsrc' : ['application/x-wais-source'] 'wtb' : ['application/vnd.webturbo'] 'wtk' : ['application/x-wintalk'] 'wvx' : ['video/x-ms-wvx'] 'x-png' : ['image/png'] 'x32' : ['application/x-authorware-bin'] 'x3d' : ['model/x3d+xml'] 'x3db' : ['model/x3d+binary'] 'x3dbz' : ['model/x3d+binary'] 'x3dv' : ['model/x3d+vrml'] 'x3dvz' : ['model/x3d+vrml'] 'x3dz' : ['model/x3d+xml'] 'xaml' : ['application/xaml+xml'] 'xap' : ['application/x-silverlight-app'] 'xar' : ['application/vnd.xara'] 'xbap' : ['application/x-ms-xbap'] 'xbd' : ['application/vnd.fujixerox.docuworks.binder'] 'xbm' : ['image/x-xbitmap', 'image/x-xbm', 'image/xbm'] 'xdf' : ['application/xcap-diff+xml'] 'xdm' : ['application/vnd.syncml.dm+xml'] 'xdp' : ['application/vnd.adobe.xdp+xml'] 'xdr' : ['video/x-amt-demorun'] 'xdssc' : ['application/dssc+xml'] 'xdw' : ['application/vnd.fujixerox.docuworks'] 'xenc' : ['application/xenc+xml'] 'xer' : ['application/patch-ops-error+xml'] 'xfdf' : ['application/vnd.adobe.xfdf'] 'xfdl' : ['application/vnd.xfdl'] 'xgz' : ['xgl/drawing'] 'xht' : ['application/xhtml+xml'] 'xhtml' : ['application/xhtml+xml'] 'xhvml' : ['application/xv+xml'] 'xif' : ['image/vnd.xiff'] 'xl' : ['application/excel'] 'xla' : ['application/excel', 'application/x-excel', 'application/x-msexcel'] 'xlam' : ['application/vnd.ms-excel.addin.macroenabled.12'] 'xlb' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel'] 'xlc' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel'] 'xld' : ['application/excel', 'application/x-excel'] 'xlf' : ['application/x-xliff+xml'] 'xlk' : ['application/excel', 'application/x-excel'] 'xll' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel'] 'xlm' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel'] 'xls' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel', 'application/x-msexcel'] 'xlsb' : ['application/vnd.ms-excel.sheet.binary.macroenabled.12'] 'xlsm' : ['application/vnd.ms-excel.sheet.macroenabled.12'] 'xlsx' : ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'] 'xlt' : ['application/excel', 'application/x-excel'] 'xltm' : ['application/vnd.ms-excel.template.macroenabled.12'] 'xltx' : ['application/vnd.openxmlformats-officedocument.spreadsheetml.template'] 'xlv' : ['application/excel', 'application/x-excel'] 'xlw' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel', 'application/x-msexcel'] 'xm' : ['audio/xm'] 'xml' : ['application/xml', 'text/xml'] 'xmz' : ['xgl/movie'] 'xo' : ['application/vnd.olpc-sugar'] 'xop' : ['application/xop+xml'] 'xpdl' : ['application/xml'] 'xpi' : ['application/x-xpinstall'] 'xpix' : ['application/x-vnd.ls-xpix'] 'xpl' : ['application/xproc+xml'] 'xpm' : ['image/x-xpixmap', 'image/xpm'] 'xpr' : ['application/vnd.is-xpr'] 'xps' : ['application/vnd.ms-xpsdocument'] 'xpw' : ['application/vnd.intercon.formnet'] 'xpx' : ['application/vnd.intercon.formnet'] 'xsl' : ['application/xml'] 'xslt' : ['application/xslt+xml'] 'xsm' : ['application/vnd.syncml+xml'] 'xspf' : ['application/xspf+xml'] 'xsr' : ['video/x-amt-showrun'] 'xul' : ['application/vnd.mozilla.xul+xml'] 'xvm' : ['application/xv+xml'] 'xvml' : ['application/xv+xml'] 'xwd' : ['image/x-xwd', 'image/x-xwindowdump'] 'xyz' : ['chemical/x-xyz'] 'xz' : ['application/x-xz'] 'yang' : ['application/yang'] 'yin' : ['application/yin+xml'] 'z' : ['application/x-compress', 'application/x-compressed'] 'z1' : ['application/x-zmachine'] 'z2' : ['application/x-zmachine'] 'z3' : ['application/x-zmachine'] 'z4' : ['application/x-zmachine'] 'z5' : ['application/x-zmachine'] 'z6' : ['application/x-zmachine'] 'z7' : ['application/x-zmachine'] 'z8' : ['application/x-zmachine'] 'zaz' : ['application/vnd.zzazz.deck+xml'] 'zip' : ['application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'] 'zir' : ['application/vnd.zul'] 'zirz' : ['application/vnd.zul'] 'zmm' : ['application/vnd.handheld-entertainment+xml'] 'zoo' : ['application/octet-stream'] 'zsh' : ['text/x-script.zsh'] '123' : ['application/vnd.lotus-1-2-3'] module.exports = MimebyFileExtension : byFileExtension
101341
### Translation of gist https://gist.github.com/nimasdj/801b0b1a50112ea6a997 Total: 1223 extensions as of 16 November 2015 ### byFileExtension = '3dm' : ['x-world/x-3dmf'] '3dmf' : ['x-world/x-3dmf'] '3dml' : ['text/vnd.in3d.3dml'] '3ds' : ['image/x-3ds'] '3g2' : ['video/3gpp2'] '3gp' : ['video/3gpp'] '7z' : ['application/x-7z-compressed'] 'a' : ['application/octet-stream'] 'aab' : ['application/x-authorware-bin'] 'aac' : ['audio/x-aac'] 'aam' : ['application/x-authorware-map'] 'aas' : ['application/x-authorware-seg'] 'abc' : ['text/vnd.abc'] 'abw' : ['application/x-abiword'] 'ac' : ['application/pkix-attr-cert'] 'acc' : ['application/vnd.americandynamics.acc'] 'ace' : ['application/x-ace-compressed'] 'acgi' : ['text/html'] 'acu' : ['application/vnd.acucobol'] 'acutc' : ['application/vnd.acucorp'] 'adp' : ['audio/adpcm'] 'aep' : ['application/vnd.audiograph'] 'afl' : ['video/animaflex'] 'afm' : ['application/x-font-type1'] 'afp' : ['application/vnd.ibm.modcap'] 'ahead' : ['application/vnd.ahead.space'] 'ai' : ['application/postscript'] 'aif' : ['audio/aiff', 'audio/x-aiff'] 'aifc' : ['audio/aiff', 'audio/x-aiff'] 'aiff' : ['audio/aiff', 'audio/x-aiff'] 'aim' : ['application/x-aim'] 'aip' : ['text/x-audiosoft-intra'] 'air' : ['application/vnd.adobe.air-application-installer-package+zip'] 'ait' : ['application/vnd.dvb.ait'] 'ami' : ['application/vnd.amiga.ami'] 'ani' : ['application/x-navi-animation'] 'aos' : ['application/x-nokia-9000-communicator-add-on-software'] 'apk' : ['application/vnd.android.package-archive'] 'appcache' : ['text/cache-manifest'] 'application' : ['application/x-ms-application'] 'apr' : ['application/vnd.lotus-approach'] 'aps' : ['application/mime'] 'arc' : ['application/x-freearc'] 'arj' : ['application/arj', 'application/octet-stream'] 'art' : ['image/x-jg'] 'asc' : ['application/pgp-signature'] 'asf' : ['video/x-ms-asf'] 'asm' : ['text/x-asm'] 'aso' : ['application/vnd.accpac.simply.aso'] 'asp' : ['text/asp'] 'asx' : ['application/x-mplayer2', 'video/x-ms-asf', 'video/x-ms-asf-plugin'] 'atc' : ['application/vnd.acucorp'] 'atom' : ['application/atom+xml'] 'atomcat' : ['application/atomcat+xml'] 'atomsvc' : ['application/atomsvc+xml'] 'atx' : ['application/vnd.antix.game-component'] 'au' : ['audio/basic'] 'avi' : ['application/x-troff-msvideo', 'video/avi', 'video/msvideo', 'video/x-msvideo'] 'avs' : ['video/avs-video'] 'aw' : ['application/applixware'] 'azf' : ['application/vnd.airzip.filesecure.azf'] 'azs' : ['application/vnd.airzip.filesecure.azs'] 'azw' : ['application/vnd.amazon.ebook'] 'bat' : ['application/x-msdownload'] 'bcpio' : ['application/x-bcpio'] 'bdf' : ['application/x-font-bdf'] 'bdm' : ['application/vnd.syncml.dm+wbxml'] 'bed' : ['application/vnd.realvnc.bed'] 'bh2' : ['application/vnd.fujitsu.oasysprs'] 'bin' : ['application/mac-binary', 'application/macbinary', 'application/octet-stream', 'application/x-binary', 'application/x-macbinary'] 'blb' : ['application/x-blorb'] 'blorb' : ['application/x-blorb'] 'bm' : ['image/bmp'] 'bmi' : ['application/vnd.bmi'] 'bmp' : ['image/bmp', 'image/x-windows-bmp'] 'boo' : ['application/book'] 'book' : ['application/vnd.framemaker'] 'box' : ['application/vnd.previewsystems.box'] 'boz' : ['application/x-bzip2'] 'bpk' : ['application/octet-stream'] 'bsh' : ['application/x-bsh'] 'btif' : ['image/prs.btif'] 'buffer' : ['application/octet-stream'] 'bz' : ['application/x-bzip'] 'bz2' : ['application/x-bzip2'] 'c' : ['text/x-c'] 'c++' : ['text/plain'] 'c11amc' : ['application/vnd.cluetrust.cartomobile-config'] 'c11amz' : ['application/vnd.cluetrust.cartomobile-config-pkg'] 'c4d' : ['application/vnd.clonk.c4group'] 'c4f' : ['application/vnd.clonk.c4group'] 'c4g' : ['application/vnd.clonk.c4group'] 'c4p' : ['application/vnd.clonk.c4group'] 'c4u' : ['application/vnd.clonk.c4group'] 'cab' : ['application/vnd.ms-cab-compressed'] 'caf' : ['audio/x-caf'] 'cap' : ['application/vnd.tcpdump.pcap'] 'car' : ['application/vnd.curl.car'] 'cat' : ['application/vnd.ms-pki.seccat'] 'cb7' : ['application/x-cbr'] 'cba' : ['application/x-cbr'] 'cbr' : ['application/x-cbr'] 'cbt' : ['application/x-cbr'] 'cbz' : ['application/x-cbr'] 'cc' : ['text/plain', 'text/x-c'] 'ccad' : ['application/clariscad'] 'cco' : ['application/x-cocoa'] 'cct' : ['application/x-director'] 'ccxml' : ['application/ccxml+xml'] 'cdbcmsg' : ['application/vnd.contact.cmsg'] 'cdf' : ['application/cdf', 'application/x-cdf', 'application/x-netcdf'] 'cdkey' : ['application/vnd.mediastation.cdkey'] 'cdmia' : ['application/cdmi-capability'] 'cdmic' : ['application/cdmi-container'] 'cdmid' : ['application/cdmi-domain'] 'cdmio' : ['application/cdmi-object'] 'cdmiq' : ['application/cdmi-queue'] 'cdx' : ['chemical/x-cdx'] 'cdxml' : ['application/vnd.chemdraw+xml'] 'cdy' : ['application/vnd.cinderella'] 'cer' : ['application/pkix-cert', 'application/x-x509-ca-cert'] 'cfs' : ['application/x-cfs-compressed'] 'cgm' : ['image/cgm'] 'cha' : ['application/x-chat'] 'chat' : ['application/x-chat'] 'chm' : ['application/vnd.ms-htmlhelp'] 'chrt' : ['application/vnd.kde.kchart'] 'cif' : ['chemical/x-cif'] 'cii' : ['application/vnd.anser-web-certificate-issue-initiation'] 'cil' : ['application/vnd.ms-artgalry'] 'cla' : ['application/vnd.claymore'] 'class' : ['application/java', 'application/java-byte-code', 'application/x-java-class'] 'clkk' : ['application/vnd.crick.clicker.keyboard'] 'clkp' : ['application/vnd.crick.clicker.palette'] 'clkt' : ['application/vnd.crick.clicker.template'] 'clkw' : ['application/vnd.crick.clicker.wordbank'] 'clkx' : ['application/vnd.crick.clicker'] 'clp' : ['application/x-msclip'] 'cmc' : ['application/vnd.cosmocaller'] 'cmdf' : ['chemical/x-cmdf'] 'cml' : ['chemical/x-cml'] 'cmp' : ['application/vnd.yellowriver-custom-menu'] 'cmx' : ['image/x-cmx'] 'cod' : ['application/vnd.rim.cod'] 'com' : ['application/octet-stream', 'text/plain'] 'conf' : ['text/plain'] 'cpio' : ['application/x-cpio'] 'cpp' : ['text/x-c'] 'cpt' : ['application/x-compactpro', 'application/x-cpt'] 'crd' : ['application/x-mscardfile'] 'crl' : ['application/pkcs-crl', 'application/pkix-crl'] 'crt' : ['application/pkix-cert', 'application/x-x509-ca-cert', 'application/x-x509-user-cert'] 'crx' : ['application/x-chrome-extension'] 'cryptonote' : ['application/vnd.rig.cryptonote'] 'csh' : ['application/x-csh', 'text/x-script.csh'] 'csml' : ['chemical/x-csml'] 'csp' : ['application/vnd.commonspace'] 'css' : ['application/x-pointplus', 'text/css'] 'cst' : ['application/x-director'] 'csv' : ['text/csv'] 'cu' : ['application/cu-seeme'] 'curl' : ['text/vnd.curl'] 'cww' : ['application/prs.cww'] 'cxt' : ['application/x-director'] 'cxx' : ['text/x-c'] 'dae' : ['model/vnd.collada+xml'] 'daf' : ['application/vnd.mobius.daf'] 'dart' : ['application/vnd.dart'] 'dataless' : ['application/vnd.fdsn.seed'] 'davmount' : ['application/davmount+xml'] 'dbk' : ['application/docbook+xml'] 'dcr' : ['application/x-director'] 'dcurl' : ['text/vnd.curl.dcurl'] 'dd2' : ['application/vnd.oma.dd2+xml'] 'ddd' : ['application/vnd.fujixerox.ddd'] 'deb' : ['application/x-debian-package'] 'deepv' : ['application/x-deepv'] 'def' : ['text/plain'] 'deploy' : ['application/octet-stream'] 'der' : ['application/x-x509-ca-cert'] 'dfac' : ['application/vnd.dreamfactory'] 'dgc' : ['application/x-dgc-compressed'] 'dic' : ['text/x-c'] 'dif' : ['video/x-dv'] 'diff' : ['text/plain'] 'dir' : ['application/x-director'] 'dis' : ['application/vnd.mobius.dis'] 'dist' : ['application/octet-stream'] 'distz' : ['application/octet-stream'] 'djv' : ['image/vnd.djvu'] 'djvu' : ['image/vnd.djvu'] 'dl' : ['video/dl', 'video/x-dl'] 'dll' : ['application/x-msdownload'] 'dmg' : ['application/x-apple-diskimage'] 'dmp' : ['application/vnd.tcpdump.pcap'] 'dms' : ['application/octet-stream'] 'dna' : ['application/vnd.dna'] 'doc' : ['application/msword'] 'docm' : ['application/vnd.ms-word.document.macroenabled.12'] 'docx' : ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'] 'dot' : ['application/msword'] 'dotm' : ['application/vnd.ms-word.template.macroenabled.12'] 'dotx' : ['application/vnd.openxmlformats-officedocument.wordprocessingml.template'] 'dp' : ['application/vnd.osgi.dp'] 'dpg' : ['application/vnd.dpgraph'] 'dra' : ['audio/vnd.dra'] 'drw' : ['application/drafting'] 'dsc' : ['text/prs.lines.tag'] 'dssc' : ['application/dssc+der'] 'dtb' : ['application/x-dtbook+xml'] 'dtd' : ['application/xml-dtd'] 'dts' : ['audio/vnd.dts'] 'dtshd' : ['audio/vnd.dts.hd'] 'dump' : ['application/octet-stream'] 'dv' : ['video/x-dv'] 'dvb' : ['video/vnd.dvb.file'] 'dvi' : ['application/x-dvi'] 'dwf' : ['drawing/x-dwf (old)', 'model/vnd.dwf'] 'dwg' : ['application/acad', 'image/vnd.dwg', 'image/x-dwg'] 'dxf' : ['image/vnd.dxf'] 'dxp' : ['application/vnd.spotfire.dxp'] 'dxr' : ['application/x-director'] 'ecelp4800' : ['audio/vnd.nuera.ecelp4800'] 'ecelp7470' : ['audio/vnd.nuera.ecelp7470'] 'ecelp9600' : ['audio/vnd.nuera.ecelp9600'] 'ecma' : ['application/ecmascript'] 'edm' : ['application/vnd.novadigm.edm'] 'edx' : ['application/vnd.novadigm.edx'] 'efif' : ['application/vnd.picsel'] 'ei6' : ['application/vnd.pg.osasli'] 'el' : ['text/x-script.elisp'] 'elc' : ['application/x-bytecode.elisp (compiled elisp)', 'application/x-elc'] 'emf' : ['application/x-msmetafile'] 'eml' : ['message/rfc822'] 'emma' : ['application/emma+xml'] 'emz' : ['application/x-msmetafile'] 'env' : ['application/x-envoy'] 'eol' : ['audio/vnd.digital-winds'] 'eot' : ['application/vnd.ms-fontobject'] 'eps' : ['application/postscript'] 'epub' : ['application/epub+zip'] 'es' : ['application/x-esrehber'] 'es3' : ['application/vnd.eszigno3+xml'] 'esa' : ['application/vnd.osgi.subsystem'] 'esf' : ['application/vnd.epson.esf'] 'et3' : ['application/vnd.eszigno3+xml'] 'etx' : ['text/x-setext'] 'eva' : ['application/x-eva'] 'event-stream' : ['text/event-stream'] 'evy' : ['application/envoy', 'application/x-envoy'] 'exe' : ['application/x-msdownload'] 'exi' : ['application/exi'] 'ext' : ['application/vnd.novadigm.ext'] 'ez' : ['application/andrew-inset'] 'ez2' : ['application/vnd.ezpix-album'] 'ez3' : ['application/vnd.ezpix-package'] 'f' : ['text/plain', 'text/x-fortran'] 'f4v' : ['video/x-f4v'] 'f77' : ['text/x-fortran'] 'f90' : ['text/plain', 'text/x-fortran'] 'fbs' : ['image/vnd.fastbidsheet'] 'fcdt' : ['application/vnd.adobe.formscentral.fcdt'] 'fcs' : ['application/vnd.isac.fcs'] 'fdf' : ['application/vnd.fdf'] 'fe_launch' : ['application/vnd.denovo.fcselayout-link'] 'fg5' : ['application/vnd.fujitsu.oasysgp'] 'fgd' : ['application/x-director'] 'fh' : ['image/x-freehand'] 'fh4' : ['image/x-freehand'] 'fh5' : ['image/x-freehand'] 'fh7' : ['image/x-freehand'] 'fhc' : ['image/x-freehand'] 'fif' : ['application/fractals', 'image/fif'] 'fig' : ['application/x-xfig'] 'flac' : ['audio/flac'] 'fli' : ['video/fli', 'video/x-fli'] 'flo' : ['application/vnd.micrografx.flo'] 'flv' : ['video/x-flv'] 'flw' : ['application/vnd.kde.kivio'] 'flx' : ['text/vnd.fmi.flexstor'] 'fly' : ['text/vnd.fly'] 'fm' : ['application/vnd.framemaker'] 'fmf' : ['video/x-atomic3d-feature'] 'fnc' : ['application/vnd.frogans.fnc'] 'for' : ['text/plain', 'text/x-fortran'] 'fpx' : ['image/vnd.fpx', 'image/vnd.net-fpx'] 'frame' : ['application/vnd.framemaker'] 'frl' : ['application/freeloader'] 'fsc' : ['application/vnd.fsc.weblaunch'] 'fst' : ['image/vnd.fst'] 'ftc' : ['application/vnd.fluxtime.clip'] 'fti' : ['application/vnd.anser-web-funds-transfer-initiation'] 'funk' : ['audio/make'] 'fvt' : ['video/vnd.fvt'] 'fxp' : ['application/vnd.adobe.fxp'] 'fxpl' : ['application/vnd.adobe.fxp'] 'fzs' : ['application/vnd.fuzzysheet'] 'g' : ['text/plain'] 'g2w' : ['application/vnd.geoplan'] 'g3' : ['image/g3fax'] 'g3w' : ['application/vnd.geospace'] 'gac' : ['application/vnd.groove-account'] 'gam' : ['application/x-tads'] 'gbr' : ['application/rpki-ghostbusters'] 'gca' : ['application/x-gca-compressed'] 'gdl' : ['model/vnd.gdl'] 'geo' : ['application/vnd.dynageo'] 'gex' : ['application/vnd.geometry-explorer'] 'ggb' : ['application/vnd.geogebra.file'] 'ggt' : ['application/vnd.geogebra.tool'] 'ghf' : ['application/vnd.groove-help'] 'gif' : ['image/gif'] 'gim' : ['application/vnd.groove-identity-message'] 'gl' : ['video/gl', 'video/x-gl'] 'gml' : ['application/gml+xml'] 'gmx' : ['application/vnd.gmx'] 'gnumeric' : ['application/x-gnumeric'] 'gph' : ['application/vnd.flographit'] 'gpx' : ['application/gpx+xml'] 'gqf' : ['application/vnd.grafeq'] 'gqs' : ['application/vnd.grafeq'] 'gram' : ['application/srgs'] 'gramps' : ['application/x-gramps-xml'] 'gre' : ['application/vnd.geometry-explorer'] 'grv' : ['application/vnd.groove-injector'] 'grxml' : ['application/srgs+xml'] 'gsd' : ['audio/x-gsm'] 'gsf' : ['application/x-font-ghostscript'] 'gsm' : ['audio/x-gsm'] 'gsp' : ['application/x-gsp'] 'gss' : ['application/x-gss'] 'gtar' : ['application/x-gtar'] 'gtm' : ['application/vnd.groove-tool-message'] 'gtw' : ['model/vnd.gtw'] 'gv' : ['text/vnd.graphviz'] 'gxf' : ['application/gxf'] 'gxt' : ['application/vnd.geonext'] 'gz' : ['application/x-compressed', 'application/x-gzip'] 'gzip' : ['application/x-gzip', 'multipart/x-gzip'] 'h' : ['text/plain', 'text/x-h'] 'h261' : ['video/h261'] 'h263' : ['video/h263'] 'h264' : ['video/h264'] 'hal' : ['application/vnd.hal+xml'] 'hbci' : ['application/vnd.hbci'] 'hdf' : ['application/x-hdf'] 'help' : ['application/x-helpfile'] 'hgl' : ['application/vnd.hp-hpgl'] 'hh' : ['text/plain', 'text/x-h'] 'hlb' : ['text/x-script'] 'hlp' : ['application/hlp', 'application/x-helpfile', 'application/x-winhelp'] 'hpg' : ['application/vnd.hp-hpgl'] 'hpgl' : ['application/vnd.hp-hpgl'] 'hpid' : ['application/vnd.hp-hpid'] 'hps' : ['application/vnd.hp-hps'] 'hqx' : ['application/binhex', 'application/binhex4', 'application/mac-binhex', 'application/mac-binhex40', 'application/x-binhex40', 'application/x-mac-binhex40'] 'hta' : ['application/hta'] 'htc' : ['text/x-component'] 'htke' : ['application/vnd.kenameaapp'] 'htm' : ['text/html'] 'html' : ['text/html'] 'htmls' : ['text/html'] 'htt' : ['text/webviewhtml'] 'htx' : ['text/html'] 'hvd' : ['application/vnd.yamaha.hv-dic'] 'hvp' : ['application/vnd.yamaha.hv-voice'] 'hvs' : ['application/vnd.yamaha.hv-script'] 'i2g' : ['application/vnd.intergeo'] 'icc' : ['application/vnd.iccprofile'] 'ice' : ['x-conference/x-cooltalk'] 'icm' : ['application/vnd.iccprofile'] 'ico' : ['image/x-icon'] 'ics' : ['text/calendar'] 'idc' : ['text/plain'] 'ief' : ['image/ief'] 'iefs' : ['image/ief'] 'ifb' : ['text/calendar'] 'ifm' : ['application/vnd.shana.informed.formdata'] 'iges' : ['application/iges', 'model/iges'] 'igl' : ['application/vnd.igloader'] 'igm' : ['application/vnd.insors.igm'] 'igs' : ['application/iges', 'model/iges'] 'igx' : ['application/vnd.micrografx.igx'] 'iif' : ['application/vnd.shana.informed.interchange'] 'ima' : ['application/x-ima'] 'imap' : ['application/x-httpd-imap'] 'imp' : ['application/vnd.accpac.simply.imp'] 'ims' : ['application/vnd.ms-ims'] 'in' : ['text/plain'] 'inf' : ['application/inf'] 'ink' : ['application/inkml+xml'] 'inkml' : ['application/inkml+xml'] 'ins' : ['application/x-internett-signup'] 'install' : ['application/x-install-instructions'] 'iota' : ['application/vnd.astraea-software.iota'] 'ip' : ['application/x-ip2'] 'ipfix' : ['application/ipfix'] 'ipk' : ['application/vnd.shana.informed.package'] 'irm' : ['application/vnd.ibm.rights-management'] 'irp' : ['application/vnd.irepository.package+xml'] 'iso' : ['application/x-iso9660-image'] 'isu' : ['video/x-isvideo'] 'it' : ['audio/it'] 'itp' : ['application/vnd.shana.informed.formtemplate'] 'iv' : ['application/x-inventor'] 'ivp' : ['application/vnd.immervision-ivp'] 'ivr' : ['i-world/i-vrml'] 'ivu' : ['application/vnd.immervision-ivu'] 'ivy' : ['application/x-livescreen'] 'jad' : ['text/vnd.sun.j2me.app-descriptor'] 'jam' : ['application/vnd.jam'] 'jar' : ['application/java-archive'] 'jav' : ['text/plain', 'text/x-java-source'] 'java' : ['text/plain', 'text/x-java-source'] 'jcm' : ['application/x-java-commerce'] 'jfif' : ['image/jpeg', 'image/pjpeg'] 'jfif-tbnl' : ['image/jpeg'] 'jisp' : ['application/vnd.jisp'] 'jlt' : ['application/vnd.hp-jlyt'] 'jnlp' : ['application/x-java-jnlp-file'] 'joda' : ['application/vnd.joost.joda-archive'] 'jpe' : ['image/jpeg', 'image/pjpeg'] 'jpeg' : ['image/jpeg', 'image/pjpeg'] 'jpg' : ['image/jpeg', 'image/pjpeg'] 'jpgm' : ['video/jpm'] 'jpgv' : ['video/jpeg'] 'jpm' : ['video/jpm'] 'jps' : ['image/x-jps'] 'js' : ['application/javascript'] 'json' : ['application/json', 'text/plain'] 'jsonml' : ['application/jsonml+json'] 'jut' : ['image/jutvision'] 'kar' : ['audio/midi', 'music/x-karaoke'] 'karbon' : ['application/vnd.kde.karbon'] 'kfo' : ['application/vnd.kde.kformula'] 'kia' : ['application/vnd.kidspiration'] 'kil' : ['application/x-killustrator'] 'kml' : ['application/vnd.google-earth.kml+xml'] 'kmz' : ['application/vnd.google-earth.kmz'] 'kne' : ['application/vnd.kinar'] 'knp' : ['application/vnd.kinar'] 'kon' : ['application/vnd.kde.kontour'] 'kpr' : ['application/vnd.kde.kpresenter'] 'kpt' : ['application/vnd.kde.kpresenter'] 'kpxx' : ['application/vnd.ds-keypoint'] 'ksh' : ['application/x-ksh', 'text/x-script.ksh'] 'ksp' : ['application/vnd.kde.kspread'] 'ktr' : ['application/vnd.kahootz'] 'ktx' : ['image/ktx'] 'ktz' : ['application/vnd.kahootz'] 'kwd' : ['application/vnd.kde.kword'] 'kwt' : ['application/vnd.kde.kword'] 'la' : ['audio/nspaudio', 'audio/x-nspaudio'] 'lam' : ['audio/x-liveaudio'] 'lasxml' : ['application/vnd.las.las+xml'] 'latex' : ['application/x-latex'] 'lbd' : ['application/vnd.llamagraphics.life-balance.desktop'] 'lbe' : ['application/vnd.llamagraphics.life-balance.exchange+xml'] 'les' : ['application/vnd.hhe.lesson-player'] 'lha' : ['application/lha', 'application/octet-stream', 'application/x-lha'] 'lhx' : ['application/octet-stream'] 'link66' : ['application/vnd.route66.link66+xml'] 'list' : ['text/plain'] 'list3820' : ['application/vnd.ibm.modcap'] 'listafp' : ['application/vnd.ibm.modcap'] 'lma' : ['audio/nspaudio', 'audio/x-nspaudio'] 'lnk' : ['application/x-ms-shortcut'] 'log' : ['text/plain'] 'lostxml' : ['application/lost+xml'] 'lrf' : ['application/octet-stream'] 'lrm' : ['application/vnd.ms-lrm'] 'lsp' : ['application/x-lisp', 'text/x-script.lisp'] 'lst' : ['text/plain'] 'lsx' : ['text/x-la-asf'] 'ltf' : ['application/vnd.frogans.ltf'] 'ltx' : ['application/x-latex'] 'lua' : ['text/x-lua'] 'luac' : ['application/x-lua-bytecode'] 'lvp' : ['audio/vnd.lucent.voice'] 'lwp' : ['application/vnd.lotus-wordpro'] 'lzh' : ['application/octet-stream', 'application/x-lzh'] 'lzx' : ['application/lzx', 'application/octet-stream', 'application/x-lzx'] 'm' : ['text/plain', 'text/x-m'] 'm13' : ['application/x-msmediaview'] 'm14' : ['application/x-msmediaview'] 'm1v' : ['video/mpeg'] 'm21' : ['application/mp21'] 'm2a' : ['audio/mpeg'] 'm2v' : ['video/mpeg'] 'm3a' : ['audio/mpeg'] 'm3u' : ['audio/x-mpegurl'] 'm3u8' : ['application/x-mpegURL'] 'm4a' : ['audio/mp4'] 'm4p' : ['application/mp4'] 'm4u' : ['video/vnd.mpegurl'] 'm4v' : ['video/x-m4v'] 'ma' : ['application/mathematica'] 'mads' : ['application/mads+xml'] 'mag' : ['application/vnd.ecowin.chart'] 'maker' : ['application/vnd.framemaker'] 'man' : ['text/troff'] 'manifest' : ['text/cache-manifest'] 'map' : ['application/x-navimap'] 'mar' : ['application/octet-stream'] 'markdown' : ['text/x-markdown'] 'mathml' : ['application/mathml+xml'] 'mb' : ['application/mathematica'] 'mbd' : ['application/mbedlet'] 'mbk' : ['application/vnd.mobius.mbk'] 'mbox' : ['application/mbox'] 'mc' : ['application/x-magic-cap-package-1.0'] 'mc1' : ['application/vnd.medcalcdata'] 'mcd' : ['application/mcad', 'application/x-mathcad'] 'mcf' : ['image/vasa', 'text/mcf'] 'mcp' : ['application/netmc'] 'mcurl' : ['text/vnd.curl.mcurl'] 'md' : ['text/x-markdown'] 'mdb' : ['application/x-msaccess'] 'mdi' : ['image/vnd.ms-modi'] 'me' : ['text/troff'] 'mesh' : ['model/mesh'] 'meta4' : ['application/metalink4+xml'] 'metalink' : ['application/metalink+xml'] 'mets' : ['application/mets+xml'] 'mfm' : ['application/vnd.mfmp'] 'mft' : ['application/rpki-manifest'] 'mgp' : ['application/vnd.osgeo.mapguide.package'] 'mgz' : ['application/vnd.proteus.magazine'] 'mht' : ['message/rfc822'] 'mhtml' : ['message/rfc822'] 'mid' : ['application/x-midi', 'audio/midi', 'audio/x-mid', 'audio/x-midi', 'music/crescendo', 'x-music/x-midi'] 'midi' : ['application/x-midi', 'audio/midi', 'audio/x-mid', 'audio/x-midi', 'music/crescendo', 'x-music/x-midi'] 'mie' : ['application/x-mie'] 'mif' : ['application/x-frame', 'application/x-mif'] 'mime' : ['message/rfc822', 'www/mime'] 'mj2' : ['video/mj2'] 'mjf' : ['audio/x-vnd.audioexplosion.mjuicemediafile'] 'mjp2' : ['video/mj2'] 'mjpg' : ['video/x-motion-jpeg'] 'mk3d' : ['video/x-matroska'] 'mka' : ['audio/x-matroska'] 'mkd' : ['text/x-markdown'] 'mks' : ['video/x-matroska'] 'mkv' : ['video/x-matroska'] 'mlp' : ['application/vnd.dolby.mlp'] 'mm' : ['application/base64', 'application/x-meme'] 'mmd' : ['application/vnd.chipnuts.karaoke-mmd'] 'mme' : ['application/base64'] 'mmf' : ['application/vnd.smaf'] 'mmr' : ['image/vnd.fujixerox.edmics-mmr'] 'mng' : ['video/x-mng'] 'mny' : ['application/x-msmoney'] 'mobi' : ['application/x-mobipocket-ebook'] 'mod' : ['audio/mod', 'audio/x-mod'] 'mods' : ['application/mods+xml'] 'moov' : ['video/quicktime'] 'mov' : ['video/quicktime'] 'movie' : ['video/x-sgi-movie'] 'mp2' : ['audio/mpeg', 'audio/x-mpeg', 'video/mpeg', 'video/x-mpeg', 'video/x-mpeq2a'] 'mp21' : ['application/mp21'] 'mp2a' : ['audio/mpeg'] 'mp3' : ['audio/mpeg3', 'audio/x-mpeg-3', 'video/mpeg', 'video/x-mpeg'] 'mp4' : ['video/mp4'] 'mp4a' : ['audio/mp4'] 'mp4s' : ['application/mp4'] 'mp4v' : ['video/mp4'] 'mpa' : ['audio/mpeg', 'video/mpeg'] 'mpc' : ['application/vnd.mophun.certificate'] 'mpe' : ['video/mpeg'] 'mpeg' : ['video/mpeg'] 'mpg' : ['audio/mpeg', 'video/mpeg'] 'mpg4' : ['video/mp4'] 'mpga' : ['audio/mpeg'] 'mpkg' : ['application/vnd.apple.installer+xml'] 'mpm' : ['application/vnd.blueice.multipass'] 'mpn' : ['application/vnd.mophun.application'] 'mpp' : ['application/vnd.ms-project'] 'mpt' : ['application/vnd.ms-project'] 'mpv' : ['application/x-project'] 'mpx' : ['application/x-project'] 'mpy' : ['application/vnd.ibm.minipay'] 'mqy' : ['application/vnd.mobius.mqy'] 'mrc' : ['application/marc'] 'mrcx' : ['application/marcxml+xml'] 'ms' : ['text/troff'] 'mscml' : ['application/mediaservercontrol+xml'] 'mseed' : ['application/vnd.fdsn.mseed'] 'mseq' : ['application/vnd.mseq'] 'msf' : ['application/vnd.epson.msf'] 'msh' : ['model/mesh'] 'msi' : ['application/x-msdownload'] 'msl' : ['application/vnd.mobius.msl'] 'msty' : ['application/vnd.muvee.style'] 'mts' : ['model/vnd.mts'] 'mus' : ['application/vnd.musician'] 'musicxml' : ['application/vnd.recordare.musicxml+xml'] 'mv' : ['video/x-sgi-movie'] 'mvb' : ['application/x-msmediaview'] 'mwf' : ['application/vnd.mfer'] 'mxf' : ['application/mxf'] 'mxl' : ['application/vnd.recordare.musicxml'] 'mxml' : ['application/xv+xml'] 'mxs' : ['application/vnd.triscape.mxs'] 'mxu' : ['video/vnd.mpegurl'] 'my' : ['audio/make'] 'mzz' : ['application/x-vnd.audioexplosion.mzz'] 'n-gage' : ['application/vnd.nokia.n-gage.symbian.install'] 'n3' : ['text/n3'] 'nap' : ['image/naplps'] 'naplps' : ['image/naplps'] 'nb' : ['application/mathematica'] 'nbp' : ['application/vnd.wolfram.player'] 'nc' : ['application/x-netcdf'] 'ncm' : ['application/vnd.nokia.configuration-message'] 'ncx' : ['application/x-dtbncx+xml'] 'nfo' : ['text/x-nfo'] 'ngdat' : ['application/vnd.nokia.n-gage.data'] 'nif' : ['image/x-niff'] 'niff' : ['image/x-niff'] 'nitf' : ['application/vnd.nitf'] 'nix' : ['application/x-mix-transfer'] 'nlu' : ['application/vnd.neurolanguage.nlu'] 'nml' : ['application/vnd.enliven'] 'nnd' : ['application/vnd.noblenet-directory'] 'nns' : ['application/vnd.noblenet-sealer'] 'nnw' : ['application/vnd.noblenet-web'] 'npx' : ['image/vnd.net-fpx'] 'nsc' : ['application/x-conference'] 'nsf' : ['application/vnd.lotus-notes'] 'ntf' : ['application/vnd.nitf'] 'nvd' : ['application/x-navidoc'] 'nws' : ['message/rfc822'] 'nzb' : ['application/x-nzb'] 'o' : ['application/octet-stream'] 'oa2' : ['application/vnd.fujitsu.oasys2'] 'oa3' : ['application/vnd.fujitsu.oasys3'] 'oas' : ['application/vnd.fujitsu.oasys'] 'obd' : ['application/x-msbinder'] 'obj' : ['application/x-tgif'] 'oda' : ['application/oda'] 'odb' : ['application/vnd.oasis.opendocument.database'] 'odc' : ['application/vnd.oasis.opendocument.chart'] 'odf' : ['application/vnd.oasis.opendocument.formula'] 'odft' : ['application/vnd.oasis.opendocument.formula-template'] 'odg' : ['application/vnd.oasis.opendocument.graphics'] 'odi' : ['application/vnd.oasis.opendocument.image'] 'odm' : ['application/vnd.oasis.opendocument.text-master'] 'odp' : ['application/vnd.oasis.opendocument.presentation'] 'ods' : ['application/vnd.oasis.opendocument.spreadsheet'] 'odt' : ['application/vnd.oasis.opendocument.text'] 'oga' : ['audio/ogg'] 'ogg' : ['audio/ogg'] 'ogv' : ['video/ogg'] 'ogx' : ['application/ogg'] 'omc' : ['application/x-omc'] 'omcd' : ['application/x-omcdatamaker'] 'omcr' : ['application/x-omcregerator'] 'omdoc' : ['application/omdoc+xml'] 'onepkg' : ['application/onenote'] 'onetmp' : ['application/onenote'] 'onetoc' : ['application/onenote'] 'onetoc2' : ['application/onenote'] 'opf' : ['application/oebps-package+xml'] 'opml' : ['text/x-opml'] 'oprc' : ['application/vnd.palm'] 'org' : ['application/vnd.lotus-organizer'] 'osf' : ['application/vnd.yamaha.openscoreformat'] 'osfpvg' : ['application/vnd.yamaha.openscoreformat.osfpvg+xml'] 'otc' : ['application/vnd.oasis.opendocument.chart-template'] 'otf' : ['font/opentype'] 'otg' : ['application/vnd.oasis.opendocument.graphics-template'] 'oth' : ['application/vnd.oasis.opendocument.text-web'] 'oti' : ['application/vnd.oasis.opendocument.image-template'] 'otm' : ['application/vnd.oasis.opendocument.text-master'] 'otp' : ['application/vnd.oasis.opendocument.presentation-template'] 'ots' : ['application/vnd.oasis.opendocument.spreadsheet-template'] 'ott' : ['application/vnd.oasis.opendocument.text-template'] 'oxps' : ['application/oxps'] 'oxt' : ['application/vnd.openofficeorg.extension'] 'p' : ['text/x-pascal'] 'p10' : ['application/pkcs10', 'application/x-pkcs10'] 'p12' : ['application/pkcs-12', 'application/x-pkcs12'] 'p7a' : ['application/x-pkcs7-signature'] 'p7b' : ['application/x-pkcs7-certificates'] 'p7c' : ['application/pkcs7-mime', 'application/x-pkcs7-mime'] 'p7m' : ['application/pkcs7-mime', 'application/x-pkcs7-mime'] 'p7r' : ['application/x-pkcs7-certreqresp'] 'p7s' : ['application/pkcs7-signature'] 'p8' : ['application/pkcs8'] 'part' : ['application/pro_eng'] 'pas' : ['text/x-pascal'] 'paw' : ['application/vnd.pawaafile'] 'pbd' : ['application/vnd.powerbuilder6'] 'pbm' : ['image/x-portable-bitmap'] 'pcap' : ['application/vnd.tcpdump.pcap'] 'pcf' : ['application/x-font-pcf'] 'pcl' : ['application/vnd.hp-pcl', 'application/x-pcl'] 'pclxl' : ['application/vnd.hp-pclxl'] 'pct' : ['image/x-pict'] 'pcurl' : ['application/vnd.curl.pcurl'] 'pcx' : ['image/x-pcx'] 'pdb' : ['application/vnd.palm'] 'pdf' : ['application/pdf'] 'pfa' : ['application/x-font-type1'] 'pfb' : ['application/x-font-type1'] 'pfm' : ['application/x-font-type1'] 'pfr' : ['application/font-tdpfr'] 'pfunk' : ['audio/make'] 'pfx' : ['application/x-pkcs12'] 'pgm' : ['image/x-portable-graymap'] 'pgn' : ['application/x-chess-pgn'] 'pgp' : ['application/pgp-encrypted'] 'php' : ['text/x-php'] 'pic' : ['image/x-pict'] 'pict' : ['image/pict'] 'pkg' : ['application/octet-stream'] 'pki' : ['application/pkixcmp'] 'pkipath' : ['application/pkix-pkipath'] 'pko' : ['application/vnd.ms-pki.pko'] 'pl' : ['text/plain', 'text/x-script.perl'] 'plb' : ['application/vnd.3gpp.pic-bw-large'] 'plc' : ['application/vnd.mobius.plc'] 'plf' : ['application/vnd.pocketlearn'] 'pls' : ['application/pls+xml'] 'plx' : ['application/x-pixclscript'] 'pm' : ['image/x-xpixmap', 'text/x-script.perl-module'] 'pm4' : ['application/x-pagemaker'] 'pm5' : ['application/x-pagemaker'] 'pml' : ['application/vnd.ctc-posml'] 'png' : ['image/png'] 'pnm' : ['application/x-portable-anymap', 'image/x-portable-anymap'] 'portpkg' : ['application/vnd.macports.portpkg'] 'pot' : ['application/mspowerpoint', 'application/vnd.ms-powerpoint'] 'potm' : ['application/vnd.ms-powerpoint.template.macroenabled.12'] 'potx' : ['application/vnd.openxmlformats-officedocument.presentationml.template'] 'pov' : ['model/x-pov'] 'ppa' : ['application/vnd.ms-powerpoint'] 'ppam' : ['application/vnd.ms-powerpoint.addin.macroenabled.12'] 'ppd' : ['application/vnd.cups-ppd'] 'ppm' : ['image/x-portable-pixmap'] 'pps' : ['application/mspowerpoint', 'application/vnd.ms-powerpoint'] 'ppsm' : ['application/vnd.ms-powerpoint.slideshow.macroenabled.12'] 'ppsx' : ['application/vnd.openxmlformats-officedocument.presentationml.slideshow'] 'ppt' : ['application/mspowerpoint', 'application/powerpoint', 'application/vnd.ms-powerpoint', 'application/x-mspowerpoint'] 'pptm' : ['application/vnd.ms-powerpoint.presentation.macroenabled.12'] 'pptx' : ['application/vnd.openxmlformats-officedocument.presentationml.presentation'] 'ppz' : ['application/mspowerpoint'] 'pqa' : ['application/vnd.palm'] 'prc' : ['application/x-mobipocket-ebook'] 'pre' : ['application/vnd.lotus-freelance'] 'prf' : ['application/pics-rules'] 'prt' : ['application/pro_eng'] 'ps' : ['application/postscript'] 'psb' : ['application/vnd.3gpp.pic-bw-small'] 'psd' : ['image/vnd.adobe.photoshop'] 'psf' : ['application/x-font-linux-psf'] 'pskcxml' : ['application/pskc+xml'] 'ptid' : ['application/vnd.pvi.ptid1'] 'pub' : ['application/x-mspublisher'] 'pvb' : ['application/vnd.3gpp.pic-bw-var'] 'pvu' : ['paleovu/x-pv'] 'pwn' : ['application/vnd.3m.post-it-notes'] 'pwz' : ['application/vnd.ms-powerpoint'] 'py' : ['text/x-script.phyton'] 'pya' : ['audio/vnd.ms-playready.media.pya'] 'pyc' : ['applicaiton/x-bytecode.python'] 'pyo' : ['application/x-python-code'] 'pyv' : ['video/vnd.ms-playready.media.pyv'] 'qam' : ['application/vnd.epson.quickanime'] 'qbo' : ['application/vnd.intu.qbo'] 'qcp' : ['audio/vnd.qcelp'] 'qd3' : ['x-world/x-3dmf'] 'qd3d' : ['x-world/x-3dmf'] 'qfx' : ['application/vnd.intu.qfx'] 'qif' : ['image/x-quicktime'] 'qps' : ['application/vnd.publishare-delta-tree'] 'qt' : ['video/quicktime'] 'qtc' : ['video/x-qtc'] 'qti' : ['image/x-quicktime'] 'qtif' : ['image/x-quicktime'] 'qwd' : ['application/vnd.quark.quarkxpress'] 'qwt' : ['application/vnd.quark.quarkxpress'] 'qxb' : ['application/vnd.quark.quarkxpress'] 'qxd' : ['application/vnd.quark.quarkxpress'] 'qxl' : ['application/vnd.quark.quarkxpress'] 'qxt' : ['application/vnd.quark.quarkxpress'] 'ra' : ['audio/x-pn-realaudio', 'audio/x-pn-realaudio-plugin', 'audio/x-realaudio'] 'ram' : ['audio/x-pn-realaudio'] 'rar' : ['application/x-rar-compressed'] 'ras' : ['application/x-cmu-raster', 'image/cmu-raster', 'image/x-cmu-raster'] 'rast' : ['image/cmu-raster'] 'rcprofile' : ['application/vnd.ipunplugged.rcprofile'] 'rdf' : ['application/rdf+xml'] 'rdz' : ['application/vnd.data-vision.rdz'] 'rep' : ['application/vnd.businessobjects'] 'res' : ['application/x-dtbresource+xml'] 'rexx' : ['text/x-script.rexx'] 'rf' : ['image/vnd.rn-realflash'] 'rgb' : ['image/x-rgb'] 'rif' : ['application/reginfo+xml'] 'rip' : ['audio/vnd.rip'] 'ris' : ['application/x-research-info-systems'] 'rl' : ['application/resource-lists+xml'] 'rlc' : ['image/vnd.fujixerox.edmics-rlc'] 'rld' : ['application/resource-lists-diff+xml'] 'rm' : ['application/vnd.rn-realmedia', 'audio/x-pn-realaudio'] 'rmi' : ['audio/midi'] 'rmm' : ['audio/x-pn-realaudio'] 'rmp' : ['audio/x-pn-realaudio', 'audio/x-pn-realaudio-plugin'] 'rms' : ['application/vnd.jcp.javame.midlet-rms'] 'rmvb' : ['application/vnd.rn-realmedia-vbr'] 'rnc' : ['application/relax-ng-compact-syntax'] 'rng' : ['application/ringing-tones', 'application/vnd.nokia.ringing-tone'] 'rnx' : ['application/vnd.rn-realplayer'] 'roa' : ['application/rpki-roa'] 'roff' : ['text/troff'] 'rp' : ['image/vnd.rn-realpix'] 'rp9' : ['application/vnd.cloanto.rp9'] 'rpm' : ['audio/x-pn-realaudio-plugin'] 'rpss' : ['application/vnd.nokia.radio-presets'] 'rpst' : ['application/vnd.nokia.radio-preset'] 'rq' : ['application/sparql-query'] 'rs' : ['application/rls-services+xml'] 'rsd' : ['application/rsd+xml'] 'rss' : ['application/rss+xml'] 'rt' : ['text/richtext', 'text/vnd.rn-realtext'] 'rtf' : ['application/rtf', 'application/x-rtf', 'text/richtext'] 'rtx' : ['application/rtf', 'text/richtext'] 'rv' : ['video/vnd.rn-realvideo'] 's' : ['text/x-asm'] 's3m' : ['audio/s3m'] 'saf' : ['application/vnd.yamaha.smaf-audio'] 'saveme' : ['aapplication/octet-stream'] 'sbk' : ['application/x-tbook'] 'sbml' : ['application/sbml+xml'] 'sc' : ['application/vnd.ibm.secure-container'] 'scd' : ['application/x-msschedule'] 'scm' : ['application/x-lotusscreencam', 'text/x-script.guile', 'text/x-script.scheme', 'video/x-scm'] 'scq' : ['application/scvp-cv-item'] 'scs' : ['application/scvp-cv-response'] 'scurl' : ['text/vnd.curl.scurl'] 'sda' : ['application/vnd.stardivision.draw'] 'sdc' : ['application/vnd.stardivision.calc'] 'sdd' : ['application/vnd.stardivision.impress'] 'sdkd' : ['application/vnd.solent.sdkm+xml'] 'sdkm' : ['application/vnd.solent.sdkm+xml'] 'sdml' : ['text/plain'] 'sdp' : ['application/sdp', 'application/x-sdp'] 'sdr' : ['application/sounder'] 'sdw' : ['application/vnd.stardivision.writer'] 'sea' : ['application/sea', 'application/x-sea'] 'see' : ['application/vnd.seemail'] 'seed' : ['application/vnd.fdsn.seed'] 'sema' : ['application/vnd.sema'] 'semd' : ['application/vnd.semd'] 'semf' : ['application/vnd.semf'] 'ser' : ['application/java-serialized-object'] 'set' : ['application/set'] 'setpay' : ['application/set-payment-initiation'] 'setreg' : ['application/set-registration-initiation'] 'sfd-hdstx' : ['application/vnd.hydrostatix.sof-data'] 'sfs' : ['application/vnd.spotfire.sfs'] 'sfv' : ['text/x-sfv'] 'sgi' : ['image/sgi'] 'sgl' : ['application/vnd.stardivision.writer-global'] 'sgm' : ['text/sgml', 'text/x-sgml'] 'sgml' : ['text/sgml', 'text/x-sgml'] 'sh' : ['application/x-bsh', 'application/x-sh', 'application/x-shar', 'text/x-script.sh'] 'shar' : ['application/x-bsh', 'application/x-shar'] 'shf' : ['application/shf+xml'] 'shtml' : ['text/html', 'text/x-server-parsed-html'] 'si' : ['text/vnd.wap.si'] 'sic' : ['application/vnd.wap.sic'] 'sid' : ['image/x-mrsid-image'] 'sig' : ['application/pgp-signature'] 'sil' : ['audio/silk'] 'silo' : ['model/mesh'] 'sis' : ['application/vnd.symbian.install'] 'sisx' : ['application/vnd.symbian.install'] 'sit' : ['application/x-sit', 'application/x-stuffit'] 'sitx' : ['application/x-stuffitx'] 'skd' : ['application/vnd.koan'] 'skm' : ['application/vnd.koan'] 'skp' : ['application/vnd.koan'] 'skt' : ['application/vnd.koan'] 'sl' : ['application/x-seelogo'] 'slc' : ['application/vnd.wap.slc'] 'sldm' : ['application/vnd.ms-powerpoint.slide.macroenabled.12'] 'sldx' : ['application/vnd.openxmlformats-officedocument.presentationml.slide'] 'slt' : ['application/vnd.epson.salt'] 'sm' : ['application/vnd.stepmania.stepchart'] 'smf' : ['application/vnd.stardivision.math'] 'smi' : ['application/smil+xml'] 'smil' : ['application/smil+xml'] 'smv' : ['video/x-smv'] 'smzip' : ['application/vnd.stepmania.package'] 'snd' : ['audio/basic', 'audio/x-adpcm'] 'snf' : ['application/x-font-snf'] 'so' : ['application/octet-stream'] 'sol' : ['application/solids'] 'spc' : ['application/x-pkcs7-certificates', 'text/x-speech'] 'spf' : ['application/vnd.yamaha.smaf-phrase'] 'spl' : ['application/x-futuresplash'] 'spot' : ['text/vnd.in3d.spot'] 'spp' : ['application/scvp-vp-response'] 'spq' : ['application/scvp-vp-item'] 'spr' : ['application/x-sprite'] 'sprite' : ['application/x-sprite'] 'spx' : ['audio/ogg'] 'sql' : ['application/x-sql'] 'src' : ['application/x-wais-source'] 'srt' : ['application/x-subrip'] 'sru' : ['application/sru+xml'] 'srx' : ['application/sparql-results+xml'] 'ssdl' : ['application/ssdl+xml'] 'sse' : ['application/vnd.kodak-descriptor'] 'ssf' : ['application/vnd.epson.ssf'] 'ssi' : ['text/x-server-parsed-html'] 'ssm' : ['application/streamingmedia'] 'ssml' : ['application/ssml+xml'] 'sst' : ['application/vnd.ms-pki.certstore'] 'st' : ['application/vnd.sailingtracker.track'] 'stc' : ['application/vnd.sun.xml.calc.template'] 'std' : ['application/vnd.sun.xml.draw.template'] 'step' : ['application/step'] 'stf' : ['application/vnd.wt.stf'] 'sti' : ['application/vnd.sun.xml.impress.template'] 'stk' : ['application/hyperstudio'] 'stl' : ['application/sla', 'application/vnd.ms-pki.stl', 'application/x-navistyle'] 'stp' : ['application/step'] 'str' : ['application/vnd.pg.format'] 'stw' : ['application/vnd.sun.xml.writer.template'] 'sub' : ['text/vnd.dvb.subtitle'] 'sus' : ['application/vnd.sus-calendar'] 'susp' : ['application/vnd.sus-calendar'] 'sv4cpio' : ['application/x-sv4cpio'] 'sv4crc' : ['application/x-sv4crc'] 'svc' : ['application/vnd.dvb.service'] 'svd' : ['application/vnd.svd'] 'svf' : ['image/vnd.dwg', 'image/x-dwg'] 'svg' : ['image/svg+xml'] 'svgz' : ['image/svg+xml'] 'svr' : ['application/x-world', 'x-world/x-svr'] 'swa' : ['application/x-director'] 'swf' : ['application/x-shockwave-flash'] 'swi' : ['application/vnd.aristanetworks.swi'] 'sxc' : ['application/vnd.sun.xml.calc'] 'sxd' : ['application/vnd.sun.xml.draw'] 'sxg' : ['application/vnd.sun.xml.writer.global'] 'sxi' : ['application/vnd.sun.xml.impress'] 'sxm' : ['application/vnd.sun.xml.math'] 'sxw' : ['application/vnd.sun.xml.writer'] 't' : ['text/troff'] 't3' : ['application/x-t3vm-image'] 'taglet' : ['application/vnd.mynfc'] 'talk' : ['text/x-speech'] 'tao' : ['application/vnd.tao.intent-module-archive'] 'tar' : ['application/x-tar'] 'tbk' : ['application/toolbook', 'application/x-tbook'] 'tcap' : ['application/vnd.3gpp2.tcap'] 'tcl' : ['application/x-tcl', 'text/x-script.tcl'] 'tcsh' : ['text/x-script.tcsh'] 'teacher' : ['application/vnd.smart.teacher'] 'tei' : ['application/tei+xml'] 'teicorpus' : ['application/tei+xml'] 'tex' : ['application/x-tex'] 'texi' : ['application/x-texinfo'] 'texinfo' : ['application/x-texinfo'] 'text' : ['application/plain', 'text/plain'] 'tfi' : ['application/thraud+xml'] 'tfm' : ['application/x-tex-tfm'] 'tga' : ['image/x-tga'] 'tgz' : ['application/gnutar', 'application/x-compressed'] 'thmx' : ['application/vnd.ms-officetheme'] 'tif' : ['image/tiff', 'image/x-tiff'] 'tiff' : ['image/tiff', 'image/x-tiff'] 'tmo' : ['application/vnd.tmobile-livetv'] 'torrent' : ['application/x-bittorrent'] 'tpl' : ['application/vnd.groove-tool-template'] 'tpt' : ['application/vnd.trid.tpt'] 'tr' : ['text/troff'] 'tra' : ['application/vnd.trueapp'] 'trm' : ['application/x-msterminal'] 'ts' : ['video/MP2T'] 'tsd' : ['application/timestamped-data'] 'tsi' : ['audio/tsp-audio'] 'tsp' : ['application/dsptype', 'audio/tsplayer'] 'tsv' : ['text/tab-separated-values'] 'ttc' : ['application/x-font-ttf'] 'ttf' : ['application/x-font-ttf'] 'ttl' : ['text/turtle'] 'turbot' : ['image/<NAME>'] 'twd' : ['application/vnd.simtech-mindmapper'] 'twds' : ['application/vnd.simtech-mindmapper'] 'txd' : ['application/vnd.genomatix.tuxedo'] 'txf' : ['application/vnd.mobius.txf'] 'txt' : ['text/plain'] 'u32' : ['application/x-authorware-bin'] 'udeb' : ['application/x-debian-package'] 'ufd' : ['application/vnd.ufdl'] 'ufdl' : ['application/vnd.ufdl'] 'uil' : ['text/x-uil'] 'ulx' : ['application/x-glulx'] 'umj' : ['application/vnd.umajin'] 'uni' : ['text/uri-list'] 'unis' : ['text/uri-list'] 'unityweb' : ['application/vnd.unity'] 'unv' : ['application/i-deas'] 'uoml' : ['application/vnd.uoml+xml'] 'uri' : ['text/uri-list'] 'uris' : ['text/uri-list'] 'urls' : ['text/uri-list'] 'ustar' : ['application/x-ustar', 'multipart/x-ustar'] 'utz' : ['application/vnd.uiq.theme'] 'uu' : ['application/octet-stream', 'text/x-uuencode'] 'uue' : ['text/x-uuencode'] 'uva' : ['audio/vnd.dece.audio'] 'uvd' : ['application/vnd.dece.data'] 'uvf' : ['application/vnd.dece.data'] 'uvg' : ['image/vnd.dece.graphic'] 'uvh' : ['video/vnd.dece.hd'] 'uvi' : ['image/vnd.dece.graphic'] 'uvm' : ['video/vnd.dece.mobile'] 'uvp' : ['video/vnd.dece.pd'] 'uvs' : ['video/vnd.dece.sd'] 'uvt' : ['application/vnd.dece.ttml+xml'] 'uvu' : ['video/vnd.uvvu.mp4'] 'uvv' : ['video/vnd.dece.video'] 'uvva' : ['audio/vnd.dece.audio'] 'uvvd' : ['application/vnd.dece.data'] 'uvvf' : ['application/vnd.dece.data'] 'uvvg' : ['image/vnd.dece.graphic'] 'uvvh' : ['video/vnd.dece.hd'] 'uvvi' : ['image/vnd.dece.graphic'] 'uvvm' : ['video/vnd.dece.mobile'] 'uvvp' : ['video/vnd.dece.pd'] 'uvvs' : ['video/vnd.dece.sd'] 'uvvt' : ['application/vnd.dece.ttml+xml'] 'uvvu' : ['video/vnd.uvvu.mp4'] 'uvvv' : ['video/vnd.dece.video'] 'uvvx' : ['application/vnd.dece.unspecified'] 'uvvz' : ['application/vnd.dece.zip'] 'uvx' : ['application/vnd.dece.unspecified'] 'uvz' : ['application/vnd.dece.zip'] 'vcard' : ['text/vcard'] 'vcd' : ['application/x-cdlink'] 'vcf' : ['text/x-vcard'] 'vcg' : ['application/vnd.groove-vcard'] 'vcs' : ['text/x-vcalendar'] 'vcx' : ['application/vnd.vcx'] 'vda' : ['application/vda'] 'vdo' : ['video/vdo'] 'vew' : ['application/groupwise'] 'vis' : ['application/vnd.visionary'] 'viv' : ['video/vivo', 'video/vnd.vivo'] 'vivo' : ['video/vivo', 'video/vnd.vivo'] 'vmd' : ['application/vocaltec-media-desc'] 'vmf' : ['application/vocaltec-media-file'] 'vob' : ['video/x-ms-vob'] 'voc' : ['audio/voc', 'audio/x-voc'] 'vor' : ['application/vnd.stardivision.writer'] 'vos' : ['video/vosaic'] 'vox' : ['application/x-authorware-bin'] 'vqe' : ['audio/x-twinvq-plugin'] 'vqf' : ['audio/x-twinvq'] 'vql' : ['audio/x-twinvq-plugin'] 'vrml' : ['application/x-vrml', 'model/vrml', 'x-world/x-vrml'] 'vrt' : ['x-world/x-vrt'] 'vsd' : ['application/vnd.visio'] 'vsf' : ['application/vnd.vsf'] 'vss' : ['application/vnd.visio'] 'vst' : ['application/vnd.visio'] 'vsw' : ['application/vnd.visio'] 'vtt' : ['text/vtt'] 'vtu' : ['model/vnd.vtu'] 'vxml' : ['application/voicexml+xml'] 'w3d' : ['application/x-director'] 'w60' : ['application/wordperfect6.0'] 'w61' : ['application/wordperfect6.1'] 'w6w' : ['application/msword'] 'wad' : ['application/x-doom'] 'wav' : ['audio/wav', 'audio/x-wav'] 'wax' : ['audio/x-ms-wax'] 'wb1' : ['application/x-qpro'] 'wbmp' : ['image/vnd.wap.wbmp'] 'wbs' : ['application/vnd.criticaltools.wbs+xml'] 'wbxml' : ['application/vnd.wap.wbxml'] 'wcm' : ['application/vnd.ms-works'] 'wdb' : ['application/vnd.ms-works'] 'wdp' : ['image/vnd.ms-photo'] 'web' : ['application/vnd.xara'] 'weba' : ['audio/webm'] 'webapp' : ['application/x-web-app-manifest+json'] 'webm' : ['video/webm'] 'webp' : ['image/webp'] 'wg' : ['application/vnd.pmi.widget'] 'wgt' : ['application/widget'] 'wiz' : ['application/msword'] 'wk1' : ['application/x-123'] 'wks' : ['application/vnd.ms-works'] 'wm' : ['video/x-ms-wm'] 'wma' : ['audio/x-ms-wma'] 'wmd' : ['application/x-ms-wmd'] 'wmf' : ['application/x-msmetafile'] 'wml' : ['text/vnd.wap.wml'] 'wmlc' : ['application/vnd.wap.wmlc'] 'wmls' : ['text/vnd.wap.wmlscript'] 'wmlsc' : ['application/vnd.wap.wmlscriptc'] 'wmv' : ['video/x-ms-wmv'] 'wmx' : ['video/x-ms-wmx'] 'wmz' : ['application/x-msmetafile'] 'woff' : ['application/x-font-woff'] 'word' : ['application/msword'] 'wp' : ['application/wordperfect'] 'wp5' : ['application/wordperfect', 'application/wordperfect6.0'] 'wp6' : ['application/wordperfect'] 'wpd' : ['application/wordperfect', 'application/x-wpwin'] 'wpl' : ['application/vnd.ms-wpl'] 'wps' : ['application/vnd.ms-works'] 'wq1' : ['application/x-lotus'] 'wqd' : ['application/vnd.wqd'] 'wri' : ['application/mswrite', 'application/x-wri'] 'wrl' : ['application/x-world', 'model/vrml', 'x-world/x-vrml'] 'wrz' : ['model/vrml', 'x-world/x-vrml'] 'wsc' : ['text/scriplet'] 'wsdl' : ['application/wsdl+xml'] 'wspolicy' : ['application/wspolicy+xml'] 'wsrc' : ['application/x-wais-source'] 'wtb' : ['application/vnd.webturbo'] 'wtk' : ['application/x-wintalk'] 'wvx' : ['video/x-ms-wvx'] 'x-png' : ['image/png'] 'x32' : ['application/x-authorware-bin'] 'x3d' : ['model/x3d+xml'] 'x3db' : ['model/x3d+binary'] 'x3dbz' : ['model/x3d+binary'] 'x3dv' : ['model/x3d+vrml'] 'x3dvz' : ['model/x3d+vrml'] 'x3dz' : ['model/x3d+xml'] 'xaml' : ['application/xaml+xml'] 'xap' : ['application/x-silverlight-app'] 'xar' : ['application/vnd.xara'] 'xbap' : ['application/x-ms-xbap'] 'xbd' : ['application/vnd.fujixerox.docuworks.binder'] 'xbm' : ['image/x-xbitmap', 'image/x-xbm', 'image/xbm'] 'xdf' : ['application/xcap-diff+xml'] 'xdm' : ['application/vnd.syncml.dm+xml'] 'xdp' : ['application/vnd.adobe.xdp+xml'] 'xdr' : ['video/x-amt-demorun'] 'xdssc' : ['application/dssc+xml'] 'xdw' : ['application/vnd.fujixerox.docuworks'] 'xenc' : ['application/xenc+xml'] 'xer' : ['application/patch-ops-error+xml'] 'xfdf' : ['application/vnd.adobe.xfdf'] 'xfdl' : ['application/vnd.xfdl'] 'xgz' : ['xgl/drawing'] 'xht' : ['application/xhtml+xml'] 'xhtml' : ['application/xhtml+xml'] 'xhvml' : ['application/xv+xml'] 'xif' : ['image/vnd.xiff'] 'xl' : ['application/excel'] 'xla' : ['application/excel', 'application/x-excel', 'application/x-msexcel'] 'xlam' : ['application/vnd.ms-excel.addin.macroenabled.12'] 'xlb' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel'] 'xlc' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel'] 'xld' : ['application/excel', 'application/x-excel'] 'xlf' : ['application/x-xliff+xml'] 'xlk' : ['application/excel', 'application/x-excel'] 'xll' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel'] 'xlm' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel'] 'xls' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel', 'application/x-msexcel'] 'xlsb' : ['application/vnd.ms-excel.sheet.binary.macroenabled.12'] 'xlsm' : ['application/vnd.ms-excel.sheet.macroenabled.12'] 'xlsx' : ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'] 'xlt' : ['application/excel', 'application/x-excel'] 'xltm' : ['application/vnd.ms-excel.template.macroenabled.12'] 'xltx' : ['application/vnd.openxmlformats-officedocument.spreadsheetml.template'] 'xlv' : ['application/excel', 'application/x-excel'] 'xlw' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel', 'application/x-msexcel'] 'xm' : ['audio/xm'] 'xml' : ['application/xml', 'text/xml'] 'xmz' : ['xgl/movie'] 'xo' : ['application/vnd.olpc-sugar'] 'xop' : ['application/xop+xml'] 'xpdl' : ['application/xml'] 'xpi' : ['application/x-xpinstall'] 'xpix' : ['application/x-vnd.ls-xpix'] 'xpl' : ['application/xproc+xml'] 'xpm' : ['image/x-xpixmap', 'image/xpm'] 'xpr' : ['application/vnd.is-xpr'] 'xps' : ['application/vnd.ms-xpsdocument'] 'xpw' : ['application/vnd.intercon.formnet'] 'xpx' : ['application/vnd.intercon.formnet'] 'xsl' : ['application/xml'] 'xslt' : ['application/xslt+xml'] 'xsm' : ['application/vnd.syncml+xml'] 'xspf' : ['application/xspf+xml'] 'xsr' : ['video/x-amt-showrun'] 'xul' : ['application/vnd.mozilla.xul+xml'] 'xvm' : ['application/xv+xml'] 'xvml' : ['application/xv+xml'] 'xwd' : ['image/x-xwd', 'image/x-xwindowdump'] 'xyz' : ['chemical/x-xyz'] 'xz' : ['application/x-xz'] 'yang' : ['application/yang'] 'yin' : ['application/yin+xml'] 'z' : ['application/x-compress', 'application/x-compressed'] 'z1' : ['application/x-zmachine'] 'z2' : ['application/x-zmachine'] 'z3' : ['application/x-zmachine'] 'z4' : ['application/x-zmachine'] 'z5' : ['application/x-zmachine'] 'z6' : ['application/x-zmachine'] 'z7' : ['application/x-zmachine'] 'z8' : ['application/x-zmachine'] 'zaz' : ['application/vnd.zzazz.deck+xml'] 'zip' : ['application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'] 'zir' : ['application/vnd.zul'] 'zirz' : ['application/vnd.zul'] 'zmm' : ['application/vnd.handheld-entertainment+xml'] 'zoo' : ['application/octet-stream'] 'zsh' : ['text/x-script.zsh'] '123' : ['application/vnd.lotus-1-2-3'] module.exports = MimebyFileExtension : byFileExtension
true
### Translation of gist https://gist.github.com/nimasdj/801b0b1a50112ea6a997 Total: 1223 extensions as of 16 November 2015 ### byFileExtension = '3dm' : ['x-world/x-3dmf'] '3dmf' : ['x-world/x-3dmf'] '3dml' : ['text/vnd.in3d.3dml'] '3ds' : ['image/x-3ds'] '3g2' : ['video/3gpp2'] '3gp' : ['video/3gpp'] '7z' : ['application/x-7z-compressed'] 'a' : ['application/octet-stream'] 'aab' : ['application/x-authorware-bin'] 'aac' : ['audio/x-aac'] 'aam' : ['application/x-authorware-map'] 'aas' : ['application/x-authorware-seg'] 'abc' : ['text/vnd.abc'] 'abw' : ['application/x-abiword'] 'ac' : ['application/pkix-attr-cert'] 'acc' : ['application/vnd.americandynamics.acc'] 'ace' : ['application/x-ace-compressed'] 'acgi' : ['text/html'] 'acu' : ['application/vnd.acucobol'] 'acutc' : ['application/vnd.acucorp'] 'adp' : ['audio/adpcm'] 'aep' : ['application/vnd.audiograph'] 'afl' : ['video/animaflex'] 'afm' : ['application/x-font-type1'] 'afp' : ['application/vnd.ibm.modcap'] 'ahead' : ['application/vnd.ahead.space'] 'ai' : ['application/postscript'] 'aif' : ['audio/aiff', 'audio/x-aiff'] 'aifc' : ['audio/aiff', 'audio/x-aiff'] 'aiff' : ['audio/aiff', 'audio/x-aiff'] 'aim' : ['application/x-aim'] 'aip' : ['text/x-audiosoft-intra'] 'air' : ['application/vnd.adobe.air-application-installer-package+zip'] 'ait' : ['application/vnd.dvb.ait'] 'ami' : ['application/vnd.amiga.ami'] 'ani' : ['application/x-navi-animation'] 'aos' : ['application/x-nokia-9000-communicator-add-on-software'] 'apk' : ['application/vnd.android.package-archive'] 'appcache' : ['text/cache-manifest'] 'application' : ['application/x-ms-application'] 'apr' : ['application/vnd.lotus-approach'] 'aps' : ['application/mime'] 'arc' : ['application/x-freearc'] 'arj' : ['application/arj', 'application/octet-stream'] 'art' : ['image/x-jg'] 'asc' : ['application/pgp-signature'] 'asf' : ['video/x-ms-asf'] 'asm' : ['text/x-asm'] 'aso' : ['application/vnd.accpac.simply.aso'] 'asp' : ['text/asp'] 'asx' : ['application/x-mplayer2', 'video/x-ms-asf', 'video/x-ms-asf-plugin'] 'atc' : ['application/vnd.acucorp'] 'atom' : ['application/atom+xml'] 'atomcat' : ['application/atomcat+xml'] 'atomsvc' : ['application/atomsvc+xml'] 'atx' : ['application/vnd.antix.game-component'] 'au' : ['audio/basic'] 'avi' : ['application/x-troff-msvideo', 'video/avi', 'video/msvideo', 'video/x-msvideo'] 'avs' : ['video/avs-video'] 'aw' : ['application/applixware'] 'azf' : ['application/vnd.airzip.filesecure.azf'] 'azs' : ['application/vnd.airzip.filesecure.azs'] 'azw' : ['application/vnd.amazon.ebook'] 'bat' : ['application/x-msdownload'] 'bcpio' : ['application/x-bcpio'] 'bdf' : ['application/x-font-bdf'] 'bdm' : ['application/vnd.syncml.dm+wbxml'] 'bed' : ['application/vnd.realvnc.bed'] 'bh2' : ['application/vnd.fujitsu.oasysprs'] 'bin' : ['application/mac-binary', 'application/macbinary', 'application/octet-stream', 'application/x-binary', 'application/x-macbinary'] 'blb' : ['application/x-blorb'] 'blorb' : ['application/x-blorb'] 'bm' : ['image/bmp'] 'bmi' : ['application/vnd.bmi'] 'bmp' : ['image/bmp', 'image/x-windows-bmp'] 'boo' : ['application/book'] 'book' : ['application/vnd.framemaker'] 'box' : ['application/vnd.previewsystems.box'] 'boz' : ['application/x-bzip2'] 'bpk' : ['application/octet-stream'] 'bsh' : ['application/x-bsh'] 'btif' : ['image/prs.btif'] 'buffer' : ['application/octet-stream'] 'bz' : ['application/x-bzip'] 'bz2' : ['application/x-bzip2'] 'c' : ['text/x-c'] 'c++' : ['text/plain'] 'c11amc' : ['application/vnd.cluetrust.cartomobile-config'] 'c11amz' : ['application/vnd.cluetrust.cartomobile-config-pkg'] 'c4d' : ['application/vnd.clonk.c4group'] 'c4f' : ['application/vnd.clonk.c4group'] 'c4g' : ['application/vnd.clonk.c4group'] 'c4p' : ['application/vnd.clonk.c4group'] 'c4u' : ['application/vnd.clonk.c4group'] 'cab' : ['application/vnd.ms-cab-compressed'] 'caf' : ['audio/x-caf'] 'cap' : ['application/vnd.tcpdump.pcap'] 'car' : ['application/vnd.curl.car'] 'cat' : ['application/vnd.ms-pki.seccat'] 'cb7' : ['application/x-cbr'] 'cba' : ['application/x-cbr'] 'cbr' : ['application/x-cbr'] 'cbt' : ['application/x-cbr'] 'cbz' : ['application/x-cbr'] 'cc' : ['text/plain', 'text/x-c'] 'ccad' : ['application/clariscad'] 'cco' : ['application/x-cocoa'] 'cct' : ['application/x-director'] 'ccxml' : ['application/ccxml+xml'] 'cdbcmsg' : ['application/vnd.contact.cmsg'] 'cdf' : ['application/cdf', 'application/x-cdf', 'application/x-netcdf'] 'cdkey' : ['application/vnd.mediastation.cdkey'] 'cdmia' : ['application/cdmi-capability'] 'cdmic' : ['application/cdmi-container'] 'cdmid' : ['application/cdmi-domain'] 'cdmio' : ['application/cdmi-object'] 'cdmiq' : ['application/cdmi-queue'] 'cdx' : ['chemical/x-cdx'] 'cdxml' : ['application/vnd.chemdraw+xml'] 'cdy' : ['application/vnd.cinderella'] 'cer' : ['application/pkix-cert', 'application/x-x509-ca-cert'] 'cfs' : ['application/x-cfs-compressed'] 'cgm' : ['image/cgm'] 'cha' : ['application/x-chat'] 'chat' : ['application/x-chat'] 'chm' : ['application/vnd.ms-htmlhelp'] 'chrt' : ['application/vnd.kde.kchart'] 'cif' : ['chemical/x-cif'] 'cii' : ['application/vnd.anser-web-certificate-issue-initiation'] 'cil' : ['application/vnd.ms-artgalry'] 'cla' : ['application/vnd.claymore'] 'class' : ['application/java', 'application/java-byte-code', 'application/x-java-class'] 'clkk' : ['application/vnd.crick.clicker.keyboard'] 'clkp' : ['application/vnd.crick.clicker.palette'] 'clkt' : ['application/vnd.crick.clicker.template'] 'clkw' : ['application/vnd.crick.clicker.wordbank'] 'clkx' : ['application/vnd.crick.clicker'] 'clp' : ['application/x-msclip'] 'cmc' : ['application/vnd.cosmocaller'] 'cmdf' : ['chemical/x-cmdf'] 'cml' : ['chemical/x-cml'] 'cmp' : ['application/vnd.yellowriver-custom-menu'] 'cmx' : ['image/x-cmx'] 'cod' : ['application/vnd.rim.cod'] 'com' : ['application/octet-stream', 'text/plain'] 'conf' : ['text/plain'] 'cpio' : ['application/x-cpio'] 'cpp' : ['text/x-c'] 'cpt' : ['application/x-compactpro', 'application/x-cpt'] 'crd' : ['application/x-mscardfile'] 'crl' : ['application/pkcs-crl', 'application/pkix-crl'] 'crt' : ['application/pkix-cert', 'application/x-x509-ca-cert', 'application/x-x509-user-cert'] 'crx' : ['application/x-chrome-extension'] 'cryptonote' : ['application/vnd.rig.cryptonote'] 'csh' : ['application/x-csh', 'text/x-script.csh'] 'csml' : ['chemical/x-csml'] 'csp' : ['application/vnd.commonspace'] 'css' : ['application/x-pointplus', 'text/css'] 'cst' : ['application/x-director'] 'csv' : ['text/csv'] 'cu' : ['application/cu-seeme'] 'curl' : ['text/vnd.curl'] 'cww' : ['application/prs.cww'] 'cxt' : ['application/x-director'] 'cxx' : ['text/x-c'] 'dae' : ['model/vnd.collada+xml'] 'daf' : ['application/vnd.mobius.daf'] 'dart' : ['application/vnd.dart'] 'dataless' : ['application/vnd.fdsn.seed'] 'davmount' : ['application/davmount+xml'] 'dbk' : ['application/docbook+xml'] 'dcr' : ['application/x-director'] 'dcurl' : ['text/vnd.curl.dcurl'] 'dd2' : ['application/vnd.oma.dd2+xml'] 'ddd' : ['application/vnd.fujixerox.ddd'] 'deb' : ['application/x-debian-package'] 'deepv' : ['application/x-deepv'] 'def' : ['text/plain'] 'deploy' : ['application/octet-stream'] 'der' : ['application/x-x509-ca-cert'] 'dfac' : ['application/vnd.dreamfactory'] 'dgc' : ['application/x-dgc-compressed'] 'dic' : ['text/x-c'] 'dif' : ['video/x-dv'] 'diff' : ['text/plain'] 'dir' : ['application/x-director'] 'dis' : ['application/vnd.mobius.dis'] 'dist' : ['application/octet-stream'] 'distz' : ['application/octet-stream'] 'djv' : ['image/vnd.djvu'] 'djvu' : ['image/vnd.djvu'] 'dl' : ['video/dl', 'video/x-dl'] 'dll' : ['application/x-msdownload'] 'dmg' : ['application/x-apple-diskimage'] 'dmp' : ['application/vnd.tcpdump.pcap'] 'dms' : ['application/octet-stream'] 'dna' : ['application/vnd.dna'] 'doc' : ['application/msword'] 'docm' : ['application/vnd.ms-word.document.macroenabled.12'] 'docx' : ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'] 'dot' : ['application/msword'] 'dotm' : ['application/vnd.ms-word.template.macroenabled.12'] 'dotx' : ['application/vnd.openxmlformats-officedocument.wordprocessingml.template'] 'dp' : ['application/vnd.osgi.dp'] 'dpg' : ['application/vnd.dpgraph'] 'dra' : ['audio/vnd.dra'] 'drw' : ['application/drafting'] 'dsc' : ['text/prs.lines.tag'] 'dssc' : ['application/dssc+der'] 'dtb' : ['application/x-dtbook+xml'] 'dtd' : ['application/xml-dtd'] 'dts' : ['audio/vnd.dts'] 'dtshd' : ['audio/vnd.dts.hd'] 'dump' : ['application/octet-stream'] 'dv' : ['video/x-dv'] 'dvb' : ['video/vnd.dvb.file'] 'dvi' : ['application/x-dvi'] 'dwf' : ['drawing/x-dwf (old)', 'model/vnd.dwf'] 'dwg' : ['application/acad', 'image/vnd.dwg', 'image/x-dwg'] 'dxf' : ['image/vnd.dxf'] 'dxp' : ['application/vnd.spotfire.dxp'] 'dxr' : ['application/x-director'] 'ecelp4800' : ['audio/vnd.nuera.ecelp4800'] 'ecelp7470' : ['audio/vnd.nuera.ecelp7470'] 'ecelp9600' : ['audio/vnd.nuera.ecelp9600'] 'ecma' : ['application/ecmascript'] 'edm' : ['application/vnd.novadigm.edm'] 'edx' : ['application/vnd.novadigm.edx'] 'efif' : ['application/vnd.picsel'] 'ei6' : ['application/vnd.pg.osasli'] 'el' : ['text/x-script.elisp'] 'elc' : ['application/x-bytecode.elisp (compiled elisp)', 'application/x-elc'] 'emf' : ['application/x-msmetafile'] 'eml' : ['message/rfc822'] 'emma' : ['application/emma+xml'] 'emz' : ['application/x-msmetafile'] 'env' : ['application/x-envoy'] 'eol' : ['audio/vnd.digital-winds'] 'eot' : ['application/vnd.ms-fontobject'] 'eps' : ['application/postscript'] 'epub' : ['application/epub+zip'] 'es' : ['application/x-esrehber'] 'es3' : ['application/vnd.eszigno3+xml'] 'esa' : ['application/vnd.osgi.subsystem'] 'esf' : ['application/vnd.epson.esf'] 'et3' : ['application/vnd.eszigno3+xml'] 'etx' : ['text/x-setext'] 'eva' : ['application/x-eva'] 'event-stream' : ['text/event-stream'] 'evy' : ['application/envoy', 'application/x-envoy'] 'exe' : ['application/x-msdownload'] 'exi' : ['application/exi'] 'ext' : ['application/vnd.novadigm.ext'] 'ez' : ['application/andrew-inset'] 'ez2' : ['application/vnd.ezpix-album'] 'ez3' : ['application/vnd.ezpix-package'] 'f' : ['text/plain', 'text/x-fortran'] 'f4v' : ['video/x-f4v'] 'f77' : ['text/x-fortran'] 'f90' : ['text/plain', 'text/x-fortran'] 'fbs' : ['image/vnd.fastbidsheet'] 'fcdt' : ['application/vnd.adobe.formscentral.fcdt'] 'fcs' : ['application/vnd.isac.fcs'] 'fdf' : ['application/vnd.fdf'] 'fe_launch' : ['application/vnd.denovo.fcselayout-link'] 'fg5' : ['application/vnd.fujitsu.oasysgp'] 'fgd' : ['application/x-director'] 'fh' : ['image/x-freehand'] 'fh4' : ['image/x-freehand'] 'fh5' : ['image/x-freehand'] 'fh7' : ['image/x-freehand'] 'fhc' : ['image/x-freehand'] 'fif' : ['application/fractals', 'image/fif'] 'fig' : ['application/x-xfig'] 'flac' : ['audio/flac'] 'fli' : ['video/fli', 'video/x-fli'] 'flo' : ['application/vnd.micrografx.flo'] 'flv' : ['video/x-flv'] 'flw' : ['application/vnd.kde.kivio'] 'flx' : ['text/vnd.fmi.flexstor'] 'fly' : ['text/vnd.fly'] 'fm' : ['application/vnd.framemaker'] 'fmf' : ['video/x-atomic3d-feature'] 'fnc' : ['application/vnd.frogans.fnc'] 'for' : ['text/plain', 'text/x-fortran'] 'fpx' : ['image/vnd.fpx', 'image/vnd.net-fpx'] 'frame' : ['application/vnd.framemaker'] 'frl' : ['application/freeloader'] 'fsc' : ['application/vnd.fsc.weblaunch'] 'fst' : ['image/vnd.fst'] 'ftc' : ['application/vnd.fluxtime.clip'] 'fti' : ['application/vnd.anser-web-funds-transfer-initiation'] 'funk' : ['audio/make'] 'fvt' : ['video/vnd.fvt'] 'fxp' : ['application/vnd.adobe.fxp'] 'fxpl' : ['application/vnd.adobe.fxp'] 'fzs' : ['application/vnd.fuzzysheet'] 'g' : ['text/plain'] 'g2w' : ['application/vnd.geoplan'] 'g3' : ['image/g3fax'] 'g3w' : ['application/vnd.geospace'] 'gac' : ['application/vnd.groove-account'] 'gam' : ['application/x-tads'] 'gbr' : ['application/rpki-ghostbusters'] 'gca' : ['application/x-gca-compressed'] 'gdl' : ['model/vnd.gdl'] 'geo' : ['application/vnd.dynageo'] 'gex' : ['application/vnd.geometry-explorer'] 'ggb' : ['application/vnd.geogebra.file'] 'ggt' : ['application/vnd.geogebra.tool'] 'ghf' : ['application/vnd.groove-help'] 'gif' : ['image/gif'] 'gim' : ['application/vnd.groove-identity-message'] 'gl' : ['video/gl', 'video/x-gl'] 'gml' : ['application/gml+xml'] 'gmx' : ['application/vnd.gmx'] 'gnumeric' : ['application/x-gnumeric'] 'gph' : ['application/vnd.flographit'] 'gpx' : ['application/gpx+xml'] 'gqf' : ['application/vnd.grafeq'] 'gqs' : ['application/vnd.grafeq'] 'gram' : ['application/srgs'] 'gramps' : ['application/x-gramps-xml'] 'gre' : ['application/vnd.geometry-explorer'] 'grv' : ['application/vnd.groove-injector'] 'grxml' : ['application/srgs+xml'] 'gsd' : ['audio/x-gsm'] 'gsf' : ['application/x-font-ghostscript'] 'gsm' : ['audio/x-gsm'] 'gsp' : ['application/x-gsp'] 'gss' : ['application/x-gss'] 'gtar' : ['application/x-gtar'] 'gtm' : ['application/vnd.groove-tool-message'] 'gtw' : ['model/vnd.gtw'] 'gv' : ['text/vnd.graphviz'] 'gxf' : ['application/gxf'] 'gxt' : ['application/vnd.geonext'] 'gz' : ['application/x-compressed', 'application/x-gzip'] 'gzip' : ['application/x-gzip', 'multipart/x-gzip'] 'h' : ['text/plain', 'text/x-h'] 'h261' : ['video/h261'] 'h263' : ['video/h263'] 'h264' : ['video/h264'] 'hal' : ['application/vnd.hal+xml'] 'hbci' : ['application/vnd.hbci'] 'hdf' : ['application/x-hdf'] 'help' : ['application/x-helpfile'] 'hgl' : ['application/vnd.hp-hpgl'] 'hh' : ['text/plain', 'text/x-h'] 'hlb' : ['text/x-script'] 'hlp' : ['application/hlp', 'application/x-helpfile', 'application/x-winhelp'] 'hpg' : ['application/vnd.hp-hpgl'] 'hpgl' : ['application/vnd.hp-hpgl'] 'hpid' : ['application/vnd.hp-hpid'] 'hps' : ['application/vnd.hp-hps'] 'hqx' : ['application/binhex', 'application/binhex4', 'application/mac-binhex', 'application/mac-binhex40', 'application/x-binhex40', 'application/x-mac-binhex40'] 'hta' : ['application/hta'] 'htc' : ['text/x-component'] 'htke' : ['application/vnd.kenameaapp'] 'htm' : ['text/html'] 'html' : ['text/html'] 'htmls' : ['text/html'] 'htt' : ['text/webviewhtml'] 'htx' : ['text/html'] 'hvd' : ['application/vnd.yamaha.hv-dic'] 'hvp' : ['application/vnd.yamaha.hv-voice'] 'hvs' : ['application/vnd.yamaha.hv-script'] 'i2g' : ['application/vnd.intergeo'] 'icc' : ['application/vnd.iccprofile'] 'ice' : ['x-conference/x-cooltalk'] 'icm' : ['application/vnd.iccprofile'] 'ico' : ['image/x-icon'] 'ics' : ['text/calendar'] 'idc' : ['text/plain'] 'ief' : ['image/ief'] 'iefs' : ['image/ief'] 'ifb' : ['text/calendar'] 'ifm' : ['application/vnd.shana.informed.formdata'] 'iges' : ['application/iges', 'model/iges'] 'igl' : ['application/vnd.igloader'] 'igm' : ['application/vnd.insors.igm'] 'igs' : ['application/iges', 'model/iges'] 'igx' : ['application/vnd.micrografx.igx'] 'iif' : ['application/vnd.shana.informed.interchange'] 'ima' : ['application/x-ima'] 'imap' : ['application/x-httpd-imap'] 'imp' : ['application/vnd.accpac.simply.imp'] 'ims' : ['application/vnd.ms-ims'] 'in' : ['text/plain'] 'inf' : ['application/inf'] 'ink' : ['application/inkml+xml'] 'inkml' : ['application/inkml+xml'] 'ins' : ['application/x-internett-signup'] 'install' : ['application/x-install-instructions'] 'iota' : ['application/vnd.astraea-software.iota'] 'ip' : ['application/x-ip2'] 'ipfix' : ['application/ipfix'] 'ipk' : ['application/vnd.shana.informed.package'] 'irm' : ['application/vnd.ibm.rights-management'] 'irp' : ['application/vnd.irepository.package+xml'] 'iso' : ['application/x-iso9660-image'] 'isu' : ['video/x-isvideo'] 'it' : ['audio/it'] 'itp' : ['application/vnd.shana.informed.formtemplate'] 'iv' : ['application/x-inventor'] 'ivp' : ['application/vnd.immervision-ivp'] 'ivr' : ['i-world/i-vrml'] 'ivu' : ['application/vnd.immervision-ivu'] 'ivy' : ['application/x-livescreen'] 'jad' : ['text/vnd.sun.j2me.app-descriptor'] 'jam' : ['application/vnd.jam'] 'jar' : ['application/java-archive'] 'jav' : ['text/plain', 'text/x-java-source'] 'java' : ['text/plain', 'text/x-java-source'] 'jcm' : ['application/x-java-commerce'] 'jfif' : ['image/jpeg', 'image/pjpeg'] 'jfif-tbnl' : ['image/jpeg'] 'jisp' : ['application/vnd.jisp'] 'jlt' : ['application/vnd.hp-jlyt'] 'jnlp' : ['application/x-java-jnlp-file'] 'joda' : ['application/vnd.joost.joda-archive'] 'jpe' : ['image/jpeg', 'image/pjpeg'] 'jpeg' : ['image/jpeg', 'image/pjpeg'] 'jpg' : ['image/jpeg', 'image/pjpeg'] 'jpgm' : ['video/jpm'] 'jpgv' : ['video/jpeg'] 'jpm' : ['video/jpm'] 'jps' : ['image/x-jps'] 'js' : ['application/javascript'] 'json' : ['application/json', 'text/plain'] 'jsonml' : ['application/jsonml+json'] 'jut' : ['image/jutvision'] 'kar' : ['audio/midi', 'music/x-karaoke'] 'karbon' : ['application/vnd.kde.karbon'] 'kfo' : ['application/vnd.kde.kformula'] 'kia' : ['application/vnd.kidspiration'] 'kil' : ['application/x-killustrator'] 'kml' : ['application/vnd.google-earth.kml+xml'] 'kmz' : ['application/vnd.google-earth.kmz'] 'kne' : ['application/vnd.kinar'] 'knp' : ['application/vnd.kinar'] 'kon' : ['application/vnd.kde.kontour'] 'kpr' : ['application/vnd.kde.kpresenter'] 'kpt' : ['application/vnd.kde.kpresenter'] 'kpxx' : ['application/vnd.ds-keypoint'] 'ksh' : ['application/x-ksh', 'text/x-script.ksh'] 'ksp' : ['application/vnd.kde.kspread'] 'ktr' : ['application/vnd.kahootz'] 'ktx' : ['image/ktx'] 'ktz' : ['application/vnd.kahootz'] 'kwd' : ['application/vnd.kde.kword'] 'kwt' : ['application/vnd.kde.kword'] 'la' : ['audio/nspaudio', 'audio/x-nspaudio'] 'lam' : ['audio/x-liveaudio'] 'lasxml' : ['application/vnd.las.las+xml'] 'latex' : ['application/x-latex'] 'lbd' : ['application/vnd.llamagraphics.life-balance.desktop'] 'lbe' : ['application/vnd.llamagraphics.life-balance.exchange+xml'] 'les' : ['application/vnd.hhe.lesson-player'] 'lha' : ['application/lha', 'application/octet-stream', 'application/x-lha'] 'lhx' : ['application/octet-stream'] 'link66' : ['application/vnd.route66.link66+xml'] 'list' : ['text/plain'] 'list3820' : ['application/vnd.ibm.modcap'] 'listafp' : ['application/vnd.ibm.modcap'] 'lma' : ['audio/nspaudio', 'audio/x-nspaudio'] 'lnk' : ['application/x-ms-shortcut'] 'log' : ['text/plain'] 'lostxml' : ['application/lost+xml'] 'lrf' : ['application/octet-stream'] 'lrm' : ['application/vnd.ms-lrm'] 'lsp' : ['application/x-lisp', 'text/x-script.lisp'] 'lst' : ['text/plain'] 'lsx' : ['text/x-la-asf'] 'ltf' : ['application/vnd.frogans.ltf'] 'ltx' : ['application/x-latex'] 'lua' : ['text/x-lua'] 'luac' : ['application/x-lua-bytecode'] 'lvp' : ['audio/vnd.lucent.voice'] 'lwp' : ['application/vnd.lotus-wordpro'] 'lzh' : ['application/octet-stream', 'application/x-lzh'] 'lzx' : ['application/lzx', 'application/octet-stream', 'application/x-lzx'] 'm' : ['text/plain', 'text/x-m'] 'm13' : ['application/x-msmediaview'] 'm14' : ['application/x-msmediaview'] 'm1v' : ['video/mpeg'] 'm21' : ['application/mp21'] 'm2a' : ['audio/mpeg'] 'm2v' : ['video/mpeg'] 'm3a' : ['audio/mpeg'] 'm3u' : ['audio/x-mpegurl'] 'm3u8' : ['application/x-mpegURL'] 'm4a' : ['audio/mp4'] 'm4p' : ['application/mp4'] 'm4u' : ['video/vnd.mpegurl'] 'm4v' : ['video/x-m4v'] 'ma' : ['application/mathematica'] 'mads' : ['application/mads+xml'] 'mag' : ['application/vnd.ecowin.chart'] 'maker' : ['application/vnd.framemaker'] 'man' : ['text/troff'] 'manifest' : ['text/cache-manifest'] 'map' : ['application/x-navimap'] 'mar' : ['application/octet-stream'] 'markdown' : ['text/x-markdown'] 'mathml' : ['application/mathml+xml'] 'mb' : ['application/mathematica'] 'mbd' : ['application/mbedlet'] 'mbk' : ['application/vnd.mobius.mbk'] 'mbox' : ['application/mbox'] 'mc' : ['application/x-magic-cap-package-1.0'] 'mc1' : ['application/vnd.medcalcdata'] 'mcd' : ['application/mcad', 'application/x-mathcad'] 'mcf' : ['image/vasa', 'text/mcf'] 'mcp' : ['application/netmc'] 'mcurl' : ['text/vnd.curl.mcurl'] 'md' : ['text/x-markdown'] 'mdb' : ['application/x-msaccess'] 'mdi' : ['image/vnd.ms-modi'] 'me' : ['text/troff'] 'mesh' : ['model/mesh'] 'meta4' : ['application/metalink4+xml'] 'metalink' : ['application/metalink+xml'] 'mets' : ['application/mets+xml'] 'mfm' : ['application/vnd.mfmp'] 'mft' : ['application/rpki-manifest'] 'mgp' : ['application/vnd.osgeo.mapguide.package'] 'mgz' : ['application/vnd.proteus.magazine'] 'mht' : ['message/rfc822'] 'mhtml' : ['message/rfc822'] 'mid' : ['application/x-midi', 'audio/midi', 'audio/x-mid', 'audio/x-midi', 'music/crescendo', 'x-music/x-midi'] 'midi' : ['application/x-midi', 'audio/midi', 'audio/x-mid', 'audio/x-midi', 'music/crescendo', 'x-music/x-midi'] 'mie' : ['application/x-mie'] 'mif' : ['application/x-frame', 'application/x-mif'] 'mime' : ['message/rfc822', 'www/mime'] 'mj2' : ['video/mj2'] 'mjf' : ['audio/x-vnd.audioexplosion.mjuicemediafile'] 'mjp2' : ['video/mj2'] 'mjpg' : ['video/x-motion-jpeg'] 'mk3d' : ['video/x-matroska'] 'mka' : ['audio/x-matroska'] 'mkd' : ['text/x-markdown'] 'mks' : ['video/x-matroska'] 'mkv' : ['video/x-matroska'] 'mlp' : ['application/vnd.dolby.mlp'] 'mm' : ['application/base64', 'application/x-meme'] 'mmd' : ['application/vnd.chipnuts.karaoke-mmd'] 'mme' : ['application/base64'] 'mmf' : ['application/vnd.smaf'] 'mmr' : ['image/vnd.fujixerox.edmics-mmr'] 'mng' : ['video/x-mng'] 'mny' : ['application/x-msmoney'] 'mobi' : ['application/x-mobipocket-ebook'] 'mod' : ['audio/mod', 'audio/x-mod'] 'mods' : ['application/mods+xml'] 'moov' : ['video/quicktime'] 'mov' : ['video/quicktime'] 'movie' : ['video/x-sgi-movie'] 'mp2' : ['audio/mpeg', 'audio/x-mpeg', 'video/mpeg', 'video/x-mpeg', 'video/x-mpeq2a'] 'mp21' : ['application/mp21'] 'mp2a' : ['audio/mpeg'] 'mp3' : ['audio/mpeg3', 'audio/x-mpeg-3', 'video/mpeg', 'video/x-mpeg'] 'mp4' : ['video/mp4'] 'mp4a' : ['audio/mp4'] 'mp4s' : ['application/mp4'] 'mp4v' : ['video/mp4'] 'mpa' : ['audio/mpeg', 'video/mpeg'] 'mpc' : ['application/vnd.mophun.certificate'] 'mpe' : ['video/mpeg'] 'mpeg' : ['video/mpeg'] 'mpg' : ['audio/mpeg', 'video/mpeg'] 'mpg4' : ['video/mp4'] 'mpga' : ['audio/mpeg'] 'mpkg' : ['application/vnd.apple.installer+xml'] 'mpm' : ['application/vnd.blueice.multipass'] 'mpn' : ['application/vnd.mophun.application'] 'mpp' : ['application/vnd.ms-project'] 'mpt' : ['application/vnd.ms-project'] 'mpv' : ['application/x-project'] 'mpx' : ['application/x-project'] 'mpy' : ['application/vnd.ibm.minipay'] 'mqy' : ['application/vnd.mobius.mqy'] 'mrc' : ['application/marc'] 'mrcx' : ['application/marcxml+xml'] 'ms' : ['text/troff'] 'mscml' : ['application/mediaservercontrol+xml'] 'mseed' : ['application/vnd.fdsn.mseed'] 'mseq' : ['application/vnd.mseq'] 'msf' : ['application/vnd.epson.msf'] 'msh' : ['model/mesh'] 'msi' : ['application/x-msdownload'] 'msl' : ['application/vnd.mobius.msl'] 'msty' : ['application/vnd.muvee.style'] 'mts' : ['model/vnd.mts'] 'mus' : ['application/vnd.musician'] 'musicxml' : ['application/vnd.recordare.musicxml+xml'] 'mv' : ['video/x-sgi-movie'] 'mvb' : ['application/x-msmediaview'] 'mwf' : ['application/vnd.mfer'] 'mxf' : ['application/mxf'] 'mxl' : ['application/vnd.recordare.musicxml'] 'mxml' : ['application/xv+xml'] 'mxs' : ['application/vnd.triscape.mxs'] 'mxu' : ['video/vnd.mpegurl'] 'my' : ['audio/make'] 'mzz' : ['application/x-vnd.audioexplosion.mzz'] 'n-gage' : ['application/vnd.nokia.n-gage.symbian.install'] 'n3' : ['text/n3'] 'nap' : ['image/naplps'] 'naplps' : ['image/naplps'] 'nb' : ['application/mathematica'] 'nbp' : ['application/vnd.wolfram.player'] 'nc' : ['application/x-netcdf'] 'ncm' : ['application/vnd.nokia.configuration-message'] 'ncx' : ['application/x-dtbncx+xml'] 'nfo' : ['text/x-nfo'] 'ngdat' : ['application/vnd.nokia.n-gage.data'] 'nif' : ['image/x-niff'] 'niff' : ['image/x-niff'] 'nitf' : ['application/vnd.nitf'] 'nix' : ['application/x-mix-transfer'] 'nlu' : ['application/vnd.neurolanguage.nlu'] 'nml' : ['application/vnd.enliven'] 'nnd' : ['application/vnd.noblenet-directory'] 'nns' : ['application/vnd.noblenet-sealer'] 'nnw' : ['application/vnd.noblenet-web'] 'npx' : ['image/vnd.net-fpx'] 'nsc' : ['application/x-conference'] 'nsf' : ['application/vnd.lotus-notes'] 'ntf' : ['application/vnd.nitf'] 'nvd' : ['application/x-navidoc'] 'nws' : ['message/rfc822'] 'nzb' : ['application/x-nzb'] 'o' : ['application/octet-stream'] 'oa2' : ['application/vnd.fujitsu.oasys2'] 'oa3' : ['application/vnd.fujitsu.oasys3'] 'oas' : ['application/vnd.fujitsu.oasys'] 'obd' : ['application/x-msbinder'] 'obj' : ['application/x-tgif'] 'oda' : ['application/oda'] 'odb' : ['application/vnd.oasis.opendocument.database'] 'odc' : ['application/vnd.oasis.opendocument.chart'] 'odf' : ['application/vnd.oasis.opendocument.formula'] 'odft' : ['application/vnd.oasis.opendocument.formula-template'] 'odg' : ['application/vnd.oasis.opendocument.graphics'] 'odi' : ['application/vnd.oasis.opendocument.image'] 'odm' : ['application/vnd.oasis.opendocument.text-master'] 'odp' : ['application/vnd.oasis.opendocument.presentation'] 'ods' : ['application/vnd.oasis.opendocument.spreadsheet'] 'odt' : ['application/vnd.oasis.opendocument.text'] 'oga' : ['audio/ogg'] 'ogg' : ['audio/ogg'] 'ogv' : ['video/ogg'] 'ogx' : ['application/ogg'] 'omc' : ['application/x-omc'] 'omcd' : ['application/x-omcdatamaker'] 'omcr' : ['application/x-omcregerator'] 'omdoc' : ['application/omdoc+xml'] 'onepkg' : ['application/onenote'] 'onetmp' : ['application/onenote'] 'onetoc' : ['application/onenote'] 'onetoc2' : ['application/onenote'] 'opf' : ['application/oebps-package+xml'] 'opml' : ['text/x-opml'] 'oprc' : ['application/vnd.palm'] 'org' : ['application/vnd.lotus-organizer'] 'osf' : ['application/vnd.yamaha.openscoreformat'] 'osfpvg' : ['application/vnd.yamaha.openscoreformat.osfpvg+xml'] 'otc' : ['application/vnd.oasis.opendocument.chart-template'] 'otf' : ['font/opentype'] 'otg' : ['application/vnd.oasis.opendocument.graphics-template'] 'oth' : ['application/vnd.oasis.opendocument.text-web'] 'oti' : ['application/vnd.oasis.opendocument.image-template'] 'otm' : ['application/vnd.oasis.opendocument.text-master'] 'otp' : ['application/vnd.oasis.opendocument.presentation-template'] 'ots' : ['application/vnd.oasis.opendocument.spreadsheet-template'] 'ott' : ['application/vnd.oasis.opendocument.text-template'] 'oxps' : ['application/oxps'] 'oxt' : ['application/vnd.openofficeorg.extension'] 'p' : ['text/x-pascal'] 'p10' : ['application/pkcs10', 'application/x-pkcs10'] 'p12' : ['application/pkcs-12', 'application/x-pkcs12'] 'p7a' : ['application/x-pkcs7-signature'] 'p7b' : ['application/x-pkcs7-certificates'] 'p7c' : ['application/pkcs7-mime', 'application/x-pkcs7-mime'] 'p7m' : ['application/pkcs7-mime', 'application/x-pkcs7-mime'] 'p7r' : ['application/x-pkcs7-certreqresp'] 'p7s' : ['application/pkcs7-signature'] 'p8' : ['application/pkcs8'] 'part' : ['application/pro_eng'] 'pas' : ['text/x-pascal'] 'paw' : ['application/vnd.pawaafile'] 'pbd' : ['application/vnd.powerbuilder6'] 'pbm' : ['image/x-portable-bitmap'] 'pcap' : ['application/vnd.tcpdump.pcap'] 'pcf' : ['application/x-font-pcf'] 'pcl' : ['application/vnd.hp-pcl', 'application/x-pcl'] 'pclxl' : ['application/vnd.hp-pclxl'] 'pct' : ['image/x-pict'] 'pcurl' : ['application/vnd.curl.pcurl'] 'pcx' : ['image/x-pcx'] 'pdb' : ['application/vnd.palm'] 'pdf' : ['application/pdf'] 'pfa' : ['application/x-font-type1'] 'pfb' : ['application/x-font-type1'] 'pfm' : ['application/x-font-type1'] 'pfr' : ['application/font-tdpfr'] 'pfunk' : ['audio/make'] 'pfx' : ['application/x-pkcs12'] 'pgm' : ['image/x-portable-graymap'] 'pgn' : ['application/x-chess-pgn'] 'pgp' : ['application/pgp-encrypted'] 'php' : ['text/x-php'] 'pic' : ['image/x-pict'] 'pict' : ['image/pict'] 'pkg' : ['application/octet-stream'] 'pki' : ['application/pkixcmp'] 'pkipath' : ['application/pkix-pkipath'] 'pko' : ['application/vnd.ms-pki.pko'] 'pl' : ['text/plain', 'text/x-script.perl'] 'plb' : ['application/vnd.3gpp.pic-bw-large'] 'plc' : ['application/vnd.mobius.plc'] 'plf' : ['application/vnd.pocketlearn'] 'pls' : ['application/pls+xml'] 'plx' : ['application/x-pixclscript'] 'pm' : ['image/x-xpixmap', 'text/x-script.perl-module'] 'pm4' : ['application/x-pagemaker'] 'pm5' : ['application/x-pagemaker'] 'pml' : ['application/vnd.ctc-posml'] 'png' : ['image/png'] 'pnm' : ['application/x-portable-anymap', 'image/x-portable-anymap'] 'portpkg' : ['application/vnd.macports.portpkg'] 'pot' : ['application/mspowerpoint', 'application/vnd.ms-powerpoint'] 'potm' : ['application/vnd.ms-powerpoint.template.macroenabled.12'] 'potx' : ['application/vnd.openxmlformats-officedocument.presentationml.template'] 'pov' : ['model/x-pov'] 'ppa' : ['application/vnd.ms-powerpoint'] 'ppam' : ['application/vnd.ms-powerpoint.addin.macroenabled.12'] 'ppd' : ['application/vnd.cups-ppd'] 'ppm' : ['image/x-portable-pixmap'] 'pps' : ['application/mspowerpoint', 'application/vnd.ms-powerpoint'] 'ppsm' : ['application/vnd.ms-powerpoint.slideshow.macroenabled.12'] 'ppsx' : ['application/vnd.openxmlformats-officedocument.presentationml.slideshow'] 'ppt' : ['application/mspowerpoint', 'application/powerpoint', 'application/vnd.ms-powerpoint', 'application/x-mspowerpoint'] 'pptm' : ['application/vnd.ms-powerpoint.presentation.macroenabled.12'] 'pptx' : ['application/vnd.openxmlformats-officedocument.presentationml.presentation'] 'ppz' : ['application/mspowerpoint'] 'pqa' : ['application/vnd.palm'] 'prc' : ['application/x-mobipocket-ebook'] 'pre' : ['application/vnd.lotus-freelance'] 'prf' : ['application/pics-rules'] 'prt' : ['application/pro_eng'] 'ps' : ['application/postscript'] 'psb' : ['application/vnd.3gpp.pic-bw-small'] 'psd' : ['image/vnd.adobe.photoshop'] 'psf' : ['application/x-font-linux-psf'] 'pskcxml' : ['application/pskc+xml'] 'ptid' : ['application/vnd.pvi.ptid1'] 'pub' : ['application/x-mspublisher'] 'pvb' : ['application/vnd.3gpp.pic-bw-var'] 'pvu' : ['paleovu/x-pv'] 'pwn' : ['application/vnd.3m.post-it-notes'] 'pwz' : ['application/vnd.ms-powerpoint'] 'py' : ['text/x-script.phyton'] 'pya' : ['audio/vnd.ms-playready.media.pya'] 'pyc' : ['applicaiton/x-bytecode.python'] 'pyo' : ['application/x-python-code'] 'pyv' : ['video/vnd.ms-playready.media.pyv'] 'qam' : ['application/vnd.epson.quickanime'] 'qbo' : ['application/vnd.intu.qbo'] 'qcp' : ['audio/vnd.qcelp'] 'qd3' : ['x-world/x-3dmf'] 'qd3d' : ['x-world/x-3dmf'] 'qfx' : ['application/vnd.intu.qfx'] 'qif' : ['image/x-quicktime'] 'qps' : ['application/vnd.publishare-delta-tree'] 'qt' : ['video/quicktime'] 'qtc' : ['video/x-qtc'] 'qti' : ['image/x-quicktime'] 'qtif' : ['image/x-quicktime'] 'qwd' : ['application/vnd.quark.quarkxpress'] 'qwt' : ['application/vnd.quark.quarkxpress'] 'qxb' : ['application/vnd.quark.quarkxpress'] 'qxd' : ['application/vnd.quark.quarkxpress'] 'qxl' : ['application/vnd.quark.quarkxpress'] 'qxt' : ['application/vnd.quark.quarkxpress'] 'ra' : ['audio/x-pn-realaudio', 'audio/x-pn-realaudio-plugin', 'audio/x-realaudio'] 'ram' : ['audio/x-pn-realaudio'] 'rar' : ['application/x-rar-compressed'] 'ras' : ['application/x-cmu-raster', 'image/cmu-raster', 'image/x-cmu-raster'] 'rast' : ['image/cmu-raster'] 'rcprofile' : ['application/vnd.ipunplugged.rcprofile'] 'rdf' : ['application/rdf+xml'] 'rdz' : ['application/vnd.data-vision.rdz'] 'rep' : ['application/vnd.businessobjects'] 'res' : ['application/x-dtbresource+xml'] 'rexx' : ['text/x-script.rexx'] 'rf' : ['image/vnd.rn-realflash'] 'rgb' : ['image/x-rgb'] 'rif' : ['application/reginfo+xml'] 'rip' : ['audio/vnd.rip'] 'ris' : ['application/x-research-info-systems'] 'rl' : ['application/resource-lists+xml'] 'rlc' : ['image/vnd.fujixerox.edmics-rlc'] 'rld' : ['application/resource-lists-diff+xml'] 'rm' : ['application/vnd.rn-realmedia', 'audio/x-pn-realaudio'] 'rmi' : ['audio/midi'] 'rmm' : ['audio/x-pn-realaudio'] 'rmp' : ['audio/x-pn-realaudio', 'audio/x-pn-realaudio-plugin'] 'rms' : ['application/vnd.jcp.javame.midlet-rms'] 'rmvb' : ['application/vnd.rn-realmedia-vbr'] 'rnc' : ['application/relax-ng-compact-syntax'] 'rng' : ['application/ringing-tones', 'application/vnd.nokia.ringing-tone'] 'rnx' : ['application/vnd.rn-realplayer'] 'roa' : ['application/rpki-roa'] 'roff' : ['text/troff'] 'rp' : ['image/vnd.rn-realpix'] 'rp9' : ['application/vnd.cloanto.rp9'] 'rpm' : ['audio/x-pn-realaudio-plugin'] 'rpss' : ['application/vnd.nokia.radio-presets'] 'rpst' : ['application/vnd.nokia.radio-preset'] 'rq' : ['application/sparql-query'] 'rs' : ['application/rls-services+xml'] 'rsd' : ['application/rsd+xml'] 'rss' : ['application/rss+xml'] 'rt' : ['text/richtext', 'text/vnd.rn-realtext'] 'rtf' : ['application/rtf', 'application/x-rtf', 'text/richtext'] 'rtx' : ['application/rtf', 'text/richtext'] 'rv' : ['video/vnd.rn-realvideo'] 's' : ['text/x-asm'] 's3m' : ['audio/s3m'] 'saf' : ['application/vnd.yamaha.smaf-audio'] 'saveme' : ['aapplication/octet-stream'] 'sbk' : ['application/x-tbook'] 'sbml' : ['application/sbml+xml'] 'sc' : ['application/vnd.ibm.secure-container'] 'scd' : ['application/x-msschedule'] 'scm' : ['application/x-lotusscreencam', 'text/x-script.guile', 'text/x-script.scheme', 'video/x-scm'] 'scq' : ['application/scvp-cv-item'] 'scs' : ['application/scvp-cv-response'] 'scurl' : ['text/vnd.curl.scurl'] 'sda' : ['application/vnd.stardivision.draw'] 'sdc' : ['application/vnd.stardivision.calc'] 'sdd' : ['application/vnd.stardivision.impress'] 'sdkd' : ['application/vnd.solent.sdkm+xml'] 'sdkm' : ['application/vnd.solent.sdkm+xml'] 'sdml' : ['text/plain'] 'sdp' : ['application/sdp', 'application/x-sdp'] 'sdr' : ['application/sounder'] 'sdw' : ['application/vnd.stardivision.writer'] 'sea' : ['application/sea', 'application/x-sea'] 'see' : ['application/vnd.seemail'] 'seed' : ['application/vnd.fdsn.seed'] 'sema' : ['application/vnd.sema'] 'semd' : ['application/vnd.semd'] 'semf' : ['application/vnd.semf'] 'ser' : ['application/java-serialized-object'] 'set' : ['application/set'] 'setpay' : ['application/set-payment-initiation'] 'setreg' : ['application/set-registration-initiation'] 'sfd-hdstx' : ['application/vnd.hydrostatix.sof-data'] 'sfs' : ['application/vnd.spotfire.sfs'] 'sfv' : ['text/x-sfv'] 'sgi' : ['image/sgi'] 'sgl' : ['application/vnd.stardivision.writer-global'] 'sgm' : ['text/sgml', 'text/x-sgml'] 'sgml' : ['text/sgml', 'text/x-sgml'] 'sh' : ['application/x-bsh', 'application/x-sh', 'application/x-shar', 'text/x-script.sh'] 'shar' : ['application/x-bsh', 'application/x-shar'] 'shf' : ['application/shf+xml'] 'shtml' : ['text/html', 'text/x-server-parsed-html'] 'si' : ['text/vnd.wap.si'] 'sic' : ['application/vnd.wap.sic'] 'sid' : ['image/x-mrsid-image'] 'sig' : ['application/pgp-signature'] 'sil' : ['audio/silk'] 'silo' : ['model/mesh'] 'sis' : ['application/vnd.symbian.install'] 'sisx' : ['application/vnd.symbian.install'] 'sit' : ['application/x-sit', 'application/x-stuffit'] 'sitx' : ['application/x-stuffitx'] 'skd' : ['application/vnd.koan'] 'skm' : ['application/vnd.koan'] 'skp' : ['application/vnd.koan'] 'skt' : ['application/vnd.koan'] 'sl' : ['application/x-seelogo'] 'slc' : ['application/vnd.wap.slc'] 'sldm' : ['application/vnd.ms-powerpoint.slide.macroenabled.12'] 'sldx' : ['application/vnd.openxmlformats-officedocument.presentationml.slide'] 'slt' : ['application/vnd.epson.salt'] 'sm' : ['application/vnd.stepmania.stepchart'] 'smf' : ['application/vnd.stardivision.math'] 'smi' : ['application/smil+xml'] 'smil' : ['application/smil+xml'] 'smv' : ['video/x-smv'] 'smzip' : ['application/vnd.stepmania.package'] 'snd' : ['audio/basic', 'audio/x-adpcm'] 'snf' : ['application/x-font-snf'] 'so' : ['application/octet-stream'] 'sol' : ['application/solids'] 'spc' : ['application/x-pkcs7-certificates', 'text/x-speech'] 'spf' : ['application/vnd.yamaha.smaf-phrase'] 'spl' : ['application/x-futuresplash'] 'spot' : ['text/vnd.in3d.spot'] 'spp' : ['application/scvp-vp-response'] 'spq' : ['application/scvp-vp-item'] 'spr' : ['application/x-sprite'] 'sprite' : ['application/x-sprite'] 'spx' : ['audio/ogg'] 'sql' : ['application/x-sql'] 'src' : ['application/x-wais-source'] 'srt' : ['application/x-subrip'] 'sru' : ['application/sru+xml'] 'srx' : ['application/sparql-results+xml'] 'ssdl' : ['application/ssdl+xml'] 'sse' : ['application/vnd.kodak-descriptor'] 'ssf' : ['application/vnd.epson.ssf'] 'ssi' : ['text/x-server-parsed-html'] 'ssm' : ['application/streamingmedia'] 'ssml' : ['application/ssml+xml'] 'sst' : ['application/vnd.ms-pki.certstore'] 'st' : ['application/vnd.sailingtracker.track'] 'stc' : ['application/vnd.sun.xml.calc.template'] 'std' : ['application/vnd.sun.xml.draw.template'] 'step' : ['application/step'] 'stf' : ['application/vnd.wt.stf'] 'sti' : ['application/vnd.sun.xml.impress.template'] 'stk' : ['application/hyperstudio'] 'stl' : ['application/sla', 'application/vnd.ms-pki.stl', 'application/x-navistyle'] 'stp' : ['application/step'] 'str' : ['application/vnd.pg.format'] 'stw' : ['application/vnd.sun.xml.writer.template'] 'sub' : ['text/vnd.dvb.subtitle'] 'sus' : ['application/vnd.sus-calendar'] 'susp' : ['application/vnd.sus-calendar'] 'sv4cpio' : ['application/x-sv4cpio'] 'sv4crc' : ['application/x-sv4crc'] 'svc' : ['application/vnd.dvb.service'] 'svd' : ['application/vnd.svd'] 'svf' : ['image/vnd.dwg', 'image/x-dwg'] 'svg' : ['image/svg+xml'] 'svgz' : ['image/svg+xml'] 'svr' : ['application/x-world', 'x-world/x-svr'] 'swa' : ['application/x-director'] 'swf' : ['application/x-shockwave-flash'] 'swi' : ['application/vnd.aristanetworks.swi'] 'sxc' : ['application/vnd.sun.xml.calc'] 'sxd' : ['application/vnd.sun.xml.draw'] 'sxg' : ['application/vnd.sun.xml.writer.global'] 'sxi' : ['application/vnd.sun.xml.impress'] 'sxm' : ['application/vnd.sun.xml.math'] 'sxw' : ['application/vnd.sun.xml.writer'] 't' : ['text/troff'] 't3' : ['application/x-t3vm-image'] 'taglet' : ['application/vnd.mynfc'] 'talk' : ['text/x-speech'] 'tao' : ['application/vnd.tao.intent-module-archive'] 'tar' : ['application/x-tar'] 'tbk' : ['application/toolbook', 'application/x-tbook'] 'tcap' : ['application/vnd.3gpp2.tcap'] 'tcl' : ['application/x-tcl', 'text/x-script.tcl'] 'tcsh' : ['text/x-script.tcsh'] 'teacher' : ['application/vnd.smart.teacher'] 'tei' : ['application/tei+xml'] 'teicorpus' : ['application/tei+xml'] 'tex' : ['application/x-tex'] 'texi' : ['application/x-texinfo'] 'texinfo' : ['application/x-texinfo'] 'text' : ['application/plain', 'text/plain'] 'tfi' : ['application/thraud+xml'] 'tfm' : ['application/x-tex-tfm'] 'tga' : ['image/x-tga'] 'tgz' : ['application/gnutar', 'application/x-compressed'] 'thmx' : ['application/vnd.ms-officetheme'] 'tif' : ['image/tiff', 'image/x-tiff'] 'tiff' : ['image/tiff', 'image/x-tiff'] 'tmo' : ['application/vnd.tmobile-livetv'] 'torrent' : ['application/x-bittorrent'] 'tpl' : ['application/vnd.groove-tool-template'] 'tpt' : ['application/vnd.trid.tpt'] 'tr' : ['text/troff'] 'tra' : ['application/vnd.trueapp'] 'trm' : ['application/x-msterminal'] 'ts' : ['video/MP2T'] 'tsd' : ['application/timestamped-data'] 'tsi' : ['audio/tsp-audio'] 'tsp' : ['application/dsptype', 'audio/tsplayer'] 'tsv' : ['text/tab-separated-values'] 'ttc' : ['application/x-font-ttf'] 'ttf' : ['application/x-font-ttf'] 'ttl' : ['text/turtle'] 'turbot' : ['image/PI:NAME:<NAME>END_PI'] 'twd' : ['application/vnd.simtech-mindmapper'] 'twds' : ['application/vnd.simtech-mindmapper'] 'txd' : ['application/vnd.genomatix.tuxedo'] 'txf' : ['application/vnd.mobius.txf'] 'txt' : ['text/plain'] 'u32' : ['application/x-authorware-bin'] 'udeb' : ['application/x-debian-package'] 'ufd' : ['application/vnd.ufdl'] 'ufdl' : ['application/vnd.ufdl'] 'uil' : ['text/x-uil'] 'ulx' : ['application/x-glulx'] 'umj' : ['application/vnd.umajin'] 'uni' : ['text/uri-list'] 'unis' : ['text/uri-list'] 'unityweb' : ['application/vnd.unity'] 'unv' : ['application/i-deas'] 'uoml' : ['application/vnd.uoml+xml'] 'uri' : ['text/uri-list'] 'uris' : ['text/uri-list'] 'urls' : ['text/uri-list'] 'ustar' : ['application/x-ustar', 'multipart/x-ustar'] 'utz' : ['application/vnd.uiq.theme'] 'uu' : ['application/octet-stream', 'text/x-uuencode'] 'uue' : ['text/x-uuencode'] 'uva' : ['audio/vnd.dece.audio'] 'uvd' : ['application/vnd.dece.data'] 'uvf' : ['application/vnd.dece.data'] 'uvg' : ['image/vnd.dece.graphic'] 'uvh' : ['video/vnd.dece.hd'] 'uvi' : ['image/vnd.dece.graphic'] 'uvm' : ['video/vnd.dece.mobile'] 'uvp' : ['video/vnd.dece.pd'] 'uvs' : ['video/vnd.dece.sd'] 'uvt' : ['application/vnd.dece.ttml+xml'] 'uvu' : ['video/vnd.uvvu.mp4'] 'uvv' : ['video/vnd.dece.video'] 'uvva' : ['audio/vnd.dece.audio'] 'uvvd' : ['application/vnd.dece.data'] 'uvvf' : ['application/vnd.dece.data'] 'uvvg' : ['image/vnd.dece.graphic'] 'uvvh' : ['video/vnd.dece.hd'] 'uvvi' : ['image/vnd.dece.graphic'] 'uvvm' : ['video/vnd.dece.mobile'] 'uvvp' : ['video/vnd.dece.pd'] 'uvvs' : ['video/vnd.dece.sd'] 'uvvt' : ['application/vnd.dece.ttml+xml'] 'uvvu' : ['video/vnd.uvvu.mp4'] 'uvvv' : ['video/vnd.dece.video'] 'uvvx' : ['application/vnd.dece.unspecified'] 'uvvz' : ['application/vnd.dece.zip'] 'uvx' : ['application/vnd.dece.unspecified'] 'uvz' : ['application/vnd.dece.zip'] 'vcard' : ['text/vcard'] 'vcd' : ['application/x-cdlink'] 'vcf' : ['text/x-vcard'] 'vcg' : ['application/vnd.groove-vcard'] 'vcs' : ['text/x-vcalendar'] 'vcx' : ['application/vnd.vcx'] 'vda' : ['application/vda'] 'vdo' : ['video/vdo'] 'vew' : ['application/groupwise'] 'vis' : ['application/vnd.visionary'] 'viv' : ['video/vivo', 'video/vnd.vivo'] 'vivo' : ['video/vivo', 'video/vnd.vivo'] 'vmd' : ['application/vocaltec-media-desc'] 'vmf' : ['application/vocaltec-media-file'] 'vob' : ['video/x-ms-vob'] 'voc' : ['audio/voc', 'audio/x-voc'] 'vor' : ['application/vnd.stardivision.writer'] 'vos' : ['video/vosaic'] 'vox' : ['application/x-authorware-bin'] 'vqe' : ['audio/x-twinvq-plugin'] 'vqf' : ['audio/x-twinvq'] 'vql' : ['audio/x-twinvq-plugin'] 'vrml' : ['application/x-vrml', 'model/vrml', 'x-world/x-vrml'] 'vrt' : ['x-world/x-vrt'] 'vsd' : ['application/vnd.visio'] 'vsf' : ['application/vnd.vsf'] 'vss' : ['application/vnd.visio'] 'vst' : ['application/vnd.visio'] 'vsw' : ['application/vnd.visio'] 'vtt' : ['text/vtt'] 'vtu' : ['model/vnd.vtu'] 'vxml' : ['application/voicexml+xml'] 'w3d' : ['application/x-director'] 'w60' : ['application/wordperfect6.0'] 'w61' : ['application/wordperfect6.1'] 'w6w' : ['application/msword'] 'wad' : ['application/x-doom'] 'wav' : ['audio/wav', 'audio/x-wav'] 'wax' : ['audio/x-ms-wax'] 'wb1' : ['application/x-qpro'] 'wbmp' : ['image/vnd.wap.wbmp'] 'wbs' : ['application/vnd.criticaltools.wbs+xml'] 'wbxml' : ['application/vnd.wap.wbxml'] 'wcm' : ['application/vnd.ms-works'] 'wdb' : ['application/vnd.ms-works'] 'wdp' : ['image/vnd.ms-photo'] 'web' : ['application/vnd.xara'] 'weba' : ['audio/webm'] 'webapp' : ['application/x-web-app-manifest+json'] 'webm' : ['video/webm'] 'webp' : ['image/webp'] 'wg' : ['application/vnd.pmi.widget'] 'wgt' : ['application/widget'] 'wiz' : ['application/msword'] 'wk1' : ['application/x-123'] 'wks' : ['application/vnd.ms-works'] 'wm' : ['video/x-ms-wm'] 'wma' : ['audio/x-ms-wma'] 'wmd' : ['application/x-ms-wmd'] 'wmf' : ['application/x-msmetafile'] 'wml' : ['text/vnd.wap.wml'] 'wmlc' : ['application/vnd.wap.wmlc'] 'wmls' : ['text/vnd.wap.wmlscript'] 'wmlsc' : ['application/vnd.wap.wmlscriptc'] 'wmv' : ['video/x-ms-wmv'] 'wmx' : ['video/x-ms-wmx'] 'wmz' : ['application/x-msmetafile'] 'woff' : ['application/x-font-woff'] 'word' : ['application/msword'] 'wp' : ['application/wordperfect'] 'wp5' : ['application/wordperfect', 'application/wordperfect6.0'] 'wp6' : ['application/wordperfect'] 'wpd' : ['application/wordperfect', 'application/x-wpwin'] 'wpl' : ['application/vnd.ms-wpl'] 'wps' : ['application/vnd.ms-works'] 'wq1' : ['application/x-lotus'] 'wqd' : ['application/vnd.wqd'] 'wri' : ['application/mswrite', 'application/x-wri'] 'wrl' : ['application/x-world', 'model/vrml', 'x-world/x-vrml'] 'wrz' : ['model/vrml', 'x-world/x-vrml'] 'wsc' : ['text/scriplet'] 'wsdl' : ['application/wsdl+xml'] 'wspolicy' : ['application/wspolicy+xml'] 'wsrc' : ['application/x-wais-source'] 'wtb' : ['application/vnd.webturbo'] 'wtk' : ['application/x-wintalk'] 'wvx' : ['video/x-ms-wvx'] 'x-png' : ['image/png'] 'x32' : ['application/x-authorware-bin'] 'x3d' : ['model/x3d+xml'] 'x3db' : ['model/x3d+binary'] 'x3dbz' : ['model/x3d+binary'] 'x3dv' : ['model/x3d+vrml'] 'x3dvz' : ['model/x3d+vrml'] 'x3dz' : ['model/x3d+xml'] 'xaml' : ['application/xaml+xml'] 'xap' : ['application/x-silverlight-app'] 'xar' : ['application/vnd.xara'] 'xbap' : ['application/x-ms-xbap'] 'xbd' : ['application/vnd.fujixerox.docuworks.binder'] 'xbm' : ['image/x-xbitmap', 'image/x-xbm', 'image/xbm'] 'xdf' : ['application/xcap-diff+xml'] 'xdm' : ['application/vnd.syncml.dm+xml'] 'xdp' : ['application/vnd.adobe.xdp+xml'] 'xdr' : ['video/x-amt-demorun'] 'xdssc' : ['application/dssc+xml'] 'xdw' : ['application/vnd.fujixerox.docuworks'] 'xenc' : ['application/xenc+xml'] 'xer' : ['application/patch-ops-error+xml'] 'xfdf' : ['application/vnd.adobe.xfdf'] 'xfdl' : ['application/vnd.xfdl'] 'xgz' : ['xgl/drawing'] 'xht' : ['application/xhtml+xml'] 'xhtml' : ['application/xhtml+xml'] 'xhvml' : ['application/xv+xml'] 'xif' : ['image/vnd.xiff'] 'xl' : ['application/excel'] 'xla' : ['application/excel', 'application/x-excel', 'application/x-msexcel'] 'xlam' : ['application/vnd.ms-excel.addin.macroenabled.12'] 'xlb' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel'] 'xlc' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel'] 'xld' : ['application/excel', 'application/x-excel'] 'xlf' : ['application/x-xliff+xml'] 'xlk' : ['application/excel', 'application/x-excel'] 'xll' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel'] 'xlm' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel'] 'xls' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel', 'application/x-msexcel'] 'xlsb' : ['application/vnd.ms-excel.sheet.binary.macroenabled.12'] 'xlsm' : ['application/vnd.ms-excel.sheet.macroenabled.12'] 'xlsx' : ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'] 'xlt' : ['application/excel', 'application/x-excel'] 'xltm' : ['application/vnd.ms-excel.template.macroenabled.12'] 'xltx' : ['application/vnd.openxmlformats-officedocument.spreadsheetml.template'] 'xlv' : ['application/excel', 'application/x-excel'] 'xlw' : ['application/excel', 'application/vnd.ms-excel', 'application/x-excel', 'application/x-msexcel'] 'xm' : ['audio/xm'] 'xml' : ['application/xml', 'text/xml'] 'xmz' : ['xgl/movie'] 'xo' : ['application/vnd.olpc-sugar'] 'xop' : ['application/xop+xml'] 'xpdl' : ['application/xml'] 'xpi' : ['application/x-xpinstall'] 'xpix' : ['application/x-vnd.ls-xpix'] 'xpl' : ['application/xproc+xml'] 'xpm' : ['image/x-xpixmap', 'image/xpm'] 'xpr' : ['application/vnd.is-xpr'] 'xps' : ['application/vnd.ms-xpsdocument'] 'xpw' : ['application/vnd.intercon.formnet'] 'xpx' : ['application/vnd.intercon.formnet'] 'xsl' : ['application/xml'] 'xslt' : ['application/xslt+xml'] 'xsm' : ['application/vnd.syncml+xml'] 'xspf' : ['application/xspf+xml'] 'xsr' : ['video/x-amt-showrun'] 'xul' : ['application/vnd.mozilla.xul+xml'] 'xvm' : ['application/xv+xml'] 'xvml' : ['application/xv+xml'] 'xwd' : ['image/x-xwd', 'image/x-xwindowdump'] 'xyz' : ['chemical/x-xyz'] 'xz' : ['application/x-xz'] 'yang' : ['application/yang'] 'yin' : ['application/yin+xml'] 'z' : ['application/x-compress', 'application/x-compressed'] 'z1' : ['application/x-zmachine'] 'z2' : ['application/x-zmachine'] 'z3' : ['application/x-zmachine'] 'z4' : ['application/x-zmachine'] 'z5' : ['application/x-zmachine'] 'z6' : ['application/x-zmachine'] 'z7' : ['application/x-zmachine'] 'z8' : ['application/x-zmachine'] 'zaz' : ['application/vnd.zzazz.deck+xml'] 'zip' : ['application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'] 'zir' : ['application/vnd.zul'] 'zirz' : ['application/vnd.zul'] 'zmm' : ['application/vnd.handheld-entertainment+xml'] 'zoo' : ['application/octet-stream'] 'zsh' : ['text/x-script.zsh'] '123' : ['application/vnd.lotus-1-2-3'] module.exports = MimebyFileExtension : byFileExtension
[ { "context": "nsartorio.github.io/jquery-nice-select\n Made by Hernán Sartorio\n###\n\n(($) ->\n\n $.fn.niceSelect = ->\n # Create", "end": 113, "score": 0.9998893141746521, "start": 98, "tag": "NAME", "value": "Hernán Sartorio" } ]
wilbur/coffee/niceselect.coffee
thomasmeagher/Casper
0
### jQuery Nice Select - v1.0 http://hernansartorio.github.io/jquery-nice-select Made by Hernán Sartorio ### (($) -> $.fn.niceSelect = -> # Create custom markup @each -> select = $(this) if !select.next().hasClass('nice-select') select.after '<div class="nice-select ' + (select.attr('class') or '') + (if select.attr('disabled') then 'disabled' else '" tabindex="0') + '"><span class="current"></span><ul class="list"></ul></div>' dropdown = select.next() options = select.find('option') selected = select.find('option:selected') dropdown.find('.current').html selected.data('display') or selected.text() options.each -> display = $(this).data('display') dropdown.find('ul').append '<li class="option ' + (if $(this).is(':selected') then 'selected' else '') + '" data-value="' + $(this).val() + (if display then '" data-display="' + display else '') + '">' + $(this).text() + '</li>' return select.hide() return ### Event listeners ### # Unbind existing events in case that the plugin has been initialized before $(document).off '.nice_select' # Open/close $(document).on 'click.nice_select', '.nice-select', (event) -> dropdown = $(this) $('.nice-select').not(dropdown).removeClass 'open' dropdown.toggleClass 'open' if dropdown.hasClass('open') dropdown.find '.option' dropdown.find('.focus').removeClass 'focus' dropdown.find('.selected').addClass 'focus' else dropdown.focus() return # Close when clicking outside $(document).on 'click.nice_select', (event) -> if $(event.target).closest('.nice-select').length == 0 $('.nice-select').removeClass('open').find '.option' return # Option click $(document).on 'click.nice_select', '.nice-select .option', (event) -> option = $(this) dropdown = option.closest('.nice-select') dropdown.find('.selected').removeClass 'selected' option.addClass 'selected' dropdown.find('.focus').removeClass 'focus' dropdown.find('.selected').addClass 'focus' text = option.data('display') or option.text() dropdown.find('.current').text text dropdown.prev('select').val(option.data('value')).trigger 'change' return # Keyboard events $(document).on 'keydown.nice_select', '.nice-select', (event) -> dropdown = $(this) focused_option = $(dropdown.find('.focus') or dropdown.find('.list .option.selected')) # Space or Enter if event.keyCode == 32 or event.keyCode == 13 if dropdown.hasClass('open') focused_option.trigger 'click' else dropdown.trigger 'click' return false # Down else if event.keyCode == 40 if !dropdown.hasClass('open') dropdown.trigger 'click' else if focused_option.next().length > 0 dropdown.find('.focus').removeClass 'focus' focused_option.next().addClass 'focus' return false # Up else if event.keyCode == 38 if !dropdown.hasClass('open') dropdown.trigger 'click' else if focused_option.prev().length > 0 dropdown.find('.focus').removeClass 'focus' focused_option.prev().addClass 'focus' return false # Esc else if event.keyCode == 27 if dropdown.hasClass('open') dropdown.trigger 'click' # Tab else if event.keyCode == 9 if dropdown.hasClass('open') return false return return return ) jQuery
99263
### jQuery Nice Select - v1.0 http://hernansartorio.github.io/jquery-nice-select Made by <NAME> ### (($) -> $.fn.niceSelect = -> # Create custom markup @each -> select = $(this) if !select.next().hasClass('nice-select') select.after '<div class="nice-select ' + (select.attr('class') or '') + (if select.attr('disabled') then 'disabled' else '" tabindex="0') + '"><span class="current"></span><ul class="list"></ul></div>' dropdown = select.next() options = select.find('option') selected = select.find('option:selected') dropdown.find('.current').html selected.data('display') or selected.text() options.each -> display = $(this).data('display') dropdown.find('ul').append '<li class="option ' + (if $(this).is(':selected') then 'selected' else '') + '" data-value="' + $(this).val() + (if display then '" data-display="' + display else '') + '">' + $(this).text() + '</li>' return select.hide() return ### Event listeners ### # Unbind existing events in case that the plugin has been initialized before $(document).off '.nice_select' # Open/close $(document).on 'click.nice_select', '.nice-select', (event) -> dropdown = $(this) $('.nice-select').not(dropdown).removeClass 'open' dropdown.toggleClass 'open' if dropdown.hasClass('open') dropdown.find '.option' dropdown.find('.focus').removeClass 'focus' dropdown.find('.selected').addClass 'focus' else dropdown.focus() return # Close when clicking outside $(document).on 'click.nice_select', (event) -> if $(event.target).closest('.nice-select').length == 0 $('.nice-select').removeClass('open').find '.option' return # Option click $(document).on 'click.nice_select', '.nice-select .option', (event) -> option = $(this) dropdown = option.closest('.nice-select') dropdown.find('.selected').removeClass 'selected' option.addClass 'selected' dropdown.find('.focus').removeClass 'focus' dropdown.find('.selected').addClass 'focus' text = option.data('display') or option.text() dropdown.find('.current').text text dropdown.prev('select').val(option.data('value')).trigger 'change' return # Keyboard events $(document).on 'keydown.nice_select', '.nice-select', (event) -> dropdown = $(this) focused_option = $(dropdown.find('.focus') or dropdown.find('.list .option.selected')) # Space or Enter if event.keyCode == 32 or event.keyCode == 13 if dropdown.hasClass('open') focused_option.trigger 'click' else dropdown.trigger 'click' return false # Down else if event.keyCode == 40 if !dropdown.hasClass('open') dropdown.trigger 'click' else if focused_option.next().length > 0 dropdown.find('.focus').removeClass 'focus' focused_option.next().addClass 'focus' return false # Up else if event.keyCode == 38 if !dropdown.hasClass('open') dropdown.trigger 'click' else if focused_option.prev().length > 0 dropdown.find('.focus').removeClass 'focus' focused_option.prev().addClass 'focus' return false # Esc else if event.keyCode == 27 if dropdown.hasClass('open') dropdown.trigger 'click' # Tab else if event.keyCode == 9 if dropdown.hasClass('open') return false return return return ) jQuery
true
### jQuery Nice Select - v1.0 http://hernansartorio.github.io/jquery-nice-select Made by PI:NAME:<NAME>END_PI ### (($) -> $.fn.niceSelect = -> # Create custom markup @each -> select = $(this) if !select.next().hasClass('nice-select') select.after '<div class="nice-select ' + (select.attr('class') or '') + (if select.attr('disabled') then 'disabled' else '" tabindex="0') + '"><span class="current"></span><ul class="list"></ul></div>' dropdown = select.next() options = select.find('option') selected = select.find('option:selected') dropdown.find('.current').html selected.data('display') or selected.text() options.each -> display = $(this).data('display') dropdown.find('ul').append '<li class="option ' + (if $(this).is(':selected') then 'selected' else '') + '" data-value="' + $(this).val() + (if display then '" data-display="' + display else '') + '">' + $(this).text() + '</li>' return select.hide() return ### Event listeners ### # Unbind existing events in case that the plugin has been initialized before $(document).off '.nice_select' # Open/close $(document).on 'click.nice_select', '.nice-select', (event) -> dropdown = $(this) $('.nice-select').not(dropdown).removeClass 'open' dropdown.toggleClass 'open' if dropdown.hasClass('open') dropdown.find '.option' dropdown.find('.focus').removeClass 'focus' dropdown.find('.selected').addClass 'focus' else dropdown.focus() return # Close when clicking outside $(document).on 'click.nice_select', (event) -> if $(event.target).closest('.nice-select').length == 0 $('.nice-select').removeClass('open').find '.option' return # Option click $(document).on 'click.nice_select', '.nice-select .option', (event) -> option = $(this) dropdown = option.closest('.nice-select') dropdown.find('.selected').removeClass 'selected' option.addClass 'selected' dropdown.find('.focus').removeClass 'focus' dropdown.find('.selected').addClass 'focus' text = option.data('display') or option.text() dropdown.find('.current').text text dropdown.prev('select').val(option.data('value')).trigger 'change' return # Keyboard events $(document).on 'keydown.nice_select', '.nice-select', (event) -> dropdown = $(this) focused_option = $(dropdown.find('.focus') or dropdown.find('.list .option.selected')) # Space or Enter if event.keyCode == 32 or event.keyCode == 13 if dropdown.hasClass('open') focused_option.trigger 'click' else dropdown.trigger 'click' return false # Down else if event.keyCode == 40 if !dropdown.hasClass('open') dropdown.trigger 'click' else if focused_option.next().length > 0 dropdown.find('.focus').removeClass 'focus' focused_option.next().addClass 'focus' return false # Up else if event.keyCode == 38 if !dropdown.hasClass('open') dropdown.trigger 'click' else if focused_option.prev().length > 0 dropdown.find('.focus').removeClass 'focus' focused_option.prev().addClass 'focus' return false # Esc else if event.keyCode == 27 if dropdown.hasClass('open') dropdown.trigger 'click' # Tab else if event.keyCode == 9 if dropdown.hasClass('open') return false return return return ) jQuery
[ { "context": "\": [{ \"value\": \"1\" }],\n \"name\": {\"given\":[\"John\"], \"family\": [\"Smith\"]},\n \"gender\": \"M\",\n ", "end": 435, "score": 0.9998810291290283, "start": 431, "tag": "NAME", "value": "John" }, { "context": "],\n \"name\": {\"given\":[\"John\"], \"family\": [\"Smith\"]},\n \"gender\": \"M\",\n \"birthDate\" : ", "end": 456, "score": 0.9997951984405518, "start": 451, "tag": "NAME", "value": "Smith" }, { "context": "er\": [{ \"value\": \"2\" }],\n \"name\": {\"given\":[\"Sally\"], \"family\": [\"Smith\"]},\n \"gender\": \"F\",\n ", "end": 966, "score": 0.999722957611084, "start": 961, "tag": "NAME", "value": "Sally" }, { "context": "}],\n \"name\": {\"given\":[\"Sally\"], \"family\": [\"Smith\"]},\n \"gender\": \"F\",\n \"birthDate\" : \"200", "end": 987, "score": 0.9997736215591431, "start": 982, "tag": "NAME", "value": "Smith" } ]
test/elm/executor/patients.coffee
luis1van/cql-execution-1
2
# Born in 1980 module.exports.p1 = { "resourceType": "Bundle", "id": "example1", "meta": { "versionId": "1", "lastUpdated": "2014-08-18T01:43:30Z" }, "base": "http://example.com/base", "entry" : [{ "resource": { "id" : "1", "meta" :{ "profile" : ["patient-qicore-qicore-patient"]}, "resourceType" : "Patient", "identifier": [{ "value": "1" }], "name": {"given":["John"], "family": ["Smith"]}, "gender": "M", "birthDate" : "1980-02-17T06:15"} } ] } # Born in 2007 module.exports.p2 = { "resourceType": "Bundle", "id": "example1", "meta": { "versionId": "1", "lastUpdated": "2014-08-18T01:43:30Z" }, "base": "http://example.com/base", "entry" : [ "resource": { "resourceType" : "Patient", "meta" :{ "profile" : ["patient-qicore-qicore-patient"]}, "id" : "2", "identifier": [{ "value": "2" }], "name": {"given":["Sally"], "family": ["Smith"]}, "gender": "F", "birthDate" : "2007-08-02T11:47" }] }
214887
# Born in 1980 module.exports.p1 = { "resourceType": "Bundle", "id": "example1", "meta": { "versionId": "1", "lastUpdated": "2014-08-18T01:43:30Z" }, "base": "http://example.com/base", "entry" : [{ "resource": { "id" : "1", "meta" :{ "profile" : ["patient-qicore-qicore-patient"]}, "resourceType" : "Patient", "identifier": [{ "value": "1" }], "name": {"given":["<NAME>"], "family": ["<NAME>"]}, "gender": "M", "birthDate" : "1980-02-17T06:15"} } ] } # Born in 2007 module.exports.p2 = { "resourceType": "Bundle", "id": "example1", "meta": { "versionId": "1", "lastUpdated": "2014-08-18T01:43:30Z" }, "base": "http://example.com/base", "entry" : [ "resource": { "resourceType" : "Patient", "meta" :{ "profile" : ["patient-qicore-qicore-patient"]}, "id" : "2", "identifier": [{ "value": "2" }], "name": {"given":["<NAME>"], "family": ["<NAME>"]}, "gender": "F", "birthDate" : "2007-08-02T11:47" }] }
true
# Born in 1980 module.exports.p1 = { "resourceType": "Bundle", "id": "example1", "meta": { "versionId": "1", "lastUpdated": "2014-08-18T01:43:30Z" }, "base": "http://example.com/base", "entry" : [{ "resource": { "id" : "1", "meta" :{ "profile" : ["patient-qicore-qicore-patient"]}, "resourceType" : "Patient", "identifier": [{ "value": "1" }], "name": {"given":["PI:NAME:<NAME>END_PI"], "family": ["PI:NAME:<NAME>END_PI"]}, "gender": "M", "birthDate" : "1980-02-17T06:15"} } ] } # Born in 2007 module.exports.p2 = { "resourceType": "Bundle", "id": "example1", "meta": { "versionId": "1", "lastUpdated": "2014-08-18T01:43:30Z" }, "base": "http://example.com/base", "entry" : [ "resource": { "resourceType" : "Patient", "meta" :{ "profile" : ["patient-qicore-qicore-patient"]}, "id" : "2", "identifier": [{ "value": "2" }], "name": {"given":["PI:NAME:<NAME>END_PI"], "family": ["PI:NAME:<NAME>END_PI"]}, "gender": "F", "birthDate" : "2007-08-02T11:47" }] }
[ { "context": "done) ->\n testUser = new User\n username: 'testUser'\n password: 'testPass'\n email: 'testEma", "end": 329, "score": 0.9995346069335938, "start": 321, "tag": "USERNAME", "value": "testUser" }, { "context": " User\n username: 'testUser'\n password: 'testPass'\n email: 'testEmail'\n testUser.save (err)", "end": 356, "score": 0.9994542598724365, "start": 348, "tag": "PASSWORD", "value": "testPass" }, { "context": " expect testUser.password\n .to.not.eql 'testPass'\n console.log 'reached save condition'\n ", "end": 470, "score": 0.984290361404419, "start": 462, "tag": "PASSWORD", "value": "testPass" }, { "context": "done) ->\n testUser = new User\n username: 'testUser'\n password:'testPass'\n email: 'testEmai", "end": 610, "score": 0.9996083974838257, "start": 602, "tag": "USERNAME", "value": "testUser" }, { "context": "w User\n username: 'testUser'\n password:'testPass'\n email: 'testEmail'\n testUser.save ->\n ", "end": 636, "score": 0.9994543790817261, "start": 628, "tag": "PASSWORD", "value": "testPass" }, { "context": " .yields null, testUser\n\n User.isValidLogin 'testUser', 'testPass', (err, retUser) ->\n expect er", "end": 782, "score": 0.9944889545440674, "start": 774, "tag": "USERNAME", "value": "testUser" }, { "context": " expect retUser.username\n .to.eql 'testUser'\n done()\n", "end": 915, "score": 0.9995495080947876, "start": 907, "tag": "USERNAME", "value": "testUser" } ]
test/models/mdlUserTest.coffee
zodoz/EC2Manager
0
sinon = require 'sinon' chai = require 'chai' expect = chai.expect mongoose = require 'mongoose' mockgoose = require 'mockgoose' User = require '../../src/models/mdlUser' mockgoose mongoose mongoose.connect 'mongodb://localhost/test' describe 'User', -> it '#save', (done) -> testUser = new User username: 'testUser' password: 'testPass' email: 'testEmail' testUser.save (err) -> expect testUser.password .to.not.eql 'testPass' console.log 'reached save condition' done() it '#isValidLogin', (done) -> testUser = new User username: 'testUser' password:'testPass' email: 'testEmail' testUser.save -> sinon.stub User, 'findOne' .yields null, testUser User.isValidLogin 'testUser', 'testPass', (err, retUser) -> expect err .to.be.null expect retUser.username .to.eql 'testUser' done()
211603
sinon = require 'sinon' chai = require 'chai' expect = chai.expect mongoose = require 'mongoose' mockgoose = require 'mockgoose' User = require '../../src/models/mdlUser' mockgoose mongoose mongoose.connect 'mongodb://localhost/test' describe 'User', -> it '#save', (done) -> testUser = new User username: 'testUser' password: '<PASSWORD>' email: 'testEmail' testUser.save (err) -> expect testUser.password .to.not.eql '<PASSWORD>' console.log 'reached save condition' done() it '#isValidLogin', (done) -> testUser = new User username: 'testUser' password:'<PASSWORD>' email: 'testEmail' testUser.save -> sinon.stub User, 'findOne' .yields null, testUser User.isValidLogin 'testUser', 'testPass', (err, retUser) -> expect err .to.be.null expect retUser.username .to.eql 'testUser' done()
true
sinon = require 'sinon' chai = require 'chai' expect = chai.expect mongoose = require 'mongoose' mockgoose = require 'mockgoose' User = require '../../src/models/mdlUser' mockgoose mongoose mongoose.connect 'mongodb://localhost/test' describe 'User', -> it '#save', (done) -> testUser = new User username: 'testUser' password: 'PI:PASSWORD:<PASSWORD>END_PI' email: 'testEmail' testUser.save (err) -> expect testUser.password .to.not.eql 'PI:PASSWORD:<PASSWORD>END_PI' console.log 'reached save condition' done() it '#isValidLogin', (done) -> testUser = new User username: 'testUser' password:'PI:PASSWORD:<PASSWORD>END_PI' email: 'testEmail' testUser.save -> sinon.stub User, 'findOne' .yields null, testUser User.isValidLogin 'testUser', 'testPass', (err, retUser) -> expect err .to.be.null expect retUser.username .to.eql 'testUser' done()
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999157786369324, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/react/profile-page/links.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import ClickToCopy from 'click-to-copy' import * as React from 'react' import { a, div, span } from 'react-dom-factories' el = React.createElement export class Links extends React.PureComponent bn = 'profile-links' rowValue = (value, attributes = {}, modifiers = []) -> if attributes.href? tagName = 'a' modifiers.push 'link' else tagName = 'span' elem = document.createElement(tagName) elem[k] = v for own k, v of attributes elem.className += " #{osu.classWithModifiers "#{bn}__value", modifiers}" elem.innerHTML = value elem.outerHTML linkMapping = twitter: (val) -> icon: 'fab fa-twitter' url: "https://twitter.com/#{val}" text: "@#{val}" discord: (val) -> icon: 'fab fa-discord' text: el ClickToCopy, value: val, showIcon: true interests: -> icon: 'far fa-heart' skype: (val) -> icon: 'fab fa-skype' url: "skype:#{val}?chat" lastfm: (val) -> icon: 'fab fa-lastfm' url: "https://last.fm/user/#{val}" location: -> icon: 'fas fa-map-marker-alt' occupation: -> icon: 'fas fa-suitcase' website: (val) -> icon: 'fas fa-link' url: val text: val.replace(/^https?:\/\//, '') textMapping = join_date: (val) -> joinDate = moment(val) joinDateTitle = joinDate.toISOString() if joinDate.isBefore moment.utc([2008]) title: joinDateTitle extraClasses: 'js-tooltip-time' html: osu.trans 'users.show.first_members' else html: osu.trans 'users.show.joined_at', date: rowValue joinDate.format(osu.trans('common.datetime.year_month.moment')), className: 'js-tooltip-time' title: joinDateTitle last_visit: (val, user) -> return html: osu.trans('users.show.lastvisit_online') if user.is_online html: osu.trans 'users.show.lastvisit', date: rowValue osu.timeago(val) playstyle: (val) -> playsWith = val.map (s) -> osu.trans "common.device.#{s}" .join ', ' html: osu.trans 'users.show.plays_with', devices: rowValue(playsWith) post_count: (val, user) -> count = osu.transChoice 'users.show.post_count.count', osu.formatNumber(val) url = laroute.route('users.posts', user: user.id) html: osu.trans 'users.show.post_count._', link: rowValue(count, href: url) render: => rows = [ ['join_date', 'last_visit', 'playstyle', 'post_count'].map @renderText ['location', 'interests', 'occupation'].map @renderLink ['twitter', 'discord', 'skype', 'lastfm', 'website'].map @renderLink ] div className: bn, for row, j in rows when _.compact(row).length > 0 div key: j, className: "#{bn}__row #{bn}__row--#{j}", row renderLink: (key) => value = @props.user[key] return unless value? {url, icon, text, title} = linkMapping[key](value) title ?= osu.trans "users.show.info.#{key}" text ?= value componentClass = "#{bn}__value" if url? component = a componentClass += " #{bn}__value--link" else component = span div className: "#{bn}__item" key: key span className: "#{bn}__icon" title: title span className: "fa-fw #{icon}" component href: url className: componentClass text renderText: (key) => value = @props.user[key] return unless value? {extraClasses, html, title} = textMapping[key](value, @props.user) div className: "#{bn}__item #{extraClasses ? ''}" key: key title: title dangerouslySetInnerHTML: __html: html
75922
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import ClickToCopy from 'click-to-copy' import * as React from 'react' import { a, div, span } from 'react-dom-factories' el = React.createElement export class Links extends React.PureComponent bn = 'profile-links' rowValue = (value, attributes = {}, modifiers = []) -> if attributes.href? tagName = 'a' modifiers.push 'link' else tagName = 'span' elem = document.createElement(tagName) elem[k] = v for own k, v of attributes elem.className += " #{osu.classWithModifiers "#{bn}__value", modifiers}" elem.innerHTML = value elem.outerHTML linkMapping = twitter: (val) -> icon: 'fab fa-twitter' url: "https://twitter.com/#{val}" text: "@#{val}" discord: (val) -> icon: 'fab fa-discord' text: el ClickToCopy, value: val, showIcon: true interests: -> icon: 'far fa-heart' skype: (val) -> icon: 'fab fa-skype' url: "skype:#{val}?chat" lastfm: (val) -> icon: 'fab fa-lastfm' url: "https://last.fm/user/#{val}" location: -> icon: 'fas fa-map-marker-alt' occupation: -> icon: 'fas fa-suitcase' website: (val) -> icon: 'fas fa-link' url: val text: val.replace(/^https?:\/\//, '') textMapping = join_date: (val) -> joinDate = moment(val) joinDateTitle = joinDate.toISOString() if joinDate.isBefore moment.utc([2008]) title: joinDateTitle extraClasses: 'js-tooltip-time' html: osu.trans 'users.show.first_members' else html: osu.trans 'users.show.joined_at', date: rowValue joinDate.format(osu.trans('common.datetime.year_month.moment')), className: 'js-tooltip-time' title: joinDateTitle last_visit: (val, user) -> return html: osu.trans('users.show.lastvisit_online') if user.is_online html: osu.trans 'users.show.lastvisit', date: rowValue osu.timeago(val) playstyle: (val) -> playsWith = val.map (s) -> osu.trans "common.device.#{s}" .join ', ' html: osu.trans 'users.show.plays_with', devices: rowValue(playsWith) post_count: (val, user) -> count = osu.transChoice 'users.show.post_count.count', osu.formatNumber(val) url = laroute.route('users.posts', user: user.id) html: osu.trans 'users.show.post_count._', link: rowValue(count, href: url) render: => rows = [ ['join_date', 'last_visit', 'playstyle', 'post_count'].map @renderText ['location', 'interests', 'occupation'].map @renderLink ['twitter', 'discord', 'skype', 'lastfm', 'website'].map @renderLink ] div className: bn, for row, j in rows when _.compact(row).length > 0 div key: j, className: "#{bn}__row #{bn}__row--#{j}", row renderLink: (key) => value = @props.user[key] return unless value? {url, icon, text, title} = linkMapping[key](value) title ?= osu.trans "users.show.info.#{key}" text ?= value componentClass = "#{bn}__value" if url? component = a componentClass += " #{bn}__value--link" else component = span div className: "#{bn}__item" key: key span className: "#{bn}__icon" title: title span className: "fa-fw #{icon}" component href: url className: componentClass text renderText: (key) => value = @props.user[key] return unless value? {extraClasses, html, title} = textMapping[key](value, @props.user) div className: "#{bn}__item #{extraClasses ? ''}" key: key title: title dangerouslySetInnerHTML: __html: html
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import ClickToCopy from 'click-to-copy' import * as React from 'react' import { a, div, span } from 'react-dom-factories' el = React.createElement export class Links extends React.PureComponent bn = 'profile-links' rowValue = (value, attributes = {}, modifiers = []) -> if attributes.href? tagName = 'a' modifiers.push 'link' else tagName = 'span' elem = document.createElement(tagName) elem[k] = v for own k, v of attributes elem.className += " #{osu.classWithModifiers "#{bn}__value", modifiers}" elem.innerHTML = value elem.outerHTML linkMapping = twitter: (val) -> icon: 'fab fa-twitter' url: "https://twitter.com/#{val}" text: "@#{val}" discord: (val) -> icon: 'fab fa-discord' text: el ClickToCopy, value: val, showIcon: true interests: -> icon: 'far fa-heart' skype: (val) -> icon: 'fab fa-skype' url: "skype:#{val}?chat" lastfm: (val) -> icon: 'fab fa-lastfm' url: "https://last.fm/user/#{val}" location: -> icon: 'fas fa-map-marker-alt' occupation: -> icon: 'fas fa-suitcase' website: (val) -> icon: 'fas fa-link' url: val text: val.replace(/^https?:\/\//, '') textMapping = join_date: (val) -> joinDate = moment(val) joinDateTitle = joinDate.toISOString() if joinDate.isBefore moment.utc([2008]) title: joinDateTitle extraClasses: 'js-tooltip-time' html: osu.trans 'users.show.first_members' else html: osu.trans 'users.show.joined_at', date: rowValue joinDate.format(osu.trans('common.datetime.year_month.moment')), className: 'js-tooltip-time' title: joinDateTitle last_visit: (val, user) -> return html: osu.trans('users.show.lastvisit_online') if user.is_online html: osu.trans 'users.show.lastvisit', date: rowValue osu.timeago(val) playstyle: (val) -> playsWith = val.map (s) -> osu.trans "common.device.#{s}" .join ', ' html: osu.trans 'users.show.plays_with', devices: rowValue(playsWith) post_count: (val, user) -> count = osu.transChoice 'users.show.post_count.count', osu.formatNumber(val) url = laroute.route('users.posts', user: user.id) html: osu.trans 'users.show.post_count._', link: rowValue(count, href: url) render: => rows = [ ['join_date', 'last_visit', 'playstyle', 'post_count'].map @renderText ['location', 'interests', 'occupation'].map @renderLink ['twitter', 'discord', 'skype', 'lastfm', 'website'].map @renderLink ] div className: bn, for row, j in rows when _.compact(row).length > 0 div key: j, className: "#{bn}__row #{bn}__row--#{j}", row renderLink: (key) => value = @props.user[key] return unless value? {url, icon, text, title} = linkMapping[key](value) title ?= osu.trans "users.show.info.#{key}" text ?= value componentClass = "#{bn}__value" if url? component = a componentClass += " #{bn}__value--link" else component = span div className: "#{bn}__item" key: key span className: "#{bn}__icon" title: title span className: "fa-fw #{icon}" component href: url className: componentClass text renderText: (key) => value = @props.user[key] return unless value? {extraClasses, html, title} = textMapping[key](value, @props.user) div className: "#{bn}__item #{extraClasses ? ''}" key: key title: title dangerouslySetInnerHTML: __html: html
[ { "context": "sions to the PostScript language\n\t# file:///Users/Alhadis/Forks/GhostScript/doc/Language.htm#Additional_ope", "end": 12423, "score": 0.6912538409233093, "start": 12416, "tag": "NAME", "value": "Alhadis" } ]
grammars/postscript.cson
Alhadis/Atom-PostScriptPreview
1
name: "PostScript" scopeName: "source.postscript" fileTypes: [ "ps" "eps", "epsf", "epsi" "gsf", "pfa", "pfb", "t1", "t42" "ai", "aia", "pdf" "joboptions" "AIAppResources" "Adobe Illustrator Cloud Prefs" "Adobe Illustrator Prefs" "Tools Panel Presets" "cidfmap", "Fontmap", "Fontmap.GS", "xlatmap" "PPI_CUtils", "Pscript5Idiom" ] firstLineMatch: """(?x) # Signature \\A%(?:!|PDF) | # Adobe Illustrator preferences \\A/(?:Menus|collection1)\\ {(?:\\r|$) | # Best guess for extensionless files distributed with GhostScript (?i:\\A%+\\s+Copyright\\s+\\(C\\)\\s+([-\\d]+),?\\s+Artifex\\sSoftware\\b) | # Hashbang ^\\#!.*(?:\\s|\\/|(?<=!)\\b) gs (?:$|\\s) | # Modeline (?i: # Emacs -\\*-(?:\\s*(?=[^:;\\s]+\\s*-\\*-)|(?:.*?[;\\s]|(?<=-\\*-))mode\\s*:\\s*) (?:ps|postscript) (?=[\\s;]|(?<![-*])-\\*-).*?-\\*- | # Vim (?:(?:\\s|^)vi(?:m[<=>]?\\d+|m)?|\\sex)(?=:(?=\\s*set?\\s[^\\n:]+:)|:(?!\\s* set?\\s)) (?:(?:\\s|\\s*:\\s*)\\w*(?:\\s*=(?:[^\\n\\\\\\s]|\\\\.)*)?)*[\\s:] (?:filetype|ft|syntax)\\s*= postscr(?:ipt)? (?=\\s|:|$) ) """ foldingStartMarker: "(?:{|<<|^stream)\\s*$" foldingStopMarker: "(?:}|>>|^end(?:stream|obj))" limitLineLength: no maxTokensPerLine: 1000 patterns: [{ name: "meta.document.pdf" begin: "\\A(?=%PDF)" end: "(?=A)B" patterns: [include: "#main"] },{ name: "meta.ai-prefs.postscript" begin: "\\A(?=/(?:(?:Menus|collection1|precision) {|textImportantVisualLinesSnapping \\d)(?:\\r|$))" end: "(?=A)B" patterns: [include: "#main"] }, include: "#main"] # Corrections for faux-PostScript highlighting injections: # Adobe Illustrator preferences "L:source.postscript meta.ai-prefs.postscript - (comment | string | source.embedded | text.embedded)": patterns: [{ # /hexEncodedSetting [ length … hex-bytes ] name: "meta.obfuscated-setting.ai-prefs.postscript" begin: "^\\s*(/(?:\\\\.|[^()<>\\[\\]{}/%\\s])*) ((\\[) (?!0\\b)(\\d+)(?:$|\\r))" end: "^\\s*(\\])|\\G(?!$)|(?!\\G)^(?!\\s*(?:\\]|[A-Fa-f0-9]+$))" contentName: "meta.array.postscript" beginCaptures: 1: patterns: [include: "$self"] 2: name: "meta.array.postscript" 3: name: "punctuation.definition.array.begin.postscript" 4: name: "constant.numeric.postscript" endCaptures: 0: name: "meta.array.postscript" 1: name: "punctuation.definition.array.end.postscript" patterns: [{ name: "string.other.hexadecimal.postscript" match: "[A-Fa-f0-9]+" }] },{ # /This\ escape\ sequence\ syntax\ doesn't\ normally\ work name: "variable.other.constant.literal.postscript" match: "(/)((?:\\\\.|[^()<>\\[\\]{}/%\\s])*)" captures: 1: name: "punctuation.definition.name.postscript" 2: patterns: [{ name: "constant.character.escape.postscript" match: "(\\\\)." captures: 1: name: "punctuation.definition.escape.backslash.postscript" }] },{ # Presumably a long integer: 65535L name: "constant.numeric.integer.long.postscript" match: "[0-9]+L" }] # PDF-specific elements "L:source.postscript meta.document.pdf - (meta.encrypted-source | source.embedded | text.embedded)": patterns: [{ # Binary streams name: "meta.encrypted-source.stream.pdf" begin: "(?:^|(?<=>>)\\s*)(?=stream$)" end: "endstream|(?=endobj\\b)" endCaptures: 0: name: "keyword.control.stream.end.pdf" patterns: [{ begin: "\\G(stream)\\s*$\\s*" end: "(?=endstream|(?=endobj\\b))" beginCaptures: 1: name: "keyword.control.stream.begin.pdf" patterns: [{ # Those weird-ass XML chunks Adobe Illustrator uses begin: "(<\\?xpacket(?=\\s)[^>]+\\?>)(?=$|<x:xmpmeta)" end: "(<\\?xpacket(?=\\s)[^>]*end\\b[^>]*\\?>)|(?=\\s*(?:endstream|endobj\\b))" beginCaptures: 1: name: "text.embedded.xml", patterns: [include: "text.xml"] endCaptures: 1: name: "text.embedded.xml", patterns: [include: "text.xml"] contentName: "text.embedded.xml" patterns: [include: "text.xml"] },{ # Ascii85 name: "string.other.base85.pdf" begin: "(?!endstream)[!-uz]{50,80}\\s*$" end: "~>|(?=\\s*(?:endstream|endobj\\b))" endCaptures: 0: name: "punctuation.definition.string.end.pdf" },{ # Raw binary name: "string.other.raw.binary.pdf" begin: "(?!endstream|[!-uz]{50,80}\\s*$)(?:(?<=[\\n\\r]|\\G|^))(?=.)" end: "(?=\\s*(?:endstream|endobj\\b))" contentName: "sublimelinter.gutter-mark" }] }] },{ # Objects match: "(?<![^/\\s{}()<>\\[\\]%])\\b(obj)\\s*(?=<<|$)|(?<=^|\\n|>>)(endobj)" captures: 1: name: "keyword.control.object.begin.pdf" 2: name: "keyword.control.object.end.pdf" },{ # Trailer name: "keyword.control.$1.pdf" match: "(?<![^/\\s{}()<>\\[\\]%])\\b(trailer|startxref)(?![^/\\s{}()<>\\[\\]%])" }] repository: main: patterns: [ {include: "#string"} {include: "#comment"} {include: "#dictionary"} {include: "#array"} {include: "#procedure"} {include: "#base85"} {include: "#hex"} {include: "#radix"} {include: "#number"} {include: "#embedded"} {include: "#operators"} {include: "#extensions"} {include: "#embeddedRow"} {include: "#names"} ] # [ … ] array: name: "meta.array.postscript" begin: "\\[" end: "\\]" beginCaptures: 0: name: "punctuation.definition.array.begin.postscript" endCaptures: 0: name: "punctuation.definition.array.end.postscript" patterns: [include: "#main"] # Ascii85-encoded data: <~ … ~> base85: name: "string.other.base85.postscript" begin: "<~" end: "~>" beginCaptures: 0: name: "punctuation.definition.string.begin.postscript" endCaptures: 0: name: "punctuation.definition.string.end.postscript" patterns: [ name: "invalid.illegal.base85.char.postscript" match: "(?:[^!-uz\\s]|~(?!>))++" ] # % Commented line comment: patterns: [ # XXX: Not sure why TextMate tokenises this, but I guess I will too name: "punctuation.whitespace.comment.leading.postscript" match: "^[ \\t]+(?=%)" # %%DSC: Document Structuring Conventions {include: "#dsc"} # % Comment name: "comment.line.percentage.postscript" begin: "%" end: "(?=$|\\r|\\f)" beginCaptures: 0: name: "punctuation.definition.comment.postscript" ] # << … >> dictionary: name: "meta.dictionary.postscript" begin: "<<" end: ">>" beginCaptures: 0: name: "punctuation.definition.dictionary.begin.postscript" endCaptures: 0: name: "punctuation.definition.dictionary.end.postscript" patterns: [include: "#main"] # Document Structuring Convention dsc: name: "meta.Document-Structuring-Comment.postscript" beginCaptures: 0: name: "keyword.other.DSC.postscript" 1: name: "punctuation.definition.keyword.DSC.postscript" 3: name: "keyword.operator.assignment.key-value.colon.postscript" contentName: "string.unquoted.DSC.postscript" begin: """(?x) ^ (%%) ( BeginBinary | BeginCustomColor | BeginData | BeginDefaults | BeginDocument | BeginEmulation | BeginExitServer | BeginFeature | BeginFile | BeginFont | BeginObject | BeginPageSetup | BeginPaperSize | BeginPreview | BeginProcSet | BeginProcessColor | BeginProlog | BeginResource | BeginSetup | BoundingBox | CMYKCustomColor | ChangeFont | Copyright | CreationDate | Creator | DocumentCustomColors | DocumentData | DocumentFonts | DocumentMedia | DocumentNeededFiles | DocumentNeededFonts | DocumentNeededProcSets | DocumentNeededResources | DocumentPaperColors | DocumentPaperForms | DocumentPaperSizes | DocumentPaperWeights | DocumentPrinterRequired | DocumentProcSets | DocumentProcessColors | DocumentSuppliedFiles | DocumentSuppliedFonts | DocumentSuppliedProcSets | DocumentSuppliedResources | EOF | Emulation | EndBinary | EndComments | EndCustomColor | EndData | EndDefaults | EndDocument | EndEmulation | EndExitServer | EndFeature | EndFile | EndFont | EndObject | EndPageSetup | EndPaperSize | EndPreview | EndProcSet | EndProcessColor | EndProlog | EndResource | EndSetup | ExecuteFile | Extensions | Feature | For | IncludeDocument | IncludeFeature | IncludeFile | IncludeFont | IncludeProcSet | IncludeResource | LanguageLevel | OperatorIntervention | OperatorMessage | Orientation | PageBoundingBox | PageCustomColors | PageFiles | PageFonts | PageMedia | PageOrder | PageOrientation | PageProcessColors | PageRequirements | PageResources | PageTrailer | Pages | Page | PaperColor | PaperForm | PaperSize | PaperWeight | ProofMode | RGBCustomColor | Requirements | Routing | Title | Trailer | VMlocation | VMusage | Version | \\+ | \\?BeginFeatureQuery | \\?BeginFileQuery | \\?BeginFontListQuery | \\?BeginFontQuery | \\?BeginPrinterQuery | \\?BeginProcSetQuery | \\?BeginQuery | \\?BeginResourceListQuery | \\?BeginResourceQuery | \\?BeginVMStatus | \\?EndFeatureQuery | \\?EndFileQuery | \\?EndFontListQuery | \\?EndFontQuery | \\?EndPrinterQuery | \\?EndProcSetQuery | \\?EndQuery | \\?EndResourceListQuery | \\?EndResourceQuery | \\?EndVMStatus ) (:)? [^\\S\\r\\n]* """ end: "(?=$|\\r|\\f)" # Encrypted PostScript sections embedded: patterns: [{ # `readline` from `currentfile` contentName: "string.unquoted.heredoc.postscript" begin: "(?<![^/\\s{}()<>\\[\\]%])\\b(currentfile)\\s+((?=\\S)[^{}%]+?)\\s+(readline)(?!\\s*})\\b(?![^/\\s{}()<>\\[\\]%])(?:$\\s*)?" end: "(?!\\G)$" beginCaptures: 1: name: "keyword.operator.postscript" 2: patterns: [include: "#main"] 3: name: "keyword.operator.postscript" },{ # Base85-encoded name: "meta.encrypted-source.base85.postscript" begin: "(?<![^/\\s{}()<>\\[\\]%])\\b(currentfile)\\s*((/)ASCII85Decode)\\s+(filter)\\b(?![^/\\s{}()<>\\[\\]%])([^}>\\]%]*?(?:exec|image|readstring)\\s*)$\\s*+" end: "~>|(?=cleartomark|closefile)" contentName: "string.other.base85.postscript" beginCaptures: 1: name: "keyword.operator.postscript" 2: name: "variable.other.literal.postscript" 3: name: "punctuation.definition.name.postscript" 4: name: "keyword.operator.postscript" 5: patterns: [include: "#main"] endCaptures: 0: name: "punctuation.definition.string.end.postscript" },{ # `eexec` encryption, typically found only in Type 1 font programs name: "meta.encrypted-source.eexec.postscript" begin: "(?<![^/\\s{}()<>\\[\\]%])\\b(currentfile)\\s+(eexec)(?:$|(?=.*[\\0-\\x08\\x14-\\x31\\x7F\\x80-\\x9F])(?=.{0,3}?[^A-Fa-f0-9]|\\b[A-Fa-f0-9]))" end: "(cleartomark|closefile)\\b(?![^/\\s{}()<>\\[\\]%])|(?<=\\G)(?=[^\\s0-9A-Fa-f])" beginCaptures: 1: name: "keyword.operator.postscript" 2: name: "keyword.operator.postscript" endCaptures: 1: name: "keyword.operator.postscript" patterns: [{ begin: "\\G(?=\\s*$)" end: "(?=\\s*\\S)" },{ begin: "(?:\\G|(?<=\\n|^))\\s*(?=\\S)" end: "(?!\\G)" patterns: [{ # Raw binary # - TODO: Find out how PostScript engines differentiate between a # procedure named `eexecute` and `eexec` followed by raw binary. name: "string.other.raw.binary.postscript" begin: "\\G(?!cleartomark|closefile)(?=.{0,3}?[^A-Fa-f0-9])" end: "(?=\\s*(?:cleartomark|closefile))" contentName: "sublimelinter.gutter-mark" },{ # Hexadecimal name: "string.other.hexadecimal.postscript" begin: "\\G(?!cleartomark|closefile)(?=\\s{0,3}?(?:[A-Fa-f0-9]))" end: "(?=\\s*[^A-Fa-f0-9\\s]|cleartomark|closefile)" }] }] }] # Lines of obvious-looking Ascii85-encoded data embeddedRow: patterns: [{ name: "string.other.base85.postscript" match: "^[!-uz]{0,78}(~>)" captures: 1: name: "punctuation.definition.string.end.postscript" },{ name: "string.other.base85.postscript" begin: """(?x) ^ (?= [^%\\[]*? \\] | [^%(]*? \\) | [^%<]*? > | .*? <(?!~|<) [A-Fa-f0-9]* [^~>A-Fa-f0-9] ) [!-uz]{60,80} [^\\S\\r\\n]* $ """ end: "^[!-uz]{0,78}(~>)" endCaptures: 0: name: "punctuation.definition.string.end.postscript" }] # GhostScript extensions to the PostScript language # file:///Users/Alhadis/Forks/GhostScript/doc/Language.htm#Additional_operators extensions: name: "keyword.operator.ghostscript.postscript" match: """(?x) (?<![^/\\s{}()<>\\[\\]%]) (?:\\b|(?=\\.)) ( \\.activatepathcontrol | \\.addcontrolpath | \\.begintransparencygroup | \\.begintransparencymaskgroup | \\.bind | \\.bindnow | \\.currentalphaisshape | \\.currentblendmode | \\.currentfillconstantalpha | \\.currentopacityalpha | \\.currentoverprintmode | \\.currentpathcontrolstate | \\.currentshapealpha | \\.currentstrokeconstantalpha | \\.currenttextknockout | \\.dicttomark | \\.endtransparencygroup | \\.endtransparencymask | \\.fileposition | \\.genordered | \\.knownget | \\.locksafe | \\.popdf14devicefilter | \\.pushpdf14devicefilter | \\.setalphaisshape | \\.setblendmode | \\.setdebug | \\.setfillconstantalpha | \\.setopacityalpha | \\.setoverprintmode | \\.setsafe | \\.setshapealpha | \\.setstrokeconstantalpha | \\.settextknockout | \\.shellarguments | \\.tempfile | %Type1BuildChar | %Type1BuildGlyph | arccos | arcsin | copydevice | copyscanlines | currentdevice | finddevice | findlibfile | findprotodevice | getdeviceprops | getenv | makeimagedevice | max | min | putdeviceprops | setdevice ) \\b (?![^/\\s{}()<>\\[\\]%]) """ # Hexadecimal data: < … > hex: name: "string.other.hexadecimal.postscript" begin: "<" end: ">" beginCaptures: 0: name: "punctuation.definition.string.begin.postscript" endCaptures: 0: name: "punctuation.definition.string.end.postscript" patterns: [ name: "invalid.illegal.hexadecimal.char.postscript" match: "[^>0-9A-Fa-f\\s]+" ] # Name objects names: patterns: [{ # //Immediately Evaluated Name name: "variable.other.constant.immediately-evaluated.postscript" match: "(//)[^()<>\\[\\]{}/%\\s]*" captures: 1: name: "punctuation.definition.name.postscript" },{ # /Literal name: "variable.other.constant.literal.postscript" match: "(/)[^()<>\\[\\]{}/%\\s]*" captures: 1: name: "punctuation.definition.name.postscript" },{ # Executable name: "variable.other.executable.postscript" match: "[^()<>\\[\\]{}/%\\s]+" }] # Integers and floating-points number: name: "constant.numeric.postscript" match: "[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[Ee][-+]?\\d+)?(?=$|[\\s\\[\\]{}(/%<])" # Built-ins operators: patterns: [{ # LanguageLevel 3 name: "keyword.operator.level-3.postscript" match: """(?x) (?<![^/\\s{}()<>\\[\\]%]) \\b ( GetHalftoneName | GetPageDeviceName | GetSubstituteCRD | StartData | StartData | addglyph | beginbfchar | beginbfrange | begincidchar | begincidrange | begincmap | begincodespacerange | beginnotdefchar | beginnotdefrange | beginrearrangedfont | beginusematrix | cliprestore | clipsave | composefont | currentsmoothness | currenttrapparams | endbfchar | endbfrange | endcidchar | endcidrange | endcmap | endcodespacerange | endnotdefchar | endnotdefrange | endrearrangedfont | endusematrix | findcolorrendering | removeall | removeglyphs | setsmoothness | settrapparams | settrapzone | shfill | usecmap | usefont ) \\b (?![^/\\s{}()<>\\[\\]%]) """ },{ # LanguageLevel 2 name: "keyword.operator.level-2.postscript" match: """(?x) (?<![^/\\s{}()<>\\[\\]%]) \\b ( GlobalFontDirectory | ISOLatin1Encoding | SharedFontDirectory | UserObjects | arct | colorimage | configurationerror | cshow | currentblackgeneration | currentcacheparams | currentcmykcolor | currentcolorrendering | currentcolorscreen | currentcolorspace | currentcolortransfer | currentcolor | currentdevparams | currentglobal | currentgstate | currenthalftone | currentobjectformat | currentoverprint | currentpacking | currentpagedevice | currentshared | currentstrokeadjust | currentsystemparams | currentundercolorremoval | currentuserparams | defineresource | defineuserobject | deletefile | execform | execuserobject | filenameforall | fileposition | filter | findencoding | findresource | gcheck | globaldict | glyphshow | gstate | ineofill | infill | instroke | inueofill | inufill | inustroke | languagelevel | makepattern | packedarray | printobject | product | realtime | rectclip | rectfill | rectstroke | renamefile | resourceforall | resourcestatus | revision | rootfont | scheck | selectfont | serialnumber | setbbox | setblackgeneration | setcachedevice2 | setcacheparams | setcmykcolor | setcolorrendering | setcolorscreen | setcolorspace | setcolortransfer | setcolor | setdevparams | setfileposition | setglobal | setgstate | sethalftone | setobjectformat | setoverprint | setpacking | setpagedevice | setpattern | setshared | setstrokeadjust | setsystemparams | setucacheparams | setundercolorremoval | setuserparams | setvmthreshold | shareddict | startjob | uappend | ucachestatus | ucache | ueofill | ufill | undefinedresource | undefinefont | undefineresource | undefineuserobject | undef | upath | ustrokepath | ustroke | vmreclaim | writeobject | xshow | xyshow | yshow ) \\b (?![^/\\s{}()<>\\[\\]%]) """ },{ # LanguageLevel 1 name: "keyword.operator.level-1.postscript" match: """(?x) (?<![^/\\s{}()<>\\[\\]%]) \\b ( FontDirectory | StandardEncoding | VMerror | abs | add | aload | anchorsearch | and | arcn | arcto | arc | array | ashow | astore | atan | awidthshow | begin | bind | bitshift | bytesavailable | cachestatus | ceiling | charpath | cleardictstack | cleartomark | clear | clippath | clip | closefile | closepath | colorimage | concatmatrix | concat | condition | copypage | copy | cos | countdictstack | countexecstack | counttomark | count | currentcontext | currentdash | currentdict | currentfile | currentflat | currentfont | currentgray | currenthalftonephase | currenthsbcolor | currentlinecap | currentlinejoin | currentlinewidth | currentmatrix | currentmiterlimit | currentpoint | currentrgbcolor | currentscreen | currenttransfer | curveto | cvi | cvlit | cvn | cvrs | cvr | cvs | cvx | defaultmatrix | definefont | defineusername | def | detach | deviceinfo | dictfull | dictstackoverflow | dictstackunderflow | dictstack | dict | div | dtransform | dup | echo | eexec | end | eoclip | eofill | eoviewclip | eq | erasepage | errordict | exch | execstackoverflow | execstack | executeonly | executive | exec | exitserver | exit | exp | false | file | fill | findfont | flattenpath | floor | flushfile | flush | forall | fork | for | getinterval | get | ge | grestoreall | grestore | gsave | gt | handleerror | identmatrix | idiv | idtransform | ifelse | if | imagemask | image | index | initclip | initgraphics | initmatrix | initviewclip | internaldict | interrupt | invalidaccess | invalidcontext | invalidexit | invalidfileaccess | invalidfont | invalidid | invalidrestore | invertmatrix | ioerror | itransform | known | kshow | length | le | limitcheck | lineto | ln | load | lock | log | loop | lt | makefont | mark | matrix | maxlength | mod | monitor | moveto | mul | neg | newpath | ne | noaccess | nocurrentpoint | notify | not | nulldevice | null | or | pathbbox | pathforall | pdfmark | pop | print | prompt | pstack | putinterval | put | quit | rand | rangecheck | rcheck | rcurveto | readhexstring | readline | readonly | readstring | read | rectviewclip | repeat | resetfile | restore | reversepath | rlineto | rmoveto | roll | rotate | round | rrand | run | save | scalefont | scale | search | serverdict | setcachedevice | setcachelimit | setcharwidth | setdash | setflat | setfont | setgray | sethalftonephase | sethsbcolor | setlinecap | setlinejoin | setlinewidth | setmatrix | setmiterlimit | setrgbcolor | setscreen | settransfer | showpage | show | sin | sqrt | srand | stackoverflow | stackunderflow | stack | start | statusdict | status | stopped | stop | store | stringwidth | string | strokepath | stroke | sub | syntaxerror | systemdict | timeout | token | transform | translate | true | truncate | typecheck | type | undefinedfilename | undefinedresult | undefined | unmatchedmark | unregistered | userdict | usertime | version | viewclippath | viewclip | vmstatus | wait | wcheck | where | widthshow | writehexstring | writestring | write | wtranslation | xcheck | xor | yield ) \\b (?![^/\\s{}()<>\\[\\]%]) | # Stuff that starts with a non-word character (?<=^|[/\\s{}()<>\\[\\]%]) (=?=|\\$error) (?=$|[/\\s{}()<>\\[\\]%]) """ }] # Procedure/subroutine procedure: name: "meta.procedure.postscript" begin: "{" end: "}" beginCaptures: 0: name: "punctuation.definition.procedure.begin.postscript" endCaptures: 0: name: "punctuation.definition.procedure.end.postscript" patterns: [include: "#main"] # Number with explicit radix radix: name: "constant.numeric.radix.postscript" match: "[0-3]?[0-9]#[0-9a-zA-Z]+" # “Special” files specialFiles: patterns: [{ # %device%file name: "constant.language.device-name.$2-device.postscript" match: "\\G(%)([-\\w]+)(?=%|\\)|$)(%)?" captures: 1: name: "punctuation.definition.device-name.begin.postscript" 3: name: "punctuation.definition.device-name.end.postscript" },{ # Usual stdio(3) streams name: "constant.language.special-file.stdio.$2.postscript" match: "\\G(%)(stderr|stdin|stdout)(?=\\)|$)" captures: 1: name: "punctuation.definition.special-file.begin.postscript" 3: name: "punctuation.definition.special-file.end.postscript" },{ # Special files related to interactive execution name: "constant.language.special-file.interactive.$2.postscript" match: "\\G(%)(lineedit|statementedit)(?=\\)|$)" captures: 1: name: "punctuation.definition.special-file.begin.postscript" 3: name: "punctuation.definition.special-file.end.postscript" }] # (Strings (denoted by (balanced) (brackets))) string: name: "string.other.postscript" begin: "\\(" end: "\\)" beginCaptures: 0: name: "punctuation.definition.string.begin.postscript" endCaptures: 0: name: "punctuation.definition.string.end.postscript" patterns: [include: "#stringInnards"] stringInnards: patterns: [{ include: "#specialFiles" },{ name: "constant.numeric.octal.postscript" match: "\\\\[0-7]{1,3}" },{ name: "constant.character.escape.postscript" match: "\\\\(\\\\|[bfnrt()]|[0-7]{1,3}|\\r?\\n)" },{ name: "invalid.illegal.unknown-escape.postscript.ignored" match: "\\\\" },{ begin: "\\(" end: "\\)" patterns: [include: "#stringInnards"] }]
57503
name: "PostScript" scopeName: "source.postscript" fileTypes: [ "ps" "eps", "epsf", "epsi" "gsf", "pfa", "pfb", "t1", "t42" "ai", "aia", "pdf" "joboptions" "AIAppResources" "Adobe Illustrator Cloud Prefs" "Adobe Illustrator Prefs" "Tools Panel Presets" "cidfmap", "Fontmap", "Fontmap.GS", "xlatmap" "PPI_CUtils", "Pscript5Idiom" ] firstLineMatch: """(?x) # Signature \\A%(?:!|PDF) | # Adobe Illustrator preferences \\A/(?:Menus|collection1)\\ {(?:\\r|$) | # Best guess for extensionless files distributed with GhostScript (?i:\\A%+\\s+Copyright\\s+\\(C\\)\\s+([-\\d]+),?\\s+Artifex\\sSoftware\\b) | # Hashbang ^\\#!.*(?:\\s|\\/|(?<=!)\\b) gs (?:$|\\s) | # Modeline (?i: # Emacs -\\*-(?:\\s*(?=[^:;\\s]+\\s*-\\*-)|(?:.*?[;\\s]|(?<=-\\*-))mode\\s*:\\s*) (?:ps|postscript) (?=[\\s;]|(?<![-*])-\\*-).*?-\\*- | # Vim (?:(?:\\s|^)vi(?:m[<=>]?\\d+|m)?|\\sex)(?=:(?=\\s*set?\\s[^\\n:]+:)|:(?!\\s* set?\\s)) (?:(?:\\s|\\s*:\\s*)\\w*(?:\\s*=(?:[^\\n\\\\\\s]|\\\\.)*)?)*[\\s:] (?:filetype|ft|syntax)\\s*= postscr(?:ipt)? (?=\\s|:|$) ) """ foldingStartMarker: "(?:{|<<|^stream)\\s*$" foldingStopMarker: "(?:}|>>|^end(?:stream|obj))" limitLineLength: no maxTokensPerLine: 1000 patterns: [{ name: "meta.document.pdf" begin: "\\A(?=%PDF)" end: "(?=A)B" patterns: [include: "#main"] },{ name: "meta.ai-prefs.postscript" begin: "\\A(?=/(?:(?:Menus|collection1|precision) {|textImportantVisualLinesSnapping \\d)(?:\\r|$))" end: "(?=A)B" patterns: [include: "#main"] }, include: "#main"] # Corrections for faux-PostScript highlighting injections: # Adobe Illustrator preferences "L:source.postscript meta.ai-prefs.postscript - (comment | string | source.embedded | text.embedded)": patterns: [{ # /hexEncodedSetting [ length … hex-bytes ] name: "meta.obfuscated-setting.ai-prefs.postscript" begin: "^\\s*(/(?:\\\\.|[^()<>\\[\\]{}/%\\s])*) ((\\[) (?!0\\b)(\\d+)(?:$|\\r))" end: "^\\s*(\\])|\\G(?!$)|(?!\\G)^(?!\\s*(?:\\]|[A-Fa-f0-9]+$))" contentName: "meta.array.postscript" beginCaptures: 1: patterns: [include: "$self"] 2: name: "meta.array.postscript" 3: name: "punctuation.definition.array.begin.postscript" 4: name: "constant.numeric.postscript" endCaptures: 0: name: "meta.array.postscript" 1: name: "punctuation.definition.array.end.postscript" patterns: [{ name: "string.other.hexadecimal.postscript" match: "[A-Fa-f0-9]+" }] },{ # /This\ escape\ sequence\ syntax\ doesn't\ normally\ work name: "variable.other.constant.literal.postscript" match: "(/)((?:\\\\.|[^()<>\\[\\]{}/%\\s])*)" captures: 1: name: "punctuation.definition.name.postscript" 2: patterns: [{ name: "constant.character.escape.postscript" match: "(\\\\)." captures: 1: name: "punctuation.definition.escape.backslash.postscript" }] },{ # Presumably a long integer: 65535L name: "constant.numeric.integer.long.postscript" match: "[0-9]+L" }] # PDF-specific elements "L:source.postscript meta.document.pdf - (meta.encrypted-source | source.embedded | text.embedded)": patterns: [{ # Binary streams name: "meta.encrypted-source.stream.pdf" begin: "(?:^|(?<=>>)\\s*)(?=stream$)" end: "endstream|(?=endobj\\b)" endCaptures: 0: name: "keyword.control.stream.end.pdf" patterns: [{ begin: "\\G(stream)\\s*$\\s*" end: "(?=endstream|(?=endobj\\b))" beginCaptures: 1: name: "keyword.control.stream.begin.pdf" patterns: [{ # Those weird-ass XML chunks Adobe Illustrator uses begin: "(<\\?xpacket(?=\\s)[^>]+\\?>)(?=$|<x:xmpmeta)" end: "(<\\?xpacket(?=\\s)[^>]*end\\b[^>]*\\?>)|(?=\\s*(?:endstream|endobj\\b))" beginCaptures: 1: name: "text.embedded.xml", patterns: [include: "text.xml"] endCaptures: 1: name: "text.embedded.xml", patterns: [include: "text.xml"] contentName: "text.embedded.xml" patterns: [include: "text.xml"] },{ # Ascii85 name: "string.other.base85.pdf" begin: "(?!endstream)[!-uz]{50,80}\\s*$" end: "~>|(?=\\s*(?:endstream|endobj\\b))" endCaptures: 0: name: "punctuation.definition.string.end.pdf" },{ # Raw binary name: "string.other.raw.binary.pdf" begin: "(?!endstream|[!-uz]{50,80}\\s*$)(?:(?<=[\\n\\r]|\\G|^))(?=.)" end: "(?=\\s*(?:endstream|endobj\\b))" contentName: "sublimelinter.gutter-mark" }] }] },{ # Objects match: "(?<![^/\\s{}()<>\\[\\]%])\\b(obj)\\s*(?=<<|$)|(?<=^|\\n|>>)(endobj)" captures: 1: name: "keyword.control.object.begin.pdf" 2: name: "keyword.control.object.end.pdf" },{ # Trailer name: "keyword.control.$1.pdf" match: "(?<![^/\\s{}()<>\\[\\]%])\\b(trailer|startxref)(?![^/\\s{}()<>\\[\\]%])" }] repository: main: patterns: [ {include: "#string"} {include: "#comment"} {include: "#dictionary"} {include: "#array"} {include: "#procedure"} {include: "#base85"} {include: "#hex"} {include: "#radix"} {include: "#number"} {include: "#embedded"} {include: "#operators"} {include: "#extensions"} {include: "#embeddedRow"} {include: "#names"} ] # [ … ] array: name: "meta.array.postscript" begin: "\\[" end: "\\]" beginCaptures: 0: name: "punctuation.definition.array.begin.postscript" endCaptures: 0: name: "punctuation.definition.array.end.postscript" patterns: [include: "#main"] # Ascii85-encoded data: <~ … ~> base85: name: "string.other.base85.postscript" begin: "<~" end: "~>" beginCaptures: 0: name: "punctuation.definition.string.begin.postscript" endCaptures: 0: name: "punctuation.definition.string.end.postscript" patterns: [ name: "invalid.illegal.base85.char.postscript" match: "(?:[^!-uz\\s]|~(?!>))++" ] # % Commented line comment: patterns: [ # XXX: Not sure why TextMate tokenises this, but I guess I will too name: "punctuation.whitespace.comment.leading.postscript" match: "^[ \\t]+(?=%)" # %%DSC: Document Structuring Conventions {include: "#dsc"} # % Comment name: "comment.line.percentage.postscript" begin: "%" end: "(?=$|\\r|\\f)" beginCaptures: 0: name: "punctuation.definition.comment.postscript" ] # << … >> dictionary: name: "meta.dictionary.postscript" begin: "<<" end: ">>" beginCaptures: 0: name: "punctuation.definition.dictionary.begin.postscript" endCaptures: 0: name: "punctuation.definition.dictionary.end.postscript" patterns: [include: "#main"] # Document Structuring Convention dsc: name: "meta.Document-Structuring-Comment.postscript" beginCaptures: 0: name: "keyword.other.DSC.postscript" 1: name: "punctuation.definition.keyword.DSC.postscript" 3: name: "keyword.operator.assignment.key-value.colon.postscript" contentName: "string.unquoted.DSC.postscript" begin: """(?x) ^ (%%) ( BeginBinary | BeginCustomColor | BeginData | BeginDefaults | BeginDocument | BeginEmulation | BeginExitServer | BeginFeature | BeginFile | BeginFont | BeginObject | BeginPageSetup | BeginPaperSize | BeginPreview | BeginProcSet | BeginProcessColor | BeginProlog | BeginResource | BeginSetup | BoundingBox | CMYKCustomColor | ChangeFont | Copyright | CreationDate | Creator | DocumentCustomColors | DocumentData | DocumentFonts | DocumentMedia | DocumentNeededFiles | DocumentNeededFonts | DocumentNeededProcSets | DocumentNeededResources | DocumentPaperColors | DocumentPaperForms | DocumentPaperSizes | DocumentPaperWeights | DocumentPrinterRequired | DocumentProcSets | DocumentProcessColors | DocumentSuppliedFiles | DocumentSuppliedFonts | DocumentSuppliedProcSets | DocumentSuppliedResources | EOF | Emulation | EndBinary | EndComments | EndCustomColor | EndData | EndDefaults | EndDocument | EndEmulation | EndExitServer | EndFeature | EndFile | EndFont | EndObject | EndPageSetup | EndPaperSize | EndPreview | EndProcSet | EndProcessColor | EndProlog | EndResource | EndSetup | ExecuteFile | Extensions | Feature | For | IncludeDocument | IncludeFeature | IncludeFile | IncludeFont | IncludeProcSet | IncludeResource | LanguageLevel | OperatorIntervention | OperatorMessage | Orientation | PageBoundingBox | PageCustomColors | PageFiles | PageFonts | PageMedia | PageOrder | PageOrientation | PageProcessColors | PageRequirements | PageResources | PageTrailer | Pages | Page | PaperColor | PaperForm | PaperSize | PaperWeight | ProofMode | RGBCustomColor | Requirements | Routing | Title | Trailer | VMlocation | VMusage | Version | \\+ | \\?BeginFeatureQuery | \\?BeginFileQuery | \\?BeginFontListQuery | \\?BeginFontQuery | \\?BeginPrinterQuery | \\?BeginProcSetQuery | \\?BeginQuery | \\?BeginResourceListQuery | \\?BeginResourceQuery | \\?BeginVMStatus | \\?EndFeatureQuery | \\?EndFileQuery | \\?EndFontListQuery | \\?EndFontQuery | \\?EndPrinterQuery | \\?EndProcSetQuery | \\?EndQuery | \\?EndResourceListQuery | \\?EndResourceQuery | \\?EndVMStatus ) (:)? [^\\S\\r\\n]* """ end: "(?=$|\\r|\\f)" # Encrypted PostScript sections embedded: patterns: [{ # `readline` from `currentfile` contentName: "string.unquoted.heredoc.postscript" begin: "(?<![^/\\s{}()<>\\[\\]%])\\b(currentfile)\\s+((?=\\S)[^{}%]+?)\\s+(readline)(?!\\s*})\\b(?![^/\\s{}()<>\\[\\]%])(?:$\\s*)?" end: "(?!\\G)$" beginCaptures: 1: name: "keyword.operator.postscript" 2: patterns: [include: "#main"] 3: name: "keyword.operator.postscript" },{ # Base85-encoded name: "meta.encrypted-source.base85.postscript" begin: "(?<![^/\\s{}()<>\\[\\]%])\\b(currentfile)\\s*((/)ASCII85Decode)\\s+(filter)\\b(?![^/\\s{}()<>\\[\\]%])([^}>\\]%]*?(?:exec|image|readstring)\\s*)$\\s*+" end: "~>|(?=cleartomark|closefile)" contentName: "string.other.base85.postscript" beginCaptures: 1: name: "keyword.operator.postscript" 2: name: "variable.other.literal.postscript" 3: name: "punctuation.definition.name.postscript" 4: name: "keyword.operator.postscript" 5: patterns: [include: "#main"] endCaptures: 0: name: "punctuation.definition.string.end.postscript" },{ # `eexec` encryption, typically found only in Type 1 font programs name: "meta.encrypted-source.eexec.postscript" begin: "(?<![^/\\s{}()<>\\[\\]%])\\b(currentfile)\\s+(eexec)(?:$|(?=.*[\\0-\\x08\\x14-\\x31\\x7F\\x80-\\x9F])(?=.{0,3}?[^A-Fa-f0-9]|\\b[A-Fa-f0-9]))" end: "(cleartomark|closefile)\\b(?![^/\\s{}()<>\\[\\]%])|(?<=\\G)(?=[^\\s0-9A-Fa-f])" beginCaptures: 1: name: "keyword.operator.postscript" 2: name: "keyword.operator.postscript" endCaptures: 1: name: "keyword.operator.postscript" patterns: [{ begin: "\\G(?=\\s*$)" end: "(?=\\s*\\S)" },{ begin: "(?:\\G|(?<=\\n|^))\\s*(?=\\S)" end: "(?!\\G)" patterns: [{ # Raw binary # - TODO: Find out how PostScript engines differentiate between a # procedure named `eexecute` and `eexec` followed by raw binary. name: "string.other.raw.binary.postscript" begin: "\\G(?!cleartomark|closefile)(?=.{0,3}?[^A-Fa-f0-9])" end: "(?=\\s*(?:cleartomark|closefile))" contentName: "sublimelinter.gutter-mark" },{ # Hexadecimal name: "string.other.hexadecimal.postscript" begin: "\\G(?!cleartomark|closefile)(?=\\s{0,3}?(?:[A-Fa-f0-9]))" end: "(?=\\s*[^A-Fa-f0-9\\s]|cleartomark|closefile)" }] }] }] # Lines of obvious-looking Ascii85-encoded data embeddedRow: patterns: [{ name: "string.other.base85.postscript" match: "^[!-uz]{0,78}(~>)" captures: 1: name: "punctuation.definition.string.end.postscript" },{ name: "string.other.base85.postscript" begin: """(?x) ^ (?= [^%\\[]*? \\] | [^%(]*? \\) | [^%<]*? > | .*? <(?!~|<) [A-Fa-f0-9]* [^~>A-Fa-f0-9] ) [!-uz]{60,80} [^\\S\\r\\n]* $ """ end: "^[!-uz]{0,78}(~>)" endCaptures: 0: name: "punctuation.definition.string.end.postscript" }] # GhostScript extensions to the PostScript language # file:///Users/<NAME>/Forks/GhostScript/doc/Language.htm#Additional_operators extensions: name: "keyword.operator.ghostscript.postscript" match: """(?x) (?<![^/\\s{}()<>\\[\\]%]) (?:\\b|(?=\\.)) ( \\.activatepathcontrol | \\.addcontrolpath | \\.begintransparencygroup | \\.begintransparencymaskgroup | \\.bind | \\.bindnow | \\.currentalphaisshape | \\.currentblendmode | \\.currentfillconstantalpha | \\.currentopacityalpha | \\.currentoverprintmode | \\.currentpathcontrolstate | \\.currentshapealpha | \\.currentstrokeconstantalpha | \\.currenttextknockout | \\.dicttomark | \\.endtransparencygroup | \\.endtransparencymask | \\.fileposition | \\.genordered | \\.knownget | \\.locksafe | \\.popdf14devicefilter | \\.pushpdf14devicefilter | \\.setalphaisshape | \\.setblendmode | \\.setdebug | \\.setfillconstantalpha | \\.setopacityalpha | \\.setoverprintmode | \\.setsafe | \\.setshapealpha | \\.setstrokeconstantalpha | \\.settextknockout | \\.shellarguments | \\.tempfile | %Type1BuildChar | %Type1BuildGlyph | arccos | arcsin | copydevice | copyscanlines | currentdevice | finddevice | findlibfile | findprotodevice | getdeviceprops | getenv | makeimagedevice | max | min | putdeviceprops | setdevice ) \\b (?![^/\\s{}()<>\\[\\]%]) """ # Hexadecimal data: < … > hex: name: "string.other.hexadecimal.postscript" begin: "<" end: ">" beginCaptures: 0: name: "punctuation.definition.string.begin.postscript" endCaptures: 0: name: "punctuation.definition.string.end.postscript" patterns: [ name: "invalid.illegal.hexadecimal.char.postscript" match: "[^>0-9A-Fa-f\\s]+" ] # Name objects names: patterns: [{ # //Immediately Evaluated Name name: "variable.other.constant.immediately-evaluated.postscript" match: "(//)[^()<>\\[\\]{}/%\\s]*" captures: 1: name: "punctuation.definition.name.postscript" },{ # /Literal name: "variable.other.constant.literal.postscript" match: "(/)[^()<>\\[\\]{}/%\\s]*" captures: 1: name: "punctuation.definition.name.postscript" },{ # Executable name: "variable.other.executable.postscript" match: "[^()<>\\[\\]{}/%\\s]+" }] # Integers and floating-points number: name: "constant.numeric.postscript" match: "[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[Ee][-+]?\\d+)?(?=$|[\\s\\[\\]{}(/%<])" # Built-ins operators: patterns: [{ # LanguageLevel 3 name: "keyword.operator.level-3.postscript" match: """(?x) (?<![^/\\s{}()<>\\[\\]%]) \\b ( GetHalftoneName | GetPageDeviceName | GetSubstituteCRD | StartData | StartData | addglyph | beginbfchar | beginbfrange | begincidchar | begincidrange | begincmap | begincodespacerange | beginnotdefchar | beginnotdefrange | beginrearrangedfont | beginusematrix | cliprestore | clipsave | composefont | currentsmoothness | currenttrapparams | endbfchar | endbfrange | endcidchar | endcidrange | endcmap | endcodespacerange | endnotdefchar | endnotdefrange | endrearrangedfont | endusematrix | findcolorrendering | removeall | removeglyphs | setsmoothness | settrapparams | settrapzone | shfill | usecmap | usefont ) \\b (?![^/\\s{}()<>\\[\\]%]) """ },{ # LanguageLevel 2 name: "keyword.operator.level-2.postscript" match: """(?x) (?<![^/\\s{}()<>\\[\\]%]) \\b ( GlobalFontDirectory | ISOLatin1Encoding | SharedFontDirectory | UserObjects | arct | colorimage | configurationerror | cshow | currentblackgeneration | currentcacheparams | currentcmykcolor | currentcolorrendering | currentcolorscreen | currentcolorspace | currentcolortransfer | currentcolor | currentdevparams | currentglobal | currentgstate | currenthalftone | currentobjectformat | currentoverprint | currentpacking | currentpagedevice | currentshared | currentstrokeadjust | currentsystemparams | currentundercolorremoval | currentuserparams | defineresource | defineuserobject | deletefile | execform | execuserobject | filenameforall | fileposition | filter | findencoding | findresource | gcheck | globaldict | glyphshow | gstate | ineofill | infill | instroke | inueofill | inufill | inustroke | languagelevel | makepattern | packedarray | printobject | product | realtime | rectclip | rectfill | rectstroke | renamefile | resourceforall | resourcestatus | revision | rootfont | scheck | selectfont | serialnumber | setbbox | setblackgeneration | setcachedevice2 | setcacheparams | setcmykcolor | setcolorrendering | setcolorscreen | setcolorspace | setcolortransfer | setcolor | setdevparams | setfileposition | setglobal | setgstate | sethalftone | setobjectformat | setoverprint | setpacking | setpagedevice | setpattern | setshared | setstrokeadjust | setsystemparams | setucacheparams | setundercolorremoval | setuserparams | setvmthreshold | shareddict | startjob | uappend | ucachestatus | ucache | ueofill | ufill | undefinedresource | undefinefont | undefineresource | undefineuserobject | undef | upath | ustrokepath | ustroke | vmreclaim | writeobject | xshow | xyshow | yshow ) \\b (?![^/\\s{}()<>\\[\\]%]) """ },{ # LanguageLevel 1 name: "keyword.operator.level-1.postscript" match: """(?x) (?<![^/\\s{}()<>\\[\\]%]) \\b ( FontDirectory | StandardEncoding | VMerror | abs | add | aload | anchorsearch | and | arcn | arcto | arc | array | ashow | astore | atan | awidthshow | begin | bind | bitshift | bytesavailable | cachestatus | ceiling | charpath | cleardictstack | cleartomark | clear | clippath | clip | closefile | closepath | colorimage | concatmatrix | concat | condition | copypage | copy | cos | countdictstack | countexecstack | counttomark | count | currentcontext | currentdash | currentdict | currentfile | currentflat | currentfont | currentgray | currenthalftonephase | currenthsbcolor | currentlinecap | currentlinejoin | currentlinewidth | currentmatrix | currentmiterlimit | currentpoint | currentrgbcolor | currentscreen | currenttransfer | curveto | cvi | cvlit | cvn | cvrs | cvr | cvs | cvx | defaultmatrix | definefont | defineusername | def | detach | deviceinfo | dictfull | dictstackoverflow | dictstackunderflow | dictstack | dict | div | dtransform | dup | echo | eexec | end | eoclip | eofill | eoviewclip | eq | erasepage | errordict | exch | execstackoverflow | execstack | executeonly | executive | exec | exitserver | exit | exp | false | file | fill | findfont | flattenpath | floor | flushfile | flush | forall | fork | for | getinterval | get | ge | grestoreall | grestore | gsave | gt | handleerror | identmatrix | idiv | idtransform | ifelse | if | imagemask | image | index | initclip | initgraphics | initmatrix | initviewclip | internaldict | interrupt | invalidaccess | invalidcontext | invalidexit | invalidfileaccess | invalidfont | invalidid | invalidrestore | invertmatrix | ioerror | itransform | known | kshow | length | le | limitcheck | lineto | ln | load | lock | log | loop | lt | makefont | mark | matrix | maxlength | mod | monitor | moveto | mul | neg | newpath | ne | noaccess | nocurrentpoint | notify | not | nulldevice | null | or | pathbbox | pathforall | pdfmark | pop | print | prompt | pstack | putinterval | put | quit | rand | rangecheck | rcheck | rcurveto | readhexstring | readline | readonly | readstring | read | rectviewclip | repeat | resetfile | restore | reversepath | rlineto | rmoveto | roll | rotate | round | rrand | run | save | scalefont | scale | search | serverdict | setcachedevice | setcachelimit | setcharwidth | setdash | setflat | setfont | setgray | sethalftonephase | sethsbcolor | setlinecap | setlinejoin | setlinewidth | setmatrix | setmiterlimit | setrgbcolor | setscreen | settransfer | showpage | show | sin | sqrt | srand | stackoverflow | stackunderflow | stack | start | statusdict | status | stopped | stop | store | stringwidth | string | strokepath | stroke | sub | syntaxerror | systemdict | timeout | token | transform | translate | true | truncate | typecheck | type | undefinedfilename | undefinedresult | undefined | unmatchedmark | unregistered | userdict | usertime | version | viewclippath | viewclip | vmstatus | wait | wcheck | where | widthshow | writehexstring | writestring | write | wtranslation | xcheck | xor | yield ) \\b (?![^/\\s{}()<>\\[\\]%]) | # Stuff that starts with a non-word character (?<=^|[/\\s{}()<>\\[\\]%]) (=?=|\\$error) (?=$|[/\\s{}()<>\\[\\]%]) """ }] # Procedure/subroutine procedure: name: "meta.procedure.postscript" begin: "{" end: "}" beginCaptures: 0: name: "punctuation.definition.procedure.begin.postscript" endCaptures: 0: name: "punctuation.definition.procedure.end.postscript" patterns: [include: "#main"] # Number with explicit radix radix: name: "constant.numeric.radix.postscript" match: "[0-3]?[0-9]#[0-9a-zA-Z]+" # “Special” files specialFiles: patterns: [{ # %device%file name: "constant.language.device-name.$2-device.postscript" match: "\\G(%)([-\\w]+)(?=%|\\)|$)(%)?" captures: 1: name: "punctuation.definition.device-name.begin.postscript" 3: name: "punctuation.definition.device-name.end.postscript" },{ # Usual stdio(3) streams name: "constant.language.special-file.stdio.$2.postscript" match: "\\G(%)(stderr|stdin|stdout)(?=\\)|$)" captures: 1: name: "punctuation.definition.special-file.begin.postscript" 3: name: "punctuation.definition.special-file.end.postscript" },{ # Special files related to interactive execution name: "constant.language.special-file.interactive.$2.postscript" match: "\\G(%)(lineedit|statementedit)(?=\\)|$)" captures: 1: name: "punctuation.definition.special-file.begin.postscript" 3: name: "punctuation.definition.special-file.end.postscript" }] # (Strings (denoted by (balanced) (brackets))) string: name: "string.other.postscript" begin: "\\(" end: "\\)" beginCaptures: 0: name: "punctuation.definition.string.begin.postscript" endCaptures: 0: name: "punctuation.definition.string.end.postscript" patterns: [include: "#stringInnards"] stringInnards: patterns: [{ include: "#specialFiles" },{ name: "constant.numeric.octal.postscript" match: "\\\\[0-7]{1,3}" },{ name: "constant.character.escape.postscript" match: "\\\\(\\\\|[bfnrt()]|[0-7]{1,3}|\\r?\\n)" },{ name: "invalid.illegal.unknown-escape.postscript.ignored" match: "\\\\" },{ begin: "\\(" end: "\\)" patterns: [include: "#stringInnards"] }]
true
name: "PostScript" scopeName: "source.postscript" fileTypes: [ "ps" "eps", "epsf", "epsi" "gsf", "pfa", "pfb", "t1", "t42" "ai", "aia", "pdf" "joboptions" "AIAppResources" "Adobe Illustrator Cloud Prefs" "Adobe Illustrator Prefs" "Tools Panel Presets" "cidfmap", "Fontmap", "Fontmap.GS", "xlatmap" "PPI_CUtils", "Pscript5Idiom" ] firstLineMatch: """(?x) # Signature \\A%(?:!|PDF) | # Adobe Illustrator preferences \\A/(?:Menus|collection1)\\ {(?:\\r|$) | # Best guess for extensionless files distributed with GhostScript (?i:\\A%+\\s+Copyright\\s+\\(C\\)\\s+([-\\d]+),?\\s+Artifex\\sSoftware\\b) | # Hashbang ^\\#!.*(?:\\s|\\/|(?<=!)\\b) gs (?:$|\\s) | # Modeline (?i: # Emacs -\\*-(?:\\s*(?=[^:;\\s]+\\s*-\\*-)|(?:.*?[;\\s]|(?<=-\\*-))mode\\s*:\\s*) (?:ps|postscript) (?=[\\s;]|(?<![-*])-\\*-).*?-\\*- | # Vim (?:(?:\\s|^)vi(?:m[<=>]?\\d+|m)?|\\sex)(?=:(?=\\s*set?\\s[^\\n:]+:)|:(?!\\s* set?\\s)) (?:(?:\\s|\\s*:\\s*)\\w*(?:\\s*=(?:[^\\n\\\\\\s]|\\\\.)*)?)*[\\s:] (?:filetype|ft|syntax)\\s*= postscr(?:ipt)? (?=\\s|:|$) ) """ foldingStartMarker: "(?:{|<<|^stream)\\s*$" foldingStopMarker: "(?:}|>>|^end(?:stream|obj))" limitLineLength: no maxTokensPerLine: 1000 patterns: [{ name: "meta.document.pdf" begin: "\\A(?=%PDF)" end: "(?=A)B" patterns: [include: "#main"] },{ name: "meta.ai-prefs.postscript" begin: "\\A(?=/(?:(?:Menus|collection1|precision) {|textImportantVisualLinesSnapping \\d)(?:\\r|$))" end: "(?=A)B" patterns: [include: "#main"] }, include: "#main"] # Corrections for faux-PostScript highlighting injections: # Adobe Illustrator preferences "L:source.postscript meta.ai-prefs.postscript - (comment | string | source.embedded | text.embedded)": patterns: [{ # /hexEncodedSetting [ length … hex-bytes ] name: "meta.obfuscated-setting.ai-prefs.postscript" begin: "^\\s*(/(?:\\\\.|[^()<>\\[\\]{}/%\\s])*) ((\\[) (?!0\\b)(\\d+)(?:$|\\r))" end: "^\\s*(\\])|\\G(?!$)|(?!\\G)^(?!\\s*(?:\\]|[A-Fa-f0-9]+$))" contentName: "meta.array.postscript" beginCaptures: 1: patterns: [include: "$self"] 2: name: "meta.array.postscript" 3: name: "punctuation.definition.array.begin.postscript" 4: name: "constant.numeric.postscript" endCaptures: 0: name: "meta.array.postscript" 1: name: "punctuation.definition.array.end.postscript" patterns: [{ name: "string.other.hexadecimal.postscript" match: "[A-Fa-f0-9]+" }] },{ # /This\ escape\ sequence\ syntax\ doesn't\ normally\ work name: "variable.other.constant.literal.postscript" match: "(/)((?:\\\\.|[^()<>\\[\\]{}/%\\s])*)" captures: 1: name: "punctuation.definition.name.postscript" 2: patterns: [{ name: "constant.character.escape.postscript" match: "(\\\\)." captures: 1: name: "punctuation.definition.escape.backslash.postscript" }] },{ # Presumably a long integer: 65535L name: "constant.numeric.integer.long.postscript" match: "[0-9]+L" }] # PDF-specific elements "L:source.postscript meta.document.pdf - (meta.encrypted-source | source.embedded | text.embedded)": patterns: [{ # Binary streams name: "meta.encrypted-source.stream.pdf" begin: "(?:^|(?<=>>)\\s*)(?=stream$)" end: "endstream|(?=endobj\\b)" endCaptures: 0: name: "keyword.control.stream.end.pdf" patterns: [{ begin: "\\G(stream)\\s*$\\s*" end: "(?=endstream|(?=endobj\\b))" beginCaptures: 1: name: "keyword.control.stream.begin.pdf" patterns: [{ # Those weird-ass XML chunks Adobe Illustrator uses begin: "(<\\?xpacket(?=\\s)[^>]+\\?>)(?=$|<x:xmpmeta)" end: "(<\\?xpacket(?=\\s)[^>]*end\\b[^>]*\\?>)|(?=\\s*(?:endstream|endobj\\b))" beginCaptures: 1: name: "text.embedded.xml", patterns: [include: "text.xml"] endCaptures: 1: name: "text.embedded.xml", patterns: [include: "text.xml"] contentName: "text.embedded.xml" patterns: [include: "text.xml"] },{ # Ascii85 name: "string.other.base85.pdf" begin: "(?!endstream)[!-uz]{50,80}\\s*$" end: "~>|(?=\\s*(?:endstream|endobj\\b))" endCaptures: 0: name: "punctuation.definition.string.end.pdf" },{ # Raw binary name: "string.other.raw.binary.pdf" begin: "(?!endstream|[!-uz]{50,80}\\s*$)(?:(?<=[\\n\\r]|\\G|^))(?=.)" end: "(?=\\s*(?:endstream|endobj\\b))" contentName: "sublimelinter.gutter-mark" }] }] },{ # Objects match: "(?<![^/\\s{}()<>\\[\\]%])\\b(obj)\\s*(?=<<|$)|(?<=^|\\n|>>)(endobj)" captures: 1: name: "keyword.control.object.begin.pdf" 2: name: "keyword.control.object.end.pdf" },{ # Trailer name: "keyword.control.$1.pdf" match: "(?<![^/\\s{}()<>\\[\\]%])\\b(trailer|startxref)(?![^/\\s{}()<>\\[\\]%])" }] repository: main: patterns: [ {include: "#string"} {include: "#comment"} {include: "#dictionary"} {include: "#array"} {include: "#procedure"} {include: "#base85"} {include: "#hex"} {include: "#radix"} {include: "#number"} {include: "#embedded"} {include: "#operators"} {include: "#extensions"} {include: "#embeddedRow"} {include: "#names"} ] # [ … ] array: name: "meta.array.postscript" begin: "\\[" end: "\\]" beginCaptures: 0: name: "punctuation.definition.array.begin.postscript" endCaptures: 0: name: "punctuation.definition.array.end.postscript" patterns: [include: "#main"] # Ascii85-encoded data: <~ … ~> base85: name: "string.other.base85.postscript" begin: "<~" end: "~>" beginCaptures: 0: name: "punctuation.definition.string.begin.postscript" endCaptures: 0: name: "punctuation.definition.string.end.postscript" patterns: [ name: "invalid.illegal.base85.char.postscript" match: "(?:[^!-uz\\s]|~(?!>))++" ] # % Commented line comment: patterns: [ # XXX: Not sure why TextMate tokenises this, but I guess I will too name: "punctuation.whitespace.comment.leading.postscript" match: "^[ \\t]+(?=%)" # %%DSC: Document Structuring Conventions {include: "#dsc"} # % Comment name: "comment.line.percentage.postscript" begin: "%" end: "(?=$|\\r|\\f)" beginCaptures: 0: name: "punctuation.definition.comment.postscript" ] # << … >> dictionary: name: "meta.dictionary.postscript" begin: "<<" end: ">>" beginCaptures: 0: name: "punctuation.definition.dictionary.begin.postscript" endCaptures: 0: name: "punctuation.definition.dictionary.end.postscript" patterns: [include: "#main"] # Document Structuring Convention dsc: name: "meta.Document-Structuring-Comment.postscript" beginCaptures: 0: name: "keyword.other.DSC.postscript" 1: name: "punctuation.definition.keyword.DSC.postscript" 3: name: "keyword.operator.assignment.key-value.colon.postscript" contentName: "string.unquoted.DSC.postscript" begin: """(?x) ^ (%%) ( BeginBinary | BeginCustomColor | BeginData | BeginDefaults | BeginDocument | BeginEmulation | BeginExitServer | BeginFeature | BeginFile | BeginFont | BeginObject | BeginPageSetup | BeginPaperSize | BeginPreview | BeginProcSet | BeginProcessColor | BeginProlog | BeginResource | BeginSetup | BoundingBox | CMYKCustomColor | ChangeFont | Copyright | CreationDate | Creator | DocumentCustomColors | DocumentData | DocumentFonts | DocumentMedia | DocumentNeededFiles | DocumentNeededFonts | DocumentNeededProcSets | DocumentNeededResources | DocumentPaperColors | DocumentPaperForms | DocumentPaperSizes | DocumentPaperWeights | DocumentPrinterRequired | DocumentProcSets | DocumentProcessColors | DocumentSuppliedFiles | DocumentSuppliedFonts | DocumentSuppliedProcSets | DocumentSuppliedResources | EOF | Emulation | EndBinary | EndComments | EndCustomColor | EndData | EndDefaults | EndDocument | EndEmulation | EndExitServer | EndFeature | EndFile | EndFont | EndObject | EndPageSetup | EndPaperSize | EndPreview | EndProcSet | EndProcessColor | EndProlog | EndResource | EndSetup | ExecuteFile | Extensions | Feature | For | IncludeDocument | IncludeFeature | IncludeFile | IncludeFont | IncludeProcSet | IncludeResource | LanguageLevel | OperatorIntervention | OperatorMessage | Orientation | PageBoundingBox | PageCustomColors | PageFiles | PageFonts | PageMedia | PageOrder | PageOrientation | PageProcessColors | PageRequirements | PageResources | PageTrailer | Pages | Page | PaperColor | PaperForm | PaperSize | PaperWeight | ProofMode | RGBCustomColor | Requirements | Routing | Title | Trailer | VMlocation | VMusage | Version | \\+ | \\?BeginFeatureQuery | \\?BeginFileQuery | \\?BeginFontListQuery | \\?BeginFontQuery | \\?BeginPrinterQuery | \\?BeginProcSetQuery | \\?BeginQuery | \\?BeginResourceListQuery | \\?BeginResourceQuery | \\?BeginVMStatus | \\?EndFeatureQuery | \\?EndFileQuery | \\?EndFontListQuery | \\?EndFontQuery | \\?EndPrinterQuery | \\?EndProcSetQuery | \\?EndQuery | \\?EndResourceListQuery | \\?EndResourceQuery | \\?EndVMStatus ) (:)? [^\\S\\r\\n]* """ end: "(?=$|\\r|\\f)" # Encrypted PostScript sections embedded: patterns: [{ # `readline` from `currentfile` contentName: "string.unquoted.heredoc.postscript" begin: "(?<![^/\\s{}()<>\\[\\]%])\\b(currentfile)\\s+((?=\\S)[^{}%]+?)\\s+(readline)(?!\\s*})\\b(?![^/\\s{}()<>\\[\\]%])(?:$\\s*)?" end: "(?!\\G)$" beginCaptures: 1: name: "keyword.operator.postscript" 2: patterns: [include: "#main"] 3: name: "keyword.operator.postscript" },{ # Base85-encoded name: "meta.encrypted-source.base85.postscript" begin: "(?<![^/\\s{}()<>\\[\\]%])\\b(currentfile)\\s*((/)ASCII85Decode)\\s+(filter)\\b(?![^/\\s{}()<>\\[\\]%])([^}>\\]%]*?(?:exec|image|readstring)\\s*)$\\s*+" end: "~>|(?=cleartomark|closefile)" contentName: "string.other.base85.postscript" beginCaptures: 1: name: "keyword.operator.postscript" 2: name: "variable.other.literal.postscript" 3: name: "punctuation.definition.name.postscript" 4: name: "keyword.operator.postscript" 5: patterns: [include: "#main"] endCaptures: 0: name: "punctuation.definition.string.end.postscript" },{ # `eexec` encryption, typically found only in Type 1 font programs name: "meta.encrypted-source.eexec.postscript" begin: "(?<![^/\\s{}()<>\\[\\]%])\\b(currentfile)\\s+(eexec)(?:$|(?=.*[\\0-\\x08\\x14-\\x31\\x7F\\x80-\\x9F])(?=.{0,3}?[^A-Fa-f0-9]|\\b[A-Fa-f0-9]))" end: "(cleartomark|closefile)\\b(?![^/\\s{}()<>\\[\\]%])|(?<=\\G)(?=[^\\s0-9A-Fa-f])" beginCaptures: 1: name: "keyword.operator.postscript" 2: name: "keyword.operator.postscript" endCaptures: 1: name: "keyword.operator.postscript" patterns: [{ begin: "\\G(?=\\s*$)" end: "(?=\\s*\\S)" },{ begin: "(?:\\G|(?<=\\n|^))\\s*(?=\\S)" end: "(?!\\G)" patterns: [{ # Raw binary # - TODO: Find out how PostScript engines differentiate between a # procedure named `eexecute` and `eexec` followed by raw binary. name: "string.other.raw.binary.postscript" begin: "\\G(?!cleartomark|closefile)(?=.{0,3}?[^A-Fa-f0-9])" end: "(?=\\s*(?:cleartomark|closefile))" contentName: "sublimelinter.gutter-mark" },{ # Hexadecimal name: "string.other.hexadecimal.postscript" begin: "\\G(?!cleartomark|closefile)(?=\\s{0,3}?(?:[A-Fa-f0-9]))" end: "(?=\\s*[^A-Fa-f0-9\\s]|cleartomark|closefile)" }] }] }] # Lines of obvious-looking Ascii85-encoded data embeddedRow: patterns: [{ name: "string.other.base85.postscript" match: "^[!-uz]{0,78}(~>)" captures: 1: name: "punctuation.definition.string.end.postscript" },{ name: "string.other.base85.postscript" begin: """(?x) ^ (?= [^%\\[]*? \\] | [^%(]*? \\) | [^%<]*? > | .*? <(?!~|<) [A-Fa-f0-9]* [^~>A-Fa-f0-9] ) [!-uz]{60,80} [^\\S\\r\\n]* $ """ end: "^[!-uz]{0,78}(~>)" endCaptures: 0: name: "punctuation.definition.string.end.postscript" }] # GhostScript extensions to the PostScript language # file:///Users/PI:NAME:<NAME>END_PI/Forks/GhostScript/doc/Language.htm#Additional_operators extensions: name: "keyword.operator.ghostscript.postscript" match: """(?x) (?<![^/\\s{}()<>\\[\\]%]) (?:\\b|(?=\\.)) ( \\.activatepathcontrol | \\.addcontrolpath | \\.begintransparencygroup | \\.begintransparencymaskgroup | \\.bind | \\.bindnow | \\.currentalphaisshape | \\.currentblendmode | \\.currentfillconstantalpha | \\.currentopacityalpha | \\.currentoverprintmode | \\.currentpathcontrolstate | \\.currentshapealpha | \\.currentstrokeconstantalpha | \\.currenttextknockout | \\.dicttomark | \\.endtransparencygroup | \\.endtransparencymask | \\.fileposition | \\.genordered | \\.knownget | \\.locksafe | \\.popdf14devicefilter | \\.pushpdf14devicefilter | \\.setalphaisshape | \\.setblendmode | \\.setdebug | \\.setfillconstantalpha | \\.setopacityalpha | \\.setoverprintmode | \\.setsafe | \\.setshapealpha | \\.setstrokeconstantalpha | \\.settextknockout | \\.shellarguments | \\.tempfile | %Type1BuildChar | %Type1BuildGlyph | arccos | arcsin | copydevice | copyscanlines | currentdevice | finddevice | findlibfile | findprotodevice | getdeviceprops | getenv | makeimagedevice | max | min | putdeviceprops | setdevice ) \\b (?![^/\\s{}()<>\\[\\]%]) """ # Hexadecimal data: < … > hex: name: "string.other.hexadecimal.postscript" begin: "<" end: ">" beginCaptures: 0: name: "punctuation.definition.string.begin.postscript" endCaptures: 0: name: "punctuation.definition.string.end.postscript" patterns: [ name: "invalid.illegal.hexadecimal.char.postscript" match: "[^>0-9A-Fa-f\\s]+" ] # Name objects names: patterns: [{ # //Immediately Evaluated Name name: "variable.other.constant.immediately-evaluated.postscript" match: "(//)[^()<>\\[\\]{}/%\\s]*" captures: 1: name: "punctuation.definition.name.postscript" },{ # /Literal name: "variable.other.constant.literal.postscript" match: "(/)[^()<>\\[\\]{}/%\\s]*" captures: 1: name: "punctuation.definition.name.postscript" },{ # Executable name: "variable.other.executable.postscript" match: "[^()<>\\[\\]{}/%\\s]+" }] # Integers and floating-points number: name: "constant.numeric.postscript" match: "[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[Ee][-+]?\\d+)?(?=$|[\\s\\[\\]{}(/%<])" # Built-ins operators: patterns: [{ # LanguageLevel 3 name: "keyword.operator.level-3.postscript" match: """(?x) (?<![^/\\s{}()<>\\[\\]%]) \\b ( GetHalftoneName | GetPageDeviceName | GetSubstituteCRD | StartData | StartData | addglyph | beginbfchar | beginbfrange | begincidchar | begincidrange | begincmap | begincodespacerange | beginnotdefchar | beginnotdefrange | beginrearrangedfont | beginusematrix | cliprestore | clipsave | composefont | currentsmoothness | currenttrapparams | endbfchar | endbfrange | endcidchar | endcidrange | endcmap | endcodespacerange | endnotdefchar | endnotdefrange | endrearrangedfont | endusematrix | findcolorrendering | removeall | removeglyphs | setsmoothness | settrapparams | settrapzone | shfill | usecmap | usefont ) \\b (?![^/\\s{}()<>\\[\\]%]) """ },{ # LanguageLevel 2 name: "keyword.operator.level-2.postscript" match: """(?x) (?<![^/\\s{}()<>\\[\\]%]) \\b ( GlobalFontDirectory | ISOLatin1Encoding | SharedFontDirectory | UserObjects | arct | colorimage | configurationerror | cshow | currentblackgeneration | currentcacheparams | currentcmykcolor | currentcolorrendering | currentcolorscreen | currentcolorspace | currentcolortransfer | currentcolor | currentdevparams | currentglobal | currentgstate | currenthalftone | currentobjectformat | currentoverprint | currentpacking | currentpagedevice | currentshared | currentstrokeadjust | currentsystemparams | currentundercolorremoval | currentuserparams | defineresource | defineuserobject | deletefile | execform | execuserobject | filenameforall | fileposition | filter | findencoding | findresource | gcheck | globaldict | glyphshow | gstate | ineofill | infill | instroke | inueofill | inufill | inustroke | languagelevel | makepattern | packedarray | printobject | product | realtime | rectclip | rectfill | rectstroke | renamefile | resourceforall | resourcestatus | revision | rootfont | scheck | selectfont | serialnumber | setbbox | setblackgeneration | setcachedevice2 | setcacheparams | setcmykcolor | setcolorrendering | setcolorscreen | setcolorspace | setcolortransfer | setcolor | setdevparams | setfileposition | setglobal | setgstate | sethalftone | setobjectformat | setoverprint | setpacking | setpagedevice | setpattern | setshared | setstrokeadjust | setsystemparams | setucacheparams | setundercolorremoval | setuserparams | setvmthreshold | shareddict | startjob | uappend | ucachestatus | ucache | ueofill | ufill | undefinedresource | undefinefont | undefineresource | undefineuserobject | undef | upath | ustrokepath | ustroke | vmreclaim | writeobject | xshow | xyshow | yshow ) \\b (?![^/\\s{}()<>\\[\\]%]) """ },{ # LanguageLevel 1 name: "keyword.operator.level-1.postscript" match: """(?x) (?<![^/\\s{}()<>\\[\\]%]) \\b ( FontDirectory | StandardEncoding | VMerror | abs | add | aload | anchorsearch | and | arcn | arcto | arc | array | ashow | astore | atan | awidthshow | begin | bind | bitshift | bytesavailable | cachestatus | ceiling | charpath | cleardictstack | cleartomark | clear | clippath | clip | closefile | closepath | colorimage | concatmatrix | concat | condition | copypage | copy | cos | countdictstack | countexecstack | counttomark | count | currentcontext | currentdash | currentdict | currentfile | currentflat | currentfont | currentgray | currenthalftonephase | currenthsbcolor | currentlinecap | currentlinejoin | currentlinewidth | currentmatrix | currentmiterlimit | currentpoint | currentrgbcolor | currentscreen | currenttransfer | curveto | cvi | cvlit | cvn | cvrs | cvr | cvs | cvx | defaultmatrix | definefont | defineusername | def | detach | deviceinfo | dictfull | dictstackoverflow | dictstackunderflow | dictstack | dict | div | dtransform | dup | echo | eexec | end | eoclip | eofill | eoviewclip | eq | erasepage | errordict | exch | execstackoverflow | execstack | executeonly | executive | exec | exitserver | exit | exp | false | file | fill | findfont | flattenpath | floor | flushfile | flush | forall | fork | for | getinterval | get | ge | grestoreall | grestore | gsave | gt | handleerror | identmatrix | idiv | idtransform | ifelse | if | imagemask | image | index | initclip | initgraphics | initmatrix | initviewclip | internaldict | interrupt | invalidaccess | invalidcontext | invalidexit | invalidfileaccess | invalidfont | invalidid | invalidrestore | invertmatrix | ioerror | itransform | known | kshow | length | le | limitcheck | lineto | ln | load | lock | log | loop | lt | makefont | mark | matrix | maxlength | mod | monitor | moveto | mul | neg | newpath | ne | noaccess | nocurrentpoint | notify | not | nulldevice | null | or | pathbbox | pathforall | pdfmark | pop | print | prompt | pstack | putinterval | put | quit | rand | rangecheck | rcheck | rcurveto | readhexstring | readline | readonly | readstring | read | rectviewclip | repeat | resetfile | restore | reversepath | rlineto | rmoveto | roll | rotate | round | rrand | run | save | scalefont | scale | search | serverdict | setcachedevice | setcachelimit | setcharwidth | setdash | setflat | setfont | setgray | sethalftonephase | sethsbcolor | setlinecap | setlinejoin | setlinewidth | setmatrix | setmiterlimit | setrgbcolor | setscreen | settransfer | showpage | show | sin | sqrt | srand | stackoverflow | stackunderflow | stack | start | statusdict | status | stopped | stop | store | stringwidth | string | strokepath | stroke | sub | syntaxerror | systemdict | timeout | token | transform | translate | true | truncate | typecheck | type | undefinedfilename | undefinedresult | undefined | unmatchedmark | unregistered | userdict | usertime | version | viewclippath | viewclip | vmstatus | wait | wcheck | where | widthshow | writehexstring | writestring | write | wtranslation | xcheck | xor | yield ) \\b (?![^/\\s{}()<>\\[\\]%]) | # Stuff that starts with a non-word character (?<=^|[/\\s{}()<>\\[\\]%]) (=?=|\\$error) (?=$|[/\\s{}()<>\\[\\]%]) """ }] # Procedure/subroutine procedure: name: "meta.procedure.postscript" begin: "{" end: "}" beginCaptures: 0: name: "punctuation.definition.procedure.begin.postscript" endCaptures: 0: name: "punctuation.definition.procedure.end.postscript" patterns: [include: "#main"] # Number with explicit radix radix: name: "constant.numeric.radix.postscript" match: "[0-3]?[0-9]#[0-9a-zA-Z]+" # “Special” files specialFiles: patterns: [{ # %device%file name: "constant.language.device-name.$2-device.postscript" match: "\\G(%)([-\\w]+)(?=%|\\)|$)(%)?" captures: 1: name: "punctuation.definition.device-name.begin.postscript" 3: name: "punctuation.definition.device-name.end.postscript" },{ # Usual stdio(3) streams name: "constant.language.special-file.stdio.$2.postscript" match: "\\G(%)(stderr|stdin|stdout)(?=\\)|$)" captures: 1: name: "punctuation.definition.special-file.begin.postscript" 3: name: "punctuation.definition.special-file.end.postscript" },{ # Special files related to interactive execution name: "constant.language.special-file.interactive.$2.postscript" match: "\\G(%)(lineedit|statementedit)(?=\\)|$)" captures: 1: name: "punctuation.definition.special-file.begin.postscript" 3: name: "punctuation.definition.special-file.end.postscript" }] # (Strings (denoted by (balanced) (brackets))) string: name: "string.other.postscript" begin: "\\(" end: "\\)" beginCaptures: 0: name: "punctuation.definition.string.begin.postscript" endCaptures: 0: name: "punctuation.definition.string.end.postscript" patterns: [include: "#stringInnards"] stringInnards: patterns: [{ include: "#specialFiles" },{ name: "constant.numeric.octal.postscript" match: "\\\\[0-7]{1,3}" },{ name: "constant.character.escape.postscript" match: "\\\\(\\\\|[bfnrt()]|[0-7]{1,3}|\\r?\\n)" },{ name: "invalid.illegal.unknown-escape.postscript.ignored" match: "\\\\" },{ begin: "\\(" end: "\\)" patterns: [include: "#stringInnards"] }]
[ { "context": "singers = {Jagger: \"Rock\", Elvis: \"Roll\"}\n", "end": 17, "score": 0.9995781779289246, "start": 11, "tag": "NAME", "value": "Jagger" }, { "context": "singers = {Jagger: \"Rock\", Elvis: \"Roll\"}\n", "end": 32, "score": 0.99885493516922, "start": 27, "tag": "NAME", "value": "Elvis" } ]
spec/fixture/themes/default/javascripts/override.coffee
ryansobol/mango
5
singers = {Jagger: "Rock", Elvis: "Roll"}
172171
singers = {<NAME>: "Rock", <NAME>: "Roll"}
true
singers = {PI:NAME:<NAME>END_PI: "Rock", PI:NAME:<NAME>END_PI: "Roll"}
[ { "context": "68802\nclient.attachChannel(channelId, { writeKey:'X0H0DM567K9B067G'})\n\nserialPort.on('open', ->\n console.log 'Seria", "end": 436, "score": 0.9996889233589172, "start": 420, "tag": "KEY", "value": "X0H0DM567K9B067G" } ]
app.coffee
knshetty/wthermometer-tap-decode-log
0
Com = require 'serialport' ThingSpeakClient = require 'thingspeakclient' serialPort = new Com.SerialPort("/dev/ttyUSB0", { baudrate: 9600 parser: Com.parsers.readline('\n') }) # Instantiate a ThinkSpeak IoT-cloud client client = new ThingSpeakClient({ server:'https://api.thingspeak.com', useTimeoutMode: false}) # Attach a channel with only a writekey channelId = 68802 client.attachChannel(channelId, { writeKey:'X0H0DM567K9B067G'}) serialPort.on('open', -> console.log 'Serial Port Opened...' serialPort.on('data', (data) -> #console.log data if((data[0..5] isnt 'ERROR:') or (data[0..5] isnt 'Fault:') or (data[0..2] isnt 'NaN')) digit1 = parseInt(data[0..3], 2) digit2 = parseInt(data[4..7], 2) digit3 = parseInt(data[8..11], 2) # Note! If the digit2 is greater than 9 i.e. for e.g. 12 then the # transmitter batteries are low on power. if (digit2 < 10) temperatureFahrenheit = "#{digit1}#{digit2}#{digit3}" #console.log temperatureFahrenheit # Note! Min-Max temperature reading capability of this wireless # thermometer 32F = 0C & 410F = 210C if ((temperatureFahrenheit >= 32) or (temperatureFahrenheit <= 410)) temperatureCelsius = "#{(temperatureFahrenheit - 32) * 0.56}" tcParts = temperatureCelsius.split('.') temperature = tcParts[0] console.log temperature client.updateChannel(channelId, {field1: temperature}) ) )
8064
Com = require 'serialport' ThingSpeakClient = require 'thingspeakclient' serialPort = new Com.SerialPort("/dev/ttyUSB0", { baudrate: 9600 parser: Com.parsers.readline('\n') }) # Instantiate a ThinkSpeak IoT-cloud client client = new ThingSpeakClient({ server:'https://api.thingspeak.com', useTimeoutMode: false}) # Attach a channel with only a writekey channelId = 68802 client.attachChannel(channelId, { writeKey:'<KEY>'}) serialPort.on('open', -> console.log 'Serial Port Opened...' serialPort.on('data', (data) -> #console.log data if((data[0..5] isnt 'ERROR:') or (data[0..5] isnt 'Fault:') or (data[0..2] isnt 'NaN')) digit1 = parseInt(data[0..3], 2) digit2 = parseInt(data[4..7], 2) digit3 = parseInt(data[8..11], 2) # Note! If the digit2 is greater than 9 i.e. for e.g. 12 then the # transmitter batteries are low on power. if (digit2 < 10) temperatureFahrenheit = "#{digit1}#{digit2}#{digit3}" #console.log temperatureFahrenheit # Note! Min-Max temperature reading capability of this wireless # thermometer 32F = 0C & 410F = 210C if ((temperatureFahrenheit >= 32) or (temperatureFahrenheit <= 410)) temperatureCelsius = "#{(temperatureFahrenheit - 32) * 0.56}" tcParts = temperatureCelsius.split('.') temperature = tcParts[0] console.log temperature client.updateChannel(channelId, {field1: temperature}) ) )
true
Com = require 'serialport' ThingSpeakClient = require 'thingspeakclient' serialPort = new Com.SerialPort("/dev/ttyUSB0", { baudrate: 9600 parser: Com.parsers.readline('\n') }) # Instantiate a ThinkSpeak IoT-cloud client client = new ThingSpeakClient({ server:'https://api.thingspeak.com', useTimeoutMode: false}) # Attach a channel with only a writekey channelId = 68802 client.attachChannel(channelId, { writeKey:'PI:KEY:<KEY>END_PI'}) serialPort.on('open', -> console.log 'Serial Port Opened...' serialPort.on('data', (data) -> #console.log data if((data[0..5] isnt 'ERROR:') or (data[0..5] isnt 'Fault:') or (data[0..2] isnt 'NaN')) digit1 = parseInt(data[0..3], 2) digit2 = parseInt(data[4..7], 2) digit3 = parseInt(data[8..11], 2) # Note! If the digit2 is greater than 9 i.e. for e.g. 12 then the # transmitter batteries are low on power. if (digit2 < 10) temperatureFahrenheit = "#{digit1}#{digit2}#{digit3}" #console.log temperatureFahrenheit # Note! Min-Max temperature reading capability of this wireless # thermometer 32F = 0C & 410F = 210C if ((temperatureFahrenheit >= 32) or (temperatureFahrenheit <= 410)) temperatureCelsius = "#{(temperatureFahrenheit - 32) * 0.56}" tcParts = temperatureCelsius.split('.') temperature = tcParts[0] console.log temperature client.updateChannel(channelId, {field1: temperature}) ) )
[ { "context": "et: 'test'\n S3_KEY: 'test'\n S3_SECRET: 'test'\n version =\n name: 'test'\n extension", "end": 1509, "score": 0.5127850770950317, "start": 1505, "tag": "KEY", "value": "test" } ]
test/store_test.coffee
Rafe/papercut
33
fs = require('fs') path = require('path') { FileStore, S3Store , TestStore } = require('../lib/store') describe 'FileStore', -> store = '' version = '' beforeEach -> store = new FileStore extension: 'jpg' directory: dir url: '/images' version = name: 'test' extension: 'jpg' it 'should return dstPath', -> store.getDstPath('test', version) .should.eql path.join(dir, '/test-test.jpg') it 'should return urlPath', -> store.getUrlPath('test', version) .should.eql '/images/test-test.jpg' it 'should auto adjust different url', -> store.config.directory = './images/output/' store.getDstPath('test', version) .should.eql path.join(dir, '/test-test.jpg') describe 'save', -> it 'should save file', (done)-> stream = fs.createReadStream('./images/sample.jpg') store.save 'test', version, stream, null, (err, url)-> fs.existsSync(path.join(dir, '/test-test.jpg')).should.be.ok url.should.eql '/images/test-test.jpg' store.result[version.name].should.eql '/images/test-test.jpg' done() it 'should handle error', (done)-> emptyStream = '' store.save 'test', version, emptyStream, 'ENOENT', (err, url)-> err.message.should.eql 'ENOENT' done() after cleanFiles describe "S3Store", -> store = '' version = '' beforeEach -> store = new S3Store extension: 'jpg' bucket: 'test' S3_KEY: 'test' S3_SECRET: 'test' version = name: 'test' extension: 'jpg' store.client = putBuffer: (buffer, dstPath, headers, callback)-> callback() it 'should return dstPath', -> store.getDstPath('test', version) .should.eql 'test-test.jpg' it 'should return urlPath with s3 url', -> store.getUrlPath('test', version) .should.eql store.awsUrl + '/test/test-test.jpg' it 'should upload file to s3', (done)-> store.save 'test', version, 'test', null, (err, url)-> url.should.eql store.awsUrl + '/test/test-test.jpg' done() it 'should handle process error', (done)-> store.save 'test', version, 'test', 'Error', (err, url)-> err.message.should.eql 'Error' done() it 'should handle upload error', (done)-> store.client = putBuffer: (buffer, dstPath, headers, callback)-> callback(new Error('Upload Error')) store.save 'test', version, 'test', null, (err, url)-> err.message.should.eql 'Upload Error' done() describe "TestStore", -> it "do nothing on storing images", -> version = name: 'test' extension: 'jpg' store = new TestStore extension: 'jpg' store.save 'test', version, 'test', null, (err, url)-> url.should.eql 'test-test.jpg'
220186
fs = require('fs') path = require('path') { FileStore, S3Store , TestStore } = require('../lib/store') describe 'FileStore', -> store = '' version = '' beforeEach -> store = new FileStore extension: 'jpg' directory: dir url: '/images' version = name: 'test' extension: 'jpg' it 'should return dstPath', -> store.getDstPath('test', version) .should.eql path.join(dir, '/test-test.jpg') it 'should return urlPath', -> store.getUrlPath('test', version) .should.eql '/images/test-test.jpg' it 'should auto adjust different url', -> store.config.directory = './images/output/' store.getDstPath('test', version) .should.eql path.join(dir, '/test-test.jpg') describe 'save', -> it 'should save file', (done)-> stream = fs.createReadStream('./images/sample.jpg') store.save 'test', version, stream, null, (err, url)-> fs.existsSync(path.join(dir, '/test-test.jpg')).should.be.ok url.should.eql '/images/test-test.jpg' store.result[version.name].should.eql '/images/test-test.jpg' done() it 'should handle error', (done)-> emptyStream = '' store.save 'test', version, emptyStream, 'ENOENT', (err, url)-> err.message.should.eql 'ENOENT' done() after cleanFiles describe "S3Store", -> store = '' version = '' beforeEach -> store = new S3Store extension: 'jpg' bucket: 'test' S3_KEY: 'test' S3_SECRET: '<KEY>' version = name: 'test' extension: 'jpg' store.client = putBuffer: (buffer, dstPath, headers, callback)-> callback() it 'should return dstPath', -> store.getDstPath('test', version) .should.eql 'test-test.jpg' it 'should return urlPath with s3 url', -> store.getUrlPath('test', version) .should.eql store.awsUrl + '/test/test-test.jpg' it 'should upload file to s3', (done)-> store.save 'test', version, 'test', null, (err, url)-> url.should.eql store.awsUrl + '/test/test-test.jpg' done() it 'should handle process error', (done)-> store.save 'test', version, 'test', 'Error', (err, url)-> err.message.should.eql 'Error' done() it 'should handle upload error', (done)-> store.client = putBuffer: (buffer, dstPath, headers, callback)-> callback(new Error('Upload Error')) store.save 'test', version, 'test', null, (err, url)-> err.message.should.eql 'Upload Error' done() describe "TestStore", -> it "do nothing on storing images", -> version = name: 'test' extension: 'jpg' store = new TestStore extension: 'jpg' store.save 'test', version, 'test', null, (err, url)-> url.should.eql 'test-test.jpg'
true
fs = require('fs') path = require('path') { FileStore, S3Store , TestStore } = require('../lib/store') describe 'FileStore', -> store = '' version = '' beforeEach -> store = new FileStore extension: 'jpg' directory: dir url: '/images' version = name: 'test' extension: 'jpg' it 'should return dstPath', -> store.getDstPath('test', version) .should.eql path.join(dir, '/test-test.jpg') it 'should return urlPath', -> store.getUrlPath('test', version) .should.eql '/images/test-test.jpg' it 'should auto adjust different url', -> store.config.directory = './images/output/' store.getDstPath('test', version) .should.eql path.join(dir, '/test-test.jpg') describe 'save', -> it 'should save file', (done)-> stream = fs.createReadStream('./images/sample.jpg') store.save 'test', version, stream, null, (err, url)-> fs.existsSync(path.join(dir, '/test-test.jpg')).should.be.ok url.should.eql '/images/test-test.jpg' store.result[version.name].should.eql '/images/test-test.jpg' done() it 'should handle error', (done)-> emptyStream = '' store.save 'test', version, emptyStream, 'ENOENT', (err, url)-> err.message.should.eql 'ENOENT' done() after cleanFiles describe "S3Store", -> store = '' version = '' beforeEach -> store = new S3Store extension: 'jpg' bucket: 'test' S3_KEY: 'test' S3_SECRET: 'PI:KEY:<KEY>END_PI' version = name: 'test' extension: 'jpg' store.client = putBuffer: (buffer, dstPath, headers, callback)-> callback() it 'should return dstPath', -> store.getDstPath('test', version) .should.eql 'test-test.jpg' it 'should return urlPath with s3 url', -> store.getUrlPath('test', version) .should.eql store.awsUrl + '/test/test-test.jpg' it 'should upload file to s3', (done)-> store.save 'test', version, 'test', null, (err, url)-> url.should.eql store.awsUrl + '/test/test-test.jpg' done() it 'should handle process error', (done)-> store.save 'test', version, 'test', 'Error', (err, url)-> err.message.should.eql 'Error' done() it 'should handle upload error', (done)-> store.client = putBuffer: (buffer, dstPath, headers, callback)-> callback(new Error('Upload Error')) store.save 'test', version, 'test', null, (err, url)-> err.message.should.eql 'Upload Error' done() describe "TestStore", -> it "do nothing on storing images", -> version = name: 'test' extension: 'jpg' store = new TestStore extension: 'jpg' store.save 'test', version, 'test', null, (err, url)-> url.should.eql 'test-test.jpg'
[ { "context": "ditProfile: @spy.editProfile\n changePassword: @spy.changePassword\n changeEmail: @spy.changeEmail\n }", "end": 291, "score": 0.6492918133735657, "start": 280, "tag": "PASSWORD", "value": "@spy.change" } ]
spec/javascripts/core/apps/profile/app-route.spec.coffee
houzelio/houzel
2
import Router from 'javascripts/core/apps/profile/app-route' describe("Profile App Route", () -> beforeAll -> @spy = jasmine.createSpyObj('spy', ['editProfile', 'changePassword', 'changeEmail']) controller = { editProfile: @spy.editProfile changePassword: @spy.changePassword changeEmail: @spy.changeEmail } @myRouter = new Router {controller: controller} Backbone.history.start() afterAll -> Backbone.history.stop() it("should execute the configured method for matched path", () -> @myRouter.navigate('user/profile', true) @myRouter.navigate('user/profile/password', true) @myRouter.navigate('user/profile/email', true) expect(@spy.editProfile).toHaveBeenCalled() expect(@spy.changePassword).toHaveBeenCalled() expect(@spy.changeEmail).toHaveBeenCalled() ) )
171841
import Router from 'javascripts/core/apps/profile/app-route' describe("Profile App Route", () -> beforeAll -> @spy = jasmine.createSpyObj('spy', ['editProfile', 'changePassword', 'changeEmail']) controller = { editProfile: @spy.editProfile changePassword: <PASSWORD>Password changeEmail: @spy.changeEmail } @myRouter = new Router {controller: controller} Backbone.history.start() afterAll -> Backbone.history.stop() it("should execute the configured method for matched path", () -> @myRouter.navigate('user/profile', true) @myRouter.navigate('user/profile/password', true) @myRouter.navigate('user/profile/email', true) expect(@spy.editProfile).toHaveBeenCalled() expect(@spy.changePassword).toHaveBeenCalled() expect(@spy.changeEmail).toHaveBeenCalled() ) )
true
import Router from 'javascripts/core/apps/profile/app-route' describe("Profile App Route", () -> beforeAll -> @spy = jasmine.createSpyObj('spy', ['editProfile', 'changePassword', 'changeEmail']) controller = { editProfile: @spy.editProfile changePassword: PI:PASSWORD:<PASSWORD>END_PIPassword changeEmail: @spy.changeEmail } @myRouter = new Router {controller: controller} Backbone.history.start() afterAll -> Backbone.history.stop() it("should execute the configured method for matched path", () -> @myRouter.navigate('user/profile', true) @myRouter.navigate('user/profile/password', true) @myRouter.navigate('user/profile/email', true) expect(@spy.editProfile).toHaveBeenCalled() expect(@spy.changePassword).toHaveBeenCalled() expect(@spy.changeEmail).toHaveBeenCalled() ) )
[ { "context": "r templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ\n\n\ttemplateData:\n\n\t\tcutTag: '<!-- ", "end": 320, "score": 0.9987694621086121, "start": 315, "tag": "USERNAME", "value": "bevry" }, { "context": "name used in copyrights and meta data\n\t\t\tauthor: \"SolidBuild.net\"\n\n\t\t\temail: \"admin@solidbuild.net\"\n\n\t\t\t# Change t", "end": 851, "score": 0.8081475496292114, "start": 837, "tag": "EMAIL", "value": "SolidBuild.net" }, { "context": "meta data\n\t\t\tauthor: \"SolidBuild.net\"\n\n\t\t\temail: \"admin@solidbuild.net\"\n\n\t\t\t# Change to your disqus name or comment it o", "end": 885, "score": 0.9999049305915833, "start": 865, "tag": "EMAIL", "value": "admin@solidbuild.net" } ]
docpad.coffee
interpaul/solidbuild.net
0
# The DocPad Configuration File # It is simply a CoffeeScript Object which is parsed by CSON docpadConfig = { # ================================= # Template Data # These are variables that will be accessible via our templates # To access one of these within our templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ templateData: cutTag: '<!-- cut -->' # Specify some site properties site: # The production url of our website. Used in sitemap and rss feed url: "http://solidbuild.net" # Here are some old site urls that you would like to redirect from oldUrls: [ 'www.website.com', 'website.herokuapp.com' ] # The default title of our website title: "SolidBuild" # The title of RSS rssTitle: "SolidBuild" # Author name used in copyrights and meta data author: "SolidBuild.net" email: "admin@solidbuild.net" # Change to your disqus name or comment it out to disable comments disqus_shortname: "solidbuild" # The website description (for SEO) description: """ SolidBuild — continuous integration server """ # The website keywords (for SEO) separated by commas keywords: """ continuous, integration, server, CI, .net, developers """ googleAnalyticsId: "UA-36917965-1" insertYandexMetrika: true googleAnalyticsDomain: "solidbuild.net" # The website's styles styles: [ '/vendor/normalize.css' '/vendor/h5bp.css' '//fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,300,400,600,700&amp;subset=latin' '/css/solidbuild.css' '//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' ] # The website's scripts scripts: [ '/vendor/jquery-min.js' '/js/script.js' ] # ----------------------------- # Helper Functions # Get the prepared site/document title # Often we would like to specify particular formatting to our page's title # we can apply that formatting here getPreparedTitle: -> # if we have a document title, then we should use that and suffix the site's title onto it if @document.title "#{@document.title} / #{@site.title}" # if our document does not have it's own title, then we should just use the site's title else @site.title # Get the prepared site/document description getPreparedDescription: -> # if we have a document description, then we should use that, otherwise use the site's description @document.description or @site.description # Get the prepared site/document keywords getPreparedKeywords: -> # Merge the document keywords with the site keywords @site.keywords.concat(@document.keywords or []).join(', ') getPreparedArticleTags: (tags) -> # Merge the document keywords with the site keywords tags.concat(tags or []).join(', ') # Post part before “cut” cuttedContent: (content) -> if @hasReadMore content cutIdx = content.search @cutTag content[0..cutIdx-1] else content # Has “cut”? hasReadMore: (content) -> content and ((content.search @cutTag) isnt -1) getTagUrl: (tag) -> doc = docpad.getFile({tag:tag}) return doc?.get('url') or '' collections: articles: -> @getCollection("html").findAllLive({kind:'blogpost'},[{blogDate:-1}]).on "add", (model) -> model.setMetaDefaults({layout:"posts",postAuthor:"Solid Build Team"}) # Plugins configurations plugins: navlinks: collections: articles: -1 cleanurls: static: true trailingSlashes: true tags: extension: '.html.eco' injectDocumentHelper: (document) -> document.setMeta( layout: 'tagcloud' data: """ <%- @partial('tag', @) %> """ ) # ================================= # Environments environments: development: templateData: site: url: 'http://localhost:9778' # ================================= # DocPad Events # Here we can define handlers for events that DocPad fires # You can find a full listing of events on the DocPad Wiki events: # Server Extend # Used to add our own custom routes to the server before the docpad routes are added serverExtend: (opts) -> # Extract the server from the options {server} = opts docpad = @docpad # As we are now running in an event, # ensure we are using the latest copy of the docpad configuraiton # and fetch our urls from it latestConfig = docpad.getConfig() oldUrls = latestConfig.templateData.site.oldUrls or [] newUrl = latestConfig.templateData.site.url # Redirect any requests accessing one of our sites oldUrls to the new site url server.use (req,res,next) -> if req.headers.host in oldUrls res.redirect(newUrl+req.url, 301) else next() } # Export our DocPad Configuration module.exports = docpadConfig
130538
# The DocPad Configuration File # It is simply a CoffeeScript Object which is parsed by CSON docpadConfig = { # ================================= # Template Data # These are variables that will be accessible via our templates # To access one of these within our templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ templateData: cutTag: '<!-- cut -->' # Specify some site properties site: # The production url of our website. Used in sitemap and rss feed url: "http://solidbuild.net" # Here are some old site urls that you would like to redirect from oldUrls: [ 'www.website.com', 'website.herokuapp.com' ] # The default title of our website title: "SolidBuild" # The title of RSS rssTitle: "SolidBuild" # Author name used in copyrights and meta data author: "<EMAIL>" email: "<EMAIL>" # Change to your disqus name or comment it out to disable comments disqus_shortname: "solidbuild" # The website description (for SEO) description: """ SolidBuild — continuous integration server """ # The website keywords (for SEO) separated by commas keywords: """ continuous, integration, server, CI, .net, developers """ googleAnalyticsId: "UA-36917965-1" insertYandexMetrika: true googleAnalyticsDomain: "solidbuild.net" # The website's styles styles: [ '/vendor/normalize.css' '/vendor/h5bp.css' '//fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,300,400,600,700&amp;subset=latin' '/css/solidbuild.css' '//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' ] # The website's scripts scripts: [ '/vendor/jquery-min.js' '/js/script.js' ] # ----------------------------- # Helper Functions # Get the prepared site/document title # Often we would like to specify particular formatting to our page's title # we can apply that formatting here getPreparedTitle: -> # if we have a document title, then we should use that and suffix the site's title onto it if @document.title "#{@document.title} / #{@site.title}" # if our document does not have it's own title, then we should just use the site's title else @site.title # Get the prepared site/document description getPreparedDescription: -> # if we have a document description, then we should use that, otherwise use the site's description @document.description or @site.description # Get the prepared site/document keywords getPreparedKeywords: -> # Merge the document keywords with the site keywords @site.keywords.concat(@document.keywords or []).join(', ') getPreparedArticleTags: (tags) -> # Merge the document keywords with the site keywords tags.concat(tags or []).join(', ') # Post part before “cut” cuttedContent: (content) -> if @hasReadMore content cutIdx = content.search @cutTag content[0..cutIdx-1] else content # Has “cut”? hasReadMore: (content) -> content and ((content.search @cutTag) isnt -1) getTagUrl: (tag) -> doc = docpad.getFile({tag:tag}) return doc?.get('url') or '' collections: articles: -> @getCollection("html").findAllLive({kind:'blogpost'},[{blogDate:-1}]).on "add", (model) -> model.setMetaDefaults({layout:"posts",postAuthor:"Solid Build Team"}) # Plugins configurations plugins: navlinks: collections: articles: -1 cleanurls: static: true trailingSlashes: true tags: extension: '.html.eco' injectDocumentHelper: (document) -> document.setMeta( layout: 'tagcloud' data: """ <%- @partial('tag', @) %> """ ) # ================================= # Environments environments: development: templateData: site: url: 'http://localhost:9778' # ================================= # DocPad Events # Here we can define handlers for events that DocPad fires # You can find a full listing of events on the DocPad Wiki events: # Server Extend # Used to add our own custom routes to the server before the docpad routes are added serverExtend: (opts) -> # Extract the server from the options {server} = opts docpad = @docpad # As we are now running in an event, # ensure we are using the latest copy of the docpad configuraiton # and fetch our urls from it latestConfig = docpad.getConfig() oldUrls = latestConfig.templateData.site.oldUrls or [] newUrl = latestConfig.templateData.site.url # Redirect any requests accessing one of our sites oldUrls to the new site url server.use (req,res,next) -> if req.headers.host in oldUrls res.redirect(newUrl+req.url, 301) else next() } # Export our DocPad Configuration module.exports = docpadConfig
true
# The DocPad Configuration File # It is simply a CoffeeScript Object which is parsed by CSON docpadConfig = { # ================================= # Template Data # These are variables that will be accessible via our templates # To access one of these within our templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ templateData: cutTag: '<!-- cut -->' # Specify some site properties site: # The production url of our website. Used in sitemap and rss feed url: "http://solidbuild.net" # Here are some old site urls that you would like to redirect from oldUrls: [ 'www.website.com', 'website.herokuapp.com' ] # The default title of our website title: "SolidBuild" # The title of RSS rssTitle: "SolidBuild" # Author name used in copyrights and meta data author: "PI:EMAIL:<EMAIL>END_PI" email: "PI:EMAIL:<EMAIL>END_PI" # Change to your disqus name or comment it out to disable comments disqus_shortname: "solidbuild" # The website description (for SEO) description: """ SolidBuild — continuous integration server """ # The website keywords (for SEO) separated by commas keywords: """ continuous, integration, server, CI, .net, developers """ googleAnalyticsId: "UA-36917965-1" insertYandexMetrika: true googleAnalyticsDomain: "solidbuild.net" # The website's styles styles: [ '/vendor/normalize.css' '/vendor/h5bp.css' '//fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,300,400,600,700&amp;subset=latin' '/css/solidbuild.css' '//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' ] # The website's scripts scripts: [ '/vendor/jquery-min.js' '/js/script.js' ] # ----------------------------- # Helper Functions # Get the prepared site/document title # Often we would like to specify particular formatting to our page's title # we can apply that formatting here getPreparedTitle: -> # if we have a document title, then we should use that and suffix the site's title onto it if @document.title "#{@document.title} / #{@site.title}" # if our document does not have it's own title, then we should just use the site's title else @site.title # Get the prepared site/document description getPreparedDescription: -> # if we have a document description, then we should use that, otherwise use the site's description @document.description or @site.description # Get the prepared site/document keywords getPreparedKeywords: -> # Merge the document keywords with the site keywords @site.keywords.concat(@document.keywords or []).join(', ') getPreparedArticleTags: (tags) -> # Merge the document keywords with the site keywords tags.concat(tags or []).join(', ') # Post part before “cut” cuttedContent: (content) -> if @hasReadMore content cutIdx = content.search @cutTag content[0..cutIdx-1] else content # Has “cut”? hasReadMore: (content) -> content and ((content.search @cutTag) isnt -1) getTagUrl: (tag) -> doc = docpad.getFile({tag:tag}) return doc?.get('url') or '' collections: articles: -> @getCollection("html").findAllLive({kind:'blogpost'},[{blogDate:-1}]).on "add", (model) -> model.setMetaDefaults({layout:"posts",postAuthor:"Solid Build Team"}) # Plugins configurations plugins: navlinks: collections: articles: -1 cleanurls: static: true trailingSlashes: true tags: extension: '.html.eco' injectDocumentHelper: (document) -> document.setMeta( layout: 'tagcloud' data: """ <%- @partial('tag', @) %> """ ) # ================================= # Environments environments: development: templateData: site: url: 'http://localhost:9778' # ================================= # DocPad Events # Here we can define handlers for events that DocPad fires # You can find a full listing of events on the DocPad Wiki events: # Server Extend # Used to add our own custom routes to the server before the docpad routes are added serverExtend: (opts) -> # Extract the server from the options {server} = opts docpad = @docpad # As we are now running in an event, # ensure we are using the latest copy of the docpad configuraiton # and fetch our urls from it latestConfig = docpad.getConfig() oldUrls = latestConfig.templateData.site.oldUrls or [] newUrl = latestConfig.templateData.site.url # Redirect any requests accessing one of our sites oldUrls to the new site url server.use (req,res,next) -> if req.headers.host in oldUrls res.redirect(newUrl+req.url, 301) else next() } # Export our DocPad Configuration module.exports = docpadConfig
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9990748763084412, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-fs-read-stream-err.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") fs = require("fs") stream = fs.createReadStream(__filename, bufferSize: 64 ) err = new Error("BAM") stream.on "error", common.mustCall(errorHandler = (err_) -> console.error "error event" process.nextTick -> assert.equal stream.fd, null assert.equal err_, err return return ) fs.close = common.mustCall((fd_, cb) -> assert.equal fd_, stream.fd process.nextTick cb return ) read = fs.read fs.read = -> # first time is ok. read.apply fs, arguments # then it breaks fs.read = -> cb = arguments[arguments.length - 1] process.nextTick -> cb err return # and should not be called again! fs.read = -> throw new Error("BOOM!")return return return stream.on "data", (buf) -> stream.on "data", assert.fail # no more 'data' events should follow return
47333
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") fs = require("fs") stream = fs.createReadStream(__filename, bufferSize: 64 ) err = new Error("BAM") stream.on "error", common.mustCall(errorHandler = (err_) -> console.error "error event" process.nextTick -> assert.equal stream.fd, null assert.equal err_, err return return ) fs.close = common.mustCall((fd_, cb) -> assert.equal fd_, stream.fd process.nextTick cb return ) read = fs.read fs.read = -> # first time is ok. read.apply fs, arguments # then it breaks fs.read = -> cb = arguments[arguments.length - 1] process.nextTick -> cb err return # and should not be called again! fs.read = -> throw new Error("BOOM!")return return return stream.on "data", (buf) -> stream.on "data", assert.fail # no more 'data' events should follow return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") fs = require("fs") stream = fs.createReadStream(__filename, bufferSize: 64 ) err = new Error("BAM") stream.on "error", common.mustCall(errorHandler = (err_) -> console.error "error event" process.nextTick -> assert.equal stream.fd, null assert.equal err_, err return return ) fs.close = common.mustCall((fd_, cb) -> assert.equal fd_, stream.fd process.nextTick cb return ) read = fs.read fs.read = -> # first time is ok. read.apply fs, arguments # then it breaks fs.read = -> cb = arguments[arguments.length - 1] process.nextTick -> cb err return # and should not be called again! fs.read = -> throw new Error("BOOM!")return return return stream.on "data", (buf) -> stream.on "data", assert.fail # no more 'data' events should follow return
[ { "context": "###\nCopyright (c) 2014 Ramesh Nair (hiddentao.com)\n\nPermission is hereby granted, fr", "end": 34, "score": 0.9998831748962402, "start": 23, "tag": "NAME", "value": "Ramesh Nair" } ]
test/select.test.coffee
SimeonC/squel
0
### Copyright (c) 2014 Ramesh Nair (hiddentao.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### squel = require "../squel-basic" {_, testCreator, assert, expect, should} = require './testbase' test = testCreator() test['SELECT builder'] = beforeEach: -> @func = squel.select @inst = @func() 'instanceof QueryBuilder': -> assert.instanceOf @inst, squel.cls.QueryBuilder 'constructor': 'override options': -> @inst = squel.select usingValuePlaceholders: true dummy: true expectedOptions = _.extend {}, squel.cls.DefaultQueryBuilderOptions, usingValuePlaceholders: true dummy: true for block in @inst.blocks if (block instanceof squel.cls.FromTableBlock) or (block instanceof squel.cls.JoinBlock) or (block instanceof squel.cls.UnionBlock) assert.same _.extend({}, expectedOptions, { allowNested: true }), block.options else assert.same expectedOptions, block.options 'override blocks': -> block = new squel.cls.StringBlock('SELECT') @inst = @func {}, [block] assert.same [block], @inst.blocks 'build query': 'need to call from() first': -> assert.throws (=> @inst.toString()), 'from() needs to be called' '>> from(table).from(table2, alias2)': beforeEach: -> @inst.from('table').from('table2', 'alias2') toString: -> assert.same @inst.toString(), 'SELECT * FROM table, table2 `alias2`' '>> field(squel.select().field("MAX(score)").FROM("scores"), fa1)': beforeEach: -> @inst.field(squel.select().field("MAX(score)").from("scores"), 'fa1') toString: -> assert.same @inst.toString(), 'SELECT (SELECT MAX(score) FROM scores) AS "fa1" FROM table, table2 `alias2`' '>> field(field1, fa1) >> field(field2)': beforeEach: -> @inst.field('field1', 'fa1').field('field2') toString: -> assert.same @inst.toString(), 'SELECT field1 AS "fa1", field2 FROM table, table2 `alias2`' '>> distinct()': beforeEach: -> @inst.distinct() toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2`' '>> group(field) >> group(field2)': beforeEach: -> @inst.group('field').group('field2') toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` GROUP BY field, field2' '>> where(a = ?, squel.select().field("MAX(score)").from("scores"))': beforeEach: -> @subQuery = squel.select().field("MAX(score)").from("scores") @inst.where('a = ?', @subQuery) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = (SELECT MAX(score) FROM scores)) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = (SELECT MAX(score) FROM scores)) GROUP BY field, field2' values: [] } '>> where(squel.expr().and(a = ?, 1).and_begin().or(b = ?, 2).or(c = ?, 3).end())': beforeEach: -> @inst.where(squel.expr().and("a = ?", 1).and_begin().or("b = ?", 2).or("c = ?", 3).end()) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = 1 AND (b = 2 OR c = 3)) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = ? AND (b = ? OR c = ?)) GROUP BY field, field2' values: [1, 2, 3] } '>> where(squel.expr().and(a = ?, QueryBuilder).and_begin().or(b = ?, 2).or(c = ?, 3).end())': beforeEach: -> subQuery = squel.select().field('field1').from('table1').where('field2 = ?', 10) @inst.where(squel.expr().and("a = ?", subQuery).and_begin().or("b = ?", 2).or("c = ?", 3).end()) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = (SELECT field1 FROM table1 WHERE (field2 = 10)) AND (b = 2 OR c = 3)) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = (SELECT field1 FROM table1 WHERE (field2 = ?)) AND (b = ? OR c = ?)) GROUP BY field, field2' values: [10, 2, 3] } '>> where(a = ?, null)': beforeEach: -> @inst.where('a = ?', null) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = NULL) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = ?) GROUP BY field, field2' values: [null] } '>> where(a = ?, 1)': beforeEach: -> @inst.where('a = ?', 1) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = 1) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = ?) GROUP BY field, field2' values: [1] } '>> join(other_table)': beforeEach: -> @inst.join('other_table') toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2' '>> order(a, true)': beforeEach: -> @inst.order('a', true) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2 ORDER BY a ASC' '>> limit(2)': beforeEach: -> @inst.limit(2) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2 ORDER BY a ASC LIMIT 2' '>> offset(3)': beforeEach: -> @inst.offset(3) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2 ORDER BY a ASC LIMIT 2 OFFSET 3' '>> order(DIST(?,?), true, 2, 3)': beforeEach: -> @inst.order('DIST(?, ?)', true, 2, false) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2 ORDER BY DIST(2, FALSE) ASC' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = ?) GROUP BY field, field2 ORDER BY DIST(?, ?) ASC' values: [1, 2, false] } '>> join(other_table, condition = expr())': beforeEach: -> subQuery = squel.select().field('abc').from('table1').where('adf = ?', 'today1') subQuery2 = squel.select().field('xyz').from('table2').where('adf = ?', 'today2') expr = squel.expr().and('field1 = ?', subQuery) @inst.join('other_table', null, expr) @inst.where('def IN ?', subQuery2) toString: -> assert.same @inst.toString(), "SELECT DISTINCT field1 AS \"fa1\", field2 FROM table, table2 `alias2` INNER JOIN other_table ON (field1 = (SELECT abc FROM table1 WHERE (adf = 'today1'))) WHERE (a = 1) AND (def IN (SELECT xyz FROM table2 WHERE (adf = 'today2'))) GROUP BY field, field2" toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table ON (field1 = (SELECT abc FROM table1 WHERE (adf = ?))) WHERE (a = ?) AND (def IN (SELECT xyz FROM table2 WHERE (adf = ?))) GROUP BY field, field2', values: ["today1",1,"today2"] } 'nested queries': 'basic': -> inner1 = squel.select().from('students') inner2 = squel.select().from('scores') @inst.from(inner1).from(inner2, 'scores') assert.same @inst.toString(), "SELECT * FROM (SELECT * FROM students), (SELECT * FROM scores) `scores`" 'deep nesting': -> inner1 = squel.select().from('students') inner2 = squel.select().from(inner1) @inst.from(inner2) assert.same @inst.toString(), "SELECT * FROM (SELECT * FROM (SELECT * FROM students))" 'nesting in JOINs': -> inner1 = squel.select().from('students') inner2 = squel.select().from(inner1) @inst.from('schools').join(inner2, 'meh', 'meh.ID = ID') assert.same @inst.toString(), "SELECT * FROM schools INNER JOIN (SELECT * FROM (SELECT * FROM students)) `meh` ON (meh.ID = ID)" 'nesting in JOINs with params': -> inner1 = squel.select().from('students').where('age = ?', 6) inner2 = squel.select().from(inner1) @inst.from('schools').where('school_type = ?', 'junior').join(inner2, 'meh', 'meh.ID = ID') assert.same @inst.toString(), "SELECT * FROM schools INNER JOIN (SELECT * FROM (SELECT * FROM students WHERE (age = 6))) `meh` ON (meh.ID = ID) WHERE (school_type = 'junior')" assert.same @inst.toParam(), { "text": "SELECT * FROM schools INNER JOIN (SELECT * FROM (SELECT * FROM students WHERE (age = ?))) `meh` ON (meh.ID = ID) WHERE (school_type = ?)", "values": [6,'junior'] } assert.same @inst.toParam({ "numberedParametersStartAt": 1}), { "text": "SELECT * FROM schools INNER JOIN (SELECT * FROM (SELECT * FROM students WHERE (age = $1))) `meh` ON (meh.ID = ID) WHERE (school_type = $2)", "values": [6,'junior'] } 'cloning': -> newinst = @inst.from('students').limit(10).clone() newinst.limit(20) assert.same 'SELECT * FROM students LIMIT 10', @inst.toString() assert.same 'SELECT * FROM students LIMIT 20', newinst.toString() 'is nestable': -> assert.same true, @inst.isNestable() 'can specify block separator': -> assert.same squel.select({separator: '\n'}) .field('thing') .from('table') .toString(), """ SELECT thing FROM table """ 'UNION JOINs': 'Two Queries NO Params': beforeEach: -> @qry1 = squel.select().field('name').from('students').where('age > 15') @qry2 = squel.select().field('name').from('students').where('age < 6') @qry1.union(@qry2) toString: -> assert.same @qry1.toString(), """ SELECT name FROM students WHERE (age > 15) UNION (SELECT name FROM students WHERE (age < 6)) """ toParam: -> assert.same @qry1.toParam(), { "text": "SELECT name FROM students WHERE (age > 15) UNION (SELECT name FROM students WHERE (age < 6))" "values": [ ] } 'Two Queries with Params': beforeEach: -> @qry1 = squel.select().field('name').from('students').where('age > ?', 15) @qry2 = squel.select().field('name').from('students').where('age < ?', 6) @qry1.union(@qry2) toString: -> assert.same @qry1.toString(), """ SELECT name FROM students WHERE (age > 15) UNION (SELECT name FROM students WHERE (age < 6)) """ toParam: -> assert.same @qry1.toParam(), { "text": "SELECT name FROM students WHERE (age > ?) UNION (SELECT name FROM students WHERE (age < ?))" "values": [ 15 6 ] } 'Three Queries': beforeEach: -> @qry1 = squel.select().field('name').from('students').where('age > ?', 15) @qry2 = squel.select().field('name').from('students').where('age < 6') @qry3 = squel.select().field('name').from('students').where('age = ?', 8) @qry1.union(@qry2) @qry1.union(@qry3) toParam: -> assert.same @qry1.toParam(), { "text": "SELECT name FROM students WHERE (age > ?) UNION (SELECT name FROM students WHERE (age < 6)) UNION (SELECT name FROM students WHERE (age = ?))" "values": [ 15 8 ] } 'toParam(2)': -> assert.same @qry1.toParam({ "numberedParametersStartAt": 2}), { "text": "SELECT name FROM students WHERE (age > $2) UNION (SELECT name FROM students WHERE (age < 6)) UNION (SELECT name FROM students WHERE (age = $3))" "values": [ 15 8 ] } 'Multi-Parameter Query': beforeEach: -> @qry1 = squel.select().field('name').from('students').where('age > ?', 15) @qry2 = squel.select().field('name').from('students').where('age < ?', 6) @qry3 = squel.select().field('name').from('students').where('age = ?', 8) @qry4 = squel.select().field('name').from('students').where('age IN [?, ?]', 2, 10) @qry1.union(@qry2) @qry1.union(@qry3) @qry4.union_all(@qry1) toString: -> assert.same @qry4.toString(), """ SELECT name FROM students WHERE (age IN [2, 10]) UNION ALL (SELECT name FROM students WHERE (age > 15) UNION (SELECT name FROM students WHERE (age < 6)) UNION (SELECT name FROM students WHERE (age = 8))) """ toParam: -> assert.same @qry4.toParam({ "numberedParametersStartAt": 1}), { "text": "SELECT name FROM students WHERE (age IN [$1, $2]) UNION ALL (SELECT name FROM students WHERE (age > $3) UNION (SELECT name FROM students WHERE (age < $4)) UNION (SELECT name FROM students WHERE (age = $5)))" "values": [ 2 10 15 6 8 ] } module?.exports[require('path').basename(__filename)] = test
69160
### Copyright (c) 2014 <NAME> (hiddentao.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### squel = require "../squel-basic" {_, testCreator, assert, expect, should} = require './testbase' test = testCreator() test['SELECT builder'] = beforeEach: -> @func = squel.select @inst = @func() 'instanceof QueryBuilder': -> assert.instanceOf @inst, squel.cls.QueryBuilder 'constructor': 'override options': -> @inst = squel.select usingValuePlaceholders: true dummy: true expectedOptions = _.extend {}, squel.cls.DefaultQueryBuilderOptions, usingValuePlaceholders: true dummy: true for block in @inst.blocks if (block instanceof squel.cls.FromTableBlock) or (block instanceof squel.cls.JoinBlock) or (block instanceof squel.cls.UnionBlock) assert.same _.extend({}, expectedOptions, { allowNested: true }), block.options else assert.same expectedOptions, block.options 'override blocks': -> block = new squel.cls.StringBlock('SELECT') @inst = @func {}, [block] assert.same [block], @inst.blocks 'build query': 'need to call from() first': -> assert.throws (=> @inst.toString()), 'from() needs to be called' '>> from(table).from(table2, alias2)': beforeEach: -> @inst.from('table').from('table2', 'alias2') toString: -> assert.same @inst.toString(), 'SELECT * FROM table, table2 `alias2`' '>> field(squel.select().field("MAX(score)").FROM("scores"), fa1)': beforeEach: -> @inst.field(squel.select().field("MAX(score)").from("scores"), 'fa1') toString: -> assert.same @inst.toString(), 'SELECT (SELECT MAX(score) FROM scores) AS "fa1" FROM table, table2 `alias2`' '>> field(field1, fa1) >> field(field2)': beforeEach: -> @inst.field('field1', 'fa1').field('field2') toString: -> assert.same @inst.toString(), 'SELECT field1 AS "fa1", field2 FROM table, table2 `alias2`' '>> distinct()': beforeEach: -> @inst.distinct() toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2`' '>> group(field) >> group(field2)': beforeEach: -> @inst.group('field').group('field2') toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` GROUP BY field, field2' '>> where(a = ?, squel.select().field("MAX(score)").from("scores"))': beforeEach: -> @subQuery = squel.select().field("MAX(score)").from("scores") @inst.where('a = ?', @subQuery) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = (SELECT MAX(score) FROM scores)) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = (SELECT MAX(score) FROM scores)) GROUP BY field, field2' values: [] } '>> where(squel.expr().and(a = ?, 1).and_begin().or(b = ?, 2).or(c = ?, 3).end())': beforeEach: -> @inst.where(squel.expr().and("a = ?", 1).and_begin().or("b = ?", 2).or("c = ?", 3).end()) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = 1 AND (b = 2 OR c = 3)) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = ? AND (b = ? OR c = ?)) GROUP BY field, field2' values: [1, 2, 3] } '>> where(squel.expr().and(a = ?, QueryBuilder).and_begin().or(b = ?, 2).or(c = ?, 3).end())': beforeEach: -> subQuery = squel.select().field('field1').from('table1').where('field2 = ?', 10) @inst.where(squel.expr().and("a = ?", subQuery).and_begin().or("b = ?", 2).or("c = ?", 3).end()) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = (SELECT field1 FROM table1 WHERE (field2 = 10)) AND (b = 2 OR c = 3)) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = (SELECT field1 FROM table1 WHERE (field2 = ?)) AND (b = ? OR c = ?)) GROUP BY field, field2' values: [10, 2, 3] } '>> where(a = ?, null)': beforeEach: -> @inst.where('a = ?', null) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = NULL) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = ?) GROUP BY field, field2' values: [null] } '>> where(a = ?, 1)': beforeEach: -> @inst.where('a = ?', 1) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = 1) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = ?) GROUP BY field, field2' values: [1] } '>> join(other_table)': beforeEach: -> @inst.join('other_table') toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2' '>> order(a, true)': beforeEach: -> @inst.order('a', true) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2 ORDER BY a ASC' '>> limit(2)': beforeEach: -> @inst.limit(2) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2 ORDER BY a ASC LIMIT 2' '>> offset(3)': beforeEach: -> @inst.offset(3) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2 ORDER BY a ASC LIMIT 2 OFFSET 3' '>> order(DIST(?,?), true, 2, 3)': beforeEach: -> @inst.order('DIST(?, ?)', true, 2, false) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2 ORDER BY DIST(2, FALSE) ASC' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = ?) GROUP BY field, field2 ORDER BY DIST(?, ?) ASC' values: [1, 2, false] } '>> join(other_table, condition = expr())': beforeEach: -> subQuery = squel.select().field('abc').from('table1').where('adf = ?', 'today1') subQuery2 = squel.select().field('xyz').from('table2').where('adf = ?', 'today2') expr = squel.expr().and('field1 = ?', subQuery) @inst.join('other_table', null, expr) @inst.where('def IN ?', subQuery2) toString: -> assert.same @inst.toString(), "SELECT DISTINCT field1 AS \"fa1\", field2 FROM table, table2 `alias2` INNER JOIN other_table ON (field1 = (SELECT abc FROM table1 WHERE (adf = 'today1'))) WHERE (a = 1) AND (def IN (SELECT xyz FROM table2 WHERE (adf = 'today2'))) GROUP BY field, field2" toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table ON (field1 = (SELECT abc FROM table1 WHERE (adf = ?))) WHERE (a = ?) AND (def IN (SELECT xyz FROM table2 WHERE (adf = ?))) GROUP BY field, field2', values: ["today1",1,"today2"] } 'nested queries': 'basic': -> inner1 = squel.select().from('students') inner2 = squel.select().from('scores') @inst.from(inner1).from(inner2, 'scores') assert.same @inst.toString(), "SELECT * FROM (SELECT * FROM students), (SELECT * FROM scores) `scores`" 'deep nesting': -> inner1 = squel.select().from('students') inner2 = squel.select().from(inner1) @inst.from(inner2) assert.same @inst.toString(), "SELECT * FROM (SELECT * FROM (SELECT * FROM students))" 'nesting in JOINs': -> inner1 = squel.select().from('students') inner2 = squel.select().from(inner1) @inst.from('schools').join(inner2, 'meh', 'meh.ID = ID') assert.same @inst.toString(), "SELECT * FROM schools INNER JOIN (SELECT * FROM (SELECT * FROM students)) `meh` ON (meh.ID = ID)" 'nesting in JOINs with params': -> inner1 = squel.select().from('students').where('age = ?', 6) inner2 = squel.select().from(inner1) @inst.from('schools').where('school_type = ?', 'junior').join(inner2, 'meh', 'meh.ID = ID') assert.same @inst.toString(), "SELECT * FROM schools INNER JOIN (SELECT * FROM (SELECT * FROM students WHERE (age = 6))) `meh` ON (meh.ID = ID) WHERE (school_type = 'junior')" assert.same @inst.toParam(), { "text": "SELECT * FROM schools INNER JOIN (SELECT * FROM (SELECT * FROM students WHERE (age = ?))) `meh` ON (meh.ID = ID) WHERE (school_type = ?)", "values": [6,'junior'] } assert.same @inst.toParam({ "numberedParametersStartAt": 1}), { "text": "SELECT * FROM schools INNER JOIN (SELECT * FROM (SELECT * FROM students WHERE (age = $1))) `meh` ON (meh.ID = ID) WHERE (school_type = $2)", "values": [6,'junior'] } 'cloning': -> newinst = @inst.from('students').limit(10).clone() newinst.limit(20) assert.same 'SELECT * FROM students LIMIT 10', @inst.toString() assert.same 'SELECT * FROM students LIMIT 20', newinst.toString() 'is nestable': -> assert.same true, @inst.isNestable() 'can specify block separator': -> assert.same squel.select({separator: '\n'}) .field('thing') .from('table') .toString(), """ SELECT thing FROM table """ 'UNION JOINs': 'Two Queries NO Params': beforeEach: -> @qry1 = squel.select().field('name').from('students').where('age > 15') @qry2 = squel.select().field('name').from('students').where('age < 6') @qry1.union(@qry2) toString: -> assert.same @qry1.toString(), """ SELECT name FROM students WHERE (age > 15) UNION (SELECT name FROM students WHERE (age < 6)) """ toParam: -> assert.same @qry1.toParam(), { "text": "SELECT name FROM students WHERE (age > 15) UNION (SELECT name FROM students WHERE (age < 6))" "values": [ ] } 'Two Queries with Params': beforeEach: -> @qry1 = squel.select().field('name').from('students').where('age > ?', 15) @qry2 = squel.select().field('name').from('students').where('age < ?', 6) @qry1.union(@qry2) toString: -> assert.same @qry1.toString(), """ SELECT name FROM students WHERE (age > 15) UNION (SELECT name FROM students WHERE (age < 6)) """ toParam: -> assert.same @qry1.toParam(), { "text": "SELECT name FROM students WHERE (age > ?) UNION (SELECT name FROM students WHERE (age < ?))" "values": [ 15 6 ] } 'Three Queries': beforeEach: -> @qry1 = squel.select().field('name').from('students').where('age > ?', 15) @qry2 = squel.select().field('name').from('students').where('age < 6') @qry3 = squel.select().field('name').from('students').where('age = ?', 8) @qry1.union(@qry2) @qry1.union(@qry3) toParam: -> assert.same @qry1.toParam(), { "text": "SELECT name FROM students WHERE (age > ?) UNION (SELECT name FROM students WHERE (age < 6)) UNION (SELECT name FROM students WHERE (age = ?))" "values": [ 15 8 ] } 'toParam(2)': -> assert.same @qry1.toParam({ "numberedParametersStartAt": 2}), { "text": "SELECT name FROM students WHERE (age > $2) UNION (SELECT name FROM students WHERE (age < 6)) UNION (SELECT name FROM students WHERE (age = $3))" "values": [ 15 8 ] } 'Multi-Parameter Query': beforeEach: -> @qry1 = squel.select().field('name').from('students').where('age > ?', 15) @qry2 = squel.select().field('name').from('students').where('age < ?', 6) @qry3 = squel.select().field('name').from('students').where('age = ?', 8) @qry4 = squel.select().field('name').from('students').where('age IN [?, ?]', 2, 10) @qry1.union(@qry2) @qry1.union(@qry3) @qry4.union_all(@qry1) toString: -> assert.same @qry4.toString(), """ SELECT name FROM students WHERE (age IN [2, 10]) UNION ALL (SELECT name FROM students WHERE (age > 15) UNION (SELECT name FROM students WHERE (age < 6)) UNION (SELECT name FROM students WHERE (age = 8))) """ toParam: -> assert.same @qry4.toParam({ "numberedParametersStartAt": 1}), { "text": "SELECT name FROM students WHERE (age IN [$1, $2]) UNION ALL (SELECT name FROM students WHERE (age > $3) UNION (SELECT name FROM students WHERE (age < $4)) UNION (SELECT name FROM students WHERE (age = $5)))" "values": [ 2 10 15 6 8 ] } module?.exports[require('path').basename(__filename)] = test
true
### Copyright (c) 2014 PI:NAME:<NAME>END_PI (hiddentao.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### squel = require "../squel-basic" {_, testCreator, assert, expect, should} = require './testbase' test = testCreator() test['SELECT builder'] = beforeEach: -> @func = squel.select @inst = @func() 'instanceof QueryBuilder': -> assert.instanceOf @inst, squel.cls.QueryBuilder 'constructor': 'override options': -> @inst = squel.select usingValuePlaceholders: true dummy: true expectedOptions = _.extend {}, squel.cls.DefaultQueryBuilderOptions, usingValuePlaceholders: true dummy: true for block in @inst.blocks if (block instanceof squel.cls.FromTableBlock) or (block instanceof squel.cls.JoinBlock) or (block instanceof squel.cls.UnionBlock) assert.same _.extend({}, expectedOptions, { allowNested: true }), block.options else assert.same expectedOptions, block.options 'override blocks': -> block = new squel.cls.StringBlock('SELECT') @inst = @func {}, [block] assert.same [block], @inst.blocks 'build query': 'need to call from() first': -> assert.throws (=> @inst.toString()), 'from() needs to be called' '>> from(table).from(table2, alias2)': beforeEach: -> @inst.from('table').from('table2', 'alias2') toString: -> assert.same @inst.toString(), 'SELECT * FROM table, table2 `alias2`' '>> field(squel.select().field("MAX(score)").FROM("scores"), fa1)': beforeEach: -> @inst.field(squel.select().field("MAX(score)").from("scores"), 'fa1') toString: -> assert.same @inst.toString(), 'SELECT (SELECT MAX(score) FROM scores) AS "fa1" FROM table, table2 `alias2`' '>> field(field1, fa1) >> field(field2)': beforeEach: -> @inst.field('field1', 'fa1').field('field2') toString: -> assert.same @inst.toString(), 'SELECT field1 AS "fa1", field2 FROM table, table2 `alias2`' '>> distinct()': beforeEach: -> @inst.distinct() toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2`' '>> group(field) >> group(field2)': beforeEach: -> @inst.group('field').group('field2') toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` GROUP BY field, field2' '>> where(a = ?, squel.select().field("MAX(score)").from("scores"))': beforeEach: -> @subQuery = squel.select().field("MAX(score)").from("scores") @inst.where('a = ?', @subQuery) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = (SELECT MAX(score) FROM scores)) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = (SELECT MAX(score) FROM scores)) GROUP BY field, field2' values: [] } '>> where(squel.expr().and(a = ?, 1).and_begin().or(b = ?, 2).or(c = ?, 3).end())': beforeEach: -> @inst.where(squel.expr().and("a = ?", 1).and_begin().or("b = ?", 2).or("c = ?", 3).end()) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = 1 AND (b = 2 OR c = 3)) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = ? AND (b = ? OR c = ?)) GROUP BY field, field2' values: [1, 2, 3] } '>> where(squel.expr().and(a = ?, QueryBuilder).and_begin().or(b = ?, 2).or(c = ?, 3).end())': beforeEach: -> subQuery = squel.select().field('field1').from('table1').where('field2 = ?', 10) @inst.where(squel.expr().and("a = ?", subQuery).and_begin().or("b = ?", 2).or("c = ?", 3).end()) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = (SELECT field1 FROM table1 WHERE (field2 = 10)) AND (b = 2 OR c = 3)) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = (SELECT field1 FROM table1 WHERE (field2 = ?)) AND (b = ? OR c = ?)) GROUP BY field, field2' values: [10, 2, 3] } '>> where(a = ?, null)': beforeEach: -> @inst.where('a = ?', null) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = NULL) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = ?) GROUP BY field, field2' values: [null] } '>> where(a = ?, 1)': beforeEach: -> @inst.where('a = ?', 1) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = 1) GROUP BY field, field2' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` WHERE (a = ?) GROUP BY field, field2' values: [1] } '>> join(other_table)': beforeEach: -> @inst.join('other_table') toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2' '>> order(a, true)': beforeEach: -> @inst.order('a', true) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2 ORDER BY a ASC' '>> limit(2)': beforeEach: -> @inst.limit(2) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2 ORDER BY a ASC LIMIT 2' '>> offset(3)': beforeEach: -> @inst.offset(3) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2 ORDER BY a ASC LIMIT 2 OFFSET 3' '>> order(DIST(?,?), true, 2, 3)': beforeEach: -> @inst.order('DIST(?, ?)', true, 2, false) toString: -> assert.same @inst.toString(), 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = 1) GROUP BY field, field2 ORDER BY DIST(2, FALSE) ASC' toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table WHERE (a = ?) GROUP BY field, field2 ORDER BY DIST(?, ?) ASC' values: [1, 2, false] } '>> join(other_table, condition = expr())': beforeEach: -> subQuery = squel.select().field('abc').from('table1').where('adf = ?', 'today1') subQuery2 = squel.select().field('xyz').from('table2').where('adf = ?', 'today2') expr = squel.expr().and('field1 = ?', subQuery) @inst.join('other_table', null, expr) @inst.where('def IN ?', subQuery2) toString: -> assert.same @inst.toString(), "SELECT DISTINCT field1 AS \"fa1\", field2 FROM table, table2 `alias2` INNER JOIN other_table ON (field1 = (SELECT abc FROM table1 WHERE (adf = 'today1'))) WHERE (a = 1) AND (def IN (SELECT xyz FROM table2 WHERE (adf = 'today2'))) GROUP BY field, field2" toParam: -> assert.same @inst.toParam(), { text: 'SELECT DISTINCT field1 AS "fa1", field2 FROM table, table2 `alias2` INNER JOIN other_table ON (field1 = (SELECT abc FROM table1 WHERE (adf = ?))) WHERE (a = ?) AND (def IN (SELECT xyz FROM table2 WHERE (adf = ?))) GROUP BY field, field2', values: ["today1",1,"today2"] } 'nested queries': 'basic': -> inner1 = squel.select().from('students') inner2 = squel.select().from('scores') @inst.from(inner1).from(inner2, 'scores') assert.same @inst.toString(), "SELECT * FROM (SELECT * FROM students), (SELECT * FROM scores) `scores`" 'deep nesting': -> inner1 = squel.select().from('students') inner2 = squel.select().from(inner1) @inst.from(inner2) assert.same @inst.toString(), "SELECT * FROM (SELECT * FROM (SELECT * FROM students))" 'nesting in JOINs': -> inner1 = squel.select().from('students') inner2 = squel.select().from(inner1) @inst.from('schools').join(inner2, 'meh', 'meh.ID = ID') assert.same @inst.toString(), "SELECT * FROM schools INNER JOIN (SELECT * FROM (SELECT * FROM students)) `meh` ON (meh.ID = ID)" 'nesting in JOINs with params': -> inner1 = squel.select().from('students').where('age = ?', 6) inner2 = squel.select().from(inner1) @inst.from('schools').where('school_type = ?', 'junior').join(inner2, 'meh', 'meh.ID = ID') assert.same @inst.toString(), "SELECT * FROM schools INNER JOIN (SELECT * FROM (SELECT * FROM students WHERE (age = 6))) `meh` ON (meh.ID = ID) WHERE (school_type = 'junior')" assert.same @inst.toParam(), { "text": "SELECT * FROM schools INNER JOIN (SELECT * FROM (SELECT * FROM students WHERE (age = ?))) `meh` ON (meh.ID = ID) WHERE (school_type = ?)", "values": [6,'junior'] } assert.same @inst.toParam({ "numberedParametersStartAt": 1}), { "text": "SELECT * FROM schools INNER JOIN (SELECT * FROM (SELECT * FROM students WHERE (age = $1))) `meh` ON (meh.ID = ID) WHERE (school_type = $2)", "values": [6,'junior'] } 'cloning': -> newinst = @inst.from('students').limit(10).clone() newinst.limit(20) assert.same 'SELECT * FROM students LIMIT 10', @inst.toString() assert.same 'SELECT * FROM students LIMIT 20', newinst.toString() 'is nestable': -> assert.same true, @inst.isNestable() 'can specify block separator': -> assert.same squel.select({separator: '\n'}) .field('thing') .from('table') .toString(), """ SELECT thing FROM table """ 'UNION JOINs': 'Two Queries NO Params': beforeEach: -> @qry1 = squel.select().field('name').from('students').where('age > 15') @qry2 = squel.select().field('name').from('students').where('age < 6') @qry1.union(@qry2) toString: -> assert.same @qry1.toString(), """ SELECT name FROM students WHERE (age > 15) UNION (SELECT name FROM students WHERE (age < 6)) """ toParam: -> assert.same @qry1.toParam(), { "text": "SELECT name FROM students WHERE (age > 15) UNION (SELECT name FROM students WHERE (age < 6))" "values": [ ] } 'Two Queries with Params': beforeEach: -> @qry1 = squel.select().field('name').from('students').where('age > ?', 15) @qry2 = squel.select().field('name').from('students').where('age < ?', 6) @qry1.union(@qry2) toString: -> assert.same @qry1.toString(), """ SELECT name FROM students WHERE (age > 15) UNION (SELECT name FROM students WHERE (age < 6)) """ toParam: -> assert.same @qry1.toParam(), { "text": "SELECT name FROM students WHERE (age > ?) UNION (SELECT name FROM students WHERE (age < ?))" "values": [ 15 6 ] } 'Three Queries': beforeEach: -> @qry1 = squel.select().field('name').from('students').where('age > ?', 15) @qry2 = squel.select().field('name').from('students').where('age < 6') @qry3 = squel.select().field('name').from('students').where('age = ?', 8) @qry1.union(@qry2) @qry1.union(@qry3) toParam: -> assert.same @qry1.toParam(), { "text": "SELECT name FROM students WHERE (age > ?) UNION (SELECT name FROM students WHERE (age < 6)) UNION (SELECT name FROM students WHERE (age = ?))" "values": [ 15 8 ] } 'toParam(2)': -> assert.same @qry1.toParam({ "numberedParametersStartAt": 2}), { "text": "SELECT name FROM students WHERE (age > $2) UNION (SELECT name FROM students WHERE (age < 6)) UNION (SELECT name FROM students WHERE (age = $3))" "values": [ 15 8 ] } 'Multi-Parameter Query': beforeEach: -> @qry1 = squel.select().field('name').from('students').where('age > ?', 15) @qry2 = squel.select().field('name').from('students').where('age < ?', 6) @qry3 = squel.select().field('name').from('students').where('age = ?', 8) @qry4 = squel.select().field('name').from('students').where('age IN [?, ?]', 2, 10) @qry1.union(@qry2) @qry1.union(@qry3) @qry4.union_all(@qry1) toString: -> assert.same @qry4.toString(), """ SELECT name FROM students WHERE (age IN [2, 10]) UNION ALL (SELECT name FROM students WHERE (age > 15) UNION (SELECT name FROM students WHERE (age < 6)) UNION (SELECT name FROM students WHERE (age = 8))) """ toParam: -> assert.same @qry4.toParam({ "numberedParametersStartAt": 1}), { "text": "SELECT name FROM students WHERE (age IN [$1, $2]) UNION ALL (SELECT name FROM students WHERE (age > $3) UNION (SELECT name FROM students WHERE (age < $4)) UNION (SELECT name FROM students WHERE (age = $5)))" "values": [ 2 10 15 6 8 ] } module?.exports[require('path').basename(__filename)] = test
[ { "context": "ch/blob/master/src/helpers.coffee\n# Many thanks to Allan Berger, Jan Monschke, Martin Schürrer, Thomas Schranz, N", "end": 134, "score": 0.9998515844345093, "start": 122, "tag": "NAME", "value": "Allan Berger" }, { "context": "/src/helpers.coffee\n# Many thanks to Allan Berger, Jan Monschke, Martin Schürrer, Thomas Schranz, Nik Graf\n\nfs = ", "end": 148, "score": 0.9998244047164917, "start": 136, "tag": "NAME", "value": "Jan Monschke" }, { "context": "offee\n# Many thanks to Allan Berger, Jan Monschke, Martin Schürrer, Thomas Schranz, Nik Graf\n\nfs = require('fs')\npat", "end": 165, "score": 0.9998317956924438, "start": 150, "tag": "NAME", "value": "Martin Schürrer" }, { "context": "ks to Allan Berger, Jan Monschke, Martin Schürrer, Thomas Schranz, Nik Graf\n\nfs = require('fs')\npath = require('pat", "end": 181, "score": 0.9998379945755005, "start": 167, "tag": "NAME", "value": "Thomas Schranz" }, { "context": "er, Jan Monschke, Martin Schürrer, Thomas Schranz, Nik Graf\n\nfs = require('fs')\npath = require('path')\nutil =", "end": 191, "score": 0.9998435974121094, "start": 183, "tag": "NAME", "value": "Nik Graf" } ]
src/utils/copy.coffee
nponeccop/socketstream
0
# Based on recursive copy functions from https://github.com/brunch/brunch/blob/master/src/helpers.coffee # Many thanks to Allan Berger, Jan Monschke, Martin Schürrer, Thomas Schranz, Nik Graf fs = require('fs') path = require('path') util = require('util') # copy single file and executes callback when done exports.copyFile = (source, destination) -> read = fs.createReadStream(source) write = fs.createWriteStream(destination) util.pump read, write # walk through tree, creates directories and copy files exports.recursiveCopy = (source, destination) -> files = fs.readdirSync source # iterates over current directory files.forEach (file) -> sourcePath = path.join source, file destinationPath = path.join destination, file stats = fs.statSync sourcePath if stats.isDirectory() fs.mkdirSync destinationPath, 0755 exports.recursiveCopy sourcePath, destinationPath else exports.copyFile sourcePath, destinationPath
225593
# Based on recursive copy functions from https://github.com/brunch/brunch/blob/master/src/helpers.coffee # Many thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME> fs = require('fs') path = require('path') util = require('util') # copy single file and executes callback when done exports.copyFile = (source, destination) -> read = fs.createReadStream(source) write = fs.createWriteStream(destination) util.pump read, write # walk through tree, creates directories and copy files exports.recursiveCopy = (source, destination) -> files = fs.readdirSync source # iterates over current directory files.forEach (file) -> sourcePath = path.join source, file destinationPath = path.join destination, file stats = fs.statSync sourcePath if stats.isDirectory() fs.mkdirSync destinationPath, 0755 exports.recursiveCopy sourcePath, destinationPath else exports.copyFile sourcePath, destinationPath
true
# Based on recursive copy functions from https://github.com/brunch/brunch/blob/master/src/helpers.coffee # Many thanks to PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI fs = require('fs') path = require('path') util = require('util') # copy single file and executes callback when done exports.copyFile = (source, destination) -> read = fs.createReadStream(source) write = fs.createWriteStream(destination) util.pump read, write # walk through tree, creates directories and copy files exports.recursiveCopy = (source, destination) -> files = fs.readdirSync source # iterates over current directory files.forEach (file) -> sourcePath = path.join source, file destinationPath = path.join destination, file stats = fs.statSync sourcePath if stats.isDirectory() fs.mkdirSync destinationPath, 0755 exports.recursiveCopy sourcePath, destinationPath else exports.copyFile sourcePath, destinationPath
[ { "context": "eature', { image_versions: ['wide'] })\n id: \"52b347c59c18db5aef000208\"\n published: true\n key: \"1\"\n name:", "end": 413, "score": 0.9864937663078308, "start": 389, "tag": "KEY", "value": "52b347c59c18db5aef000208" }, { "context": "18db5aef000208\"\n published: true\n key: \"1\"\n name: \"Top 10 Posts\"\n item_type: \"Fea", "end": 450, "score": 0.8321687579154968, "start": 449, "tag": "KEY", "value": "1" } ]
src/desktop/test/models/featured_set.test.coffee
jo-rs/force
0
_ = require 'underscore' should = require 'should' Backbone = require 'backbone' FeaturedLink = require '../../models/featured_link.coffee' FeaturedSet = require '../../models/featured_set.coffee' { fabricate } = require '@artsy/antigravity' describe 'FeaturedSet', -> beforeEach -> @set = new FeaturedSet owner: fabricate('feature', { image_versions: ['wide'] }) id: "52b347c59c18db5aef000208" published: true key: "1" name: "Top 10 Posts" item_type: "FeaturedLink" type: "featured link" owner_type: "Feature" data: new Backbone.Collection [ fabricate 'featured_link' ], { model: FeaturedLink } it 'mixes in Markdown methods', -> @set.mdToHtml.should.be.an.instanceof Function describe '#models', -> it "provides access to an array of models", -> @set.models().should.have.lengthOf 1 @set.models().should.be.instanceOf Array @set.models()[0].should.be.instanceOf FeaturedLink
24985
_ = require 'underscore' should = require 'should' Backbone = require 'backbone' FeaturedLink = require '../../models/featured_link.coffee' FeaturedSet = require '../../models/featured_set.coffee' { fabricate } = require '@artsy/antigravity' describe 'FeaturedSet', -> beforeEach -> @set = new FeaturedSet owner: fabricate('feature', { image_versions: ['wide'] }) id: "<KEY>" published: true key: "<KEY>" name: "Top 10 Posts" item_type: "FeaturedLink" type: "featured link" owner_type: "Feature" data: new Backbone.Collection [ fabricate 'featured_link' ], { model: FeaturedLink } it 'mixes in Markdown methods', -> @set.mdToHtml.should.be.an.instanceof Function describe '#models', -> it "provides access to an array of models", -> @set.models().should.have.lengthOf 1 @set.models().should.be.instanceOf Array @set.models()[0].should.be.instanceOf FeaturedLink
true
_ = require 'underscore' should = require 'should' Backbone = require 'backbone' FeaturedLink = require '../../models/featured_link.coffee' FeaturedSet = require '../../models/featured_set.coffee' { fabricate } = require '@artsy/antigravity' describe 'FeaturedSet', -> beforeEach -> @set = new FeaturedSet owner: fabricate('feature', { image_versions: ['wide'] }) id: "PI:KEY:<KEY>END_PI" published: true key: "PI:KEY:<KEY>END_PI" name: "Top 10 Posts" item_type: "FeaturedLink" type: "featured link" owner_type: "Feature" data: new Backbone.Collection [ fabricate 'featured_link' ], { model: FeaturedLink } it 'mixes in Markdown methods', -> @set.mdToHtml.should.be.an.instanceof Function describe '#models', -> it "provides access to an array of models", -> @set.models().should.have.lengthOf 1 @set.models().should.be.instanceOf Array @set.models()[0].should.be.instanceOf FeaturedLink
[ { "context": "---------------------------------\np = new Person 'Robert', 'Paulson'\nlog p.full_name # Robert Paulson\nlog ", "end": 1895, "score": 0.9998712539672852, "start": 1889, "tag": "NAME", "value": "Robert" }, { "context": "-----------------------\np = new Person 'Robert', 'Paulson'\nlog p.full_name # Robert Paulson\nlog p.full_name", "end": 1906, "score": 0.9997539520263672, "start": 1899, "tag": "NAME", "value": "Paulson" }, { "context": "= new Person 'Robert', 'Paulson'\nlog p.full_name # Robert Paulson\nlog p.full_name = 'Space Monkey'\nlog p.last_name ", "end": 1940, "score": 0.999873697757721, "start": 1926, "tag": "NAME", "value": "Robert Paulson" }, { "context": "--------------------------\nm = new Mathematician 'Bill', 'Finite'\nlog m.favnumber\nlog m.first_name\nlog m", "end": 2152, "score": 0.8163418173789978, "start": 2148, "tag": "NAME", "value": "Bill" } ]
src/coffeescript-class-instance-properties.coffee
loveencounterflow/gaps-and-islands
0
'use strict' # thx to https://stackoverflow.com/a/15509083/256361 #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- log = console.log #----------------------------------------------------------------------------------------------------------- new_properties = ( me, P... ) -> Object.defineProperties me.prototype, P... #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- class Person #--------------------------------------------------------------------------------------------------------- constructor: ( @first_name, @last_name ) -> #--------------------------------------------------------------------------------------------------------- new_properties @, favnumber: get: -> 42 #--------------------------------------------------------------------------------------------------------- Object.defineProperties @prototype, full_name: get: -> "#{@first_name} #{@last_name}" set: ( full_name ) -> [ @first_name, @last_name ] = full_name.split ' ' #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- class Mathematician extends Person #--------------------------------------------------------------------------------------------------------- new_properties @, favnumber: get: -> Infinity #----------------------------------------------------------------------------------------------------------- p = new Person 'Robert', 'Paulson' log p.full_name # Robert Paulson log p.full_name = 'Space Monkey' log p.last_name # Monkey log p.favnumber #----------------------------------------------------------------------------------------------------------- m = new Mathematician 'Bill', 'Finite' log m.favnumber log m.first_name log m.last_name log m.full_name log m.full_name = 'Zeta Cardinal' log m
79851
'use strict' # thx to https://stackoverflow.com/a/15509083/256361 #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- log = console.log #----------------------------------------------------------------------------------------------------------- new_properties = ( me, P... ) -> Object.defineProperties me.prototype, P... #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- class Person #--------------------------------------------------------------------------------------------------------- constructor: ( @first_name, @last_name ) -> #--------------------------------------------------------------------------------------------------------- new_properties @, favnumber: get: -> 42 #--------------------------------------------------------------------------------------------------------- Object.defineProperties @prototype, full_name: get: -> "#{@first_name} #{@last_name}" set: ( full_name ) -> [ @first_name, @last_name ] = full_name.split ' ' #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- class Mathematician extends Person #--------------------------------------------------------------------------------------------------------- new_properties @, favnumber: get: -> Infinity #----------------------------------------------------------------------------------------------------------- p = new Person '<NAME>', '<NAME>' log p.full_name # <NAME> log p.full_name = 'Space Monkey' log p.last_name # Monkey log p.favnumber #----------------------------------------------------------------------------------------------------------- m = new Mathematician '<NAME>', 'Finite' log m.favnumber log m.first_name log m.last_name log m.full_name log m.full_name = 'Zeta Cardinal' log m
true
'use strict' # thx to https://stackoverflow.com/a/15509083/256361 #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- log = console.log #----------------------------------------------------------------------------------------------------------- new_properties = ( me, P... ) -> Object.defineProperties me.prototype, P... #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- class Person #--------------------------------------------------------------------------------------------------------- constructor: ( @first_name, @last_name ) -> #--------------------------------------------------------------------------------------------------------- new_properties @, favnumber: get: -> 42 #--------------------------------------------------------------------------------------------------------- Object.defineProperties @prototype, full_name: get: -> "#{@first_name} #{@last_name}" set: ( full_name ) -> [ @first_name, @last_name ] = full_name.split ' ' #=========================================================================================================== # #----------------------------------------------------------------------------------------------------------- class Mathematician extends Person #--------------------------------------------------------------------------------------------------------- new_properties @, favnumber: get: -> Infinity #----------------------------------------------------------------------------------------------------------- p = new Person 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI' log p.full_name # PI:NAME:<NAME>END_PI log p.full_name = 'Space Monkey' log p.last_name # Monkey log p.favnumber #----------------------------------------------------------------------------------------------------------- m = new Mathematician 'PI:NAME:<NAME>END_PI', 'Finite' log m.favnumber log m.first_name log m.last_name log m.full_name log m.full_name = 'Zeta Cardinal' log m
[ { "context": "ress in compact, human-readable format like\n # 2001:db8:8:66::1\n toString: ->\n stringParts = (part.toString(1", "end": 6332, "score": 0.9995831847190857, "start": 6318, "tag": "IP_ADDRESS", "value": "01:db8:8:66::1" }, { "context": "xpanded format with all zeroes included, like\n # 2001:db8:8:66:0:0:0:1\n toNormalizedString: ->\n return (part.toStrin", "end": 7341, "score": 0.9996825456619263, "start": 7320, "tag": "IP_ADDRESS", "value": "2001:db8:8:66:0:0:0:1" } ]
node_modules/ipaddr.js/src/ipaddr.coffee
joeschoeler13/homework10and11
341
# Define the main object ipaddr = {} root = this # Export for both the CommonJS and browser-like environment if module? && module.exports module.exports = ipaddr else root['ipaddr'] = ipaddr # A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher. matchCIDR = (first, second, partSize, cidrBits) -> if first.length != second.length throw new Error "ipaddr: cannot match CIDR for objects with different lengths" part = 0 while cidrBits > 0 shift = partSize - cidrBits shift = 0 if shift < 0 if first[part] >> shift != second[part] >> shift return false cidrBits -= partSize part += 1 return true # An utility function to ease named range matching. See examples below. ipaddr.subnetMatch = (address, rangeList, defaultName='unicast') -> for rangeName, rangeSubnets of rangeList # ECMA5 Array.isArray isn't available everywhere if rangeSubnets[0] && !(rangeSubnets[0] instanceof Array) rangeSubnets = [ rangeSubnets ] for subnet in rangeSubnets return rangeName if address.match.apply(address, subnet) return defaultName # An IPv4 address (RFC791). class ipaddr.IPv4 # Constructs a new IPv4 address from an array of four octets # in network order (MSB first) # Verifies the input. constructor: (octets) -> if octets.length != 4 throw new Error "ipaddr: ipv4 octet count should be 4" for octet in octets if !(0 <= octet <= 255) throw new Error "ipaddr: ipv4 octet should fit in 8 bits" @octets = octets # The 'kind' method exists on both IPv4 and IPv6 classes. kind: -> return 'ipv4' # Returns the address in convenient, decimal-dotted format. toString: -> return @octets.join "." # Returns an array of byte-sized values in network order (MSB first) toByteArray: -> return @octets.slice(0) # octets.clone # Checks if this address matches other one within given CIDR range. match: (other, cidrRange) -> if cidrRange == undefined [other, cidrRange] = other if other.kind() != 'ipv4' throw new Error "ipaddr: cannot match ipv4 address with non-ipv4 one" return matchCIDR(this.octets, other.octets, 8, cidrRange) # Special IPv4 address ranges. # See also https://en.wikipedia.org/wiki/Reserved_IP_addresses SpecialRanges: unspecified: [ [ new IPv4([0, 0, 0, 0]), 8 ] ] broadcast: [ [ new IPv4([255, 255, 255, 255]), 32 ] ] multicast: [ # RFC3171 [ new IPv4([224, 0, 0, 0]), 4 ] ] linkLocal: [ # RFC3927 [ new IPv4([169, 254, 0, 0]), 16 ] ] loopback: [ # RFC5735 [ new IPv4([127, 0, 0, 0]), 8 ] ] carrierGradeNat: [ # RFC6598 [ new IPv4([100, 64, 0, 0]), 10 ] ] private: [ # RFC1918 [ new IPv4([10, 0, 0, 0]), 8 ] [ new IPv4([172, 16, 0, 0]), 12 ] [ new IPv4([192, 168, 0, 0]), 16 ] ] reserved: [ # Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700 [ new IPv4([192, 0, 0, 0]), 24 ] [ new IPv4([192, 0, 2, 0]), 24 ] [ new IPv4([192, 88, 99, 0]), 24 ] [ new IPv4([198, 51, 100, 0]), 24 ] [ new IPv4([203, 0, 113, 0]), 24 ] [ new IPv4([240, 0, 0, 0]), 4 ] ] # Checks if the address corresponds to one of the special ranges. range: -> return ipaddr.subnetMatch(this, @SpecialRanges) # Convrets this IPv4 address to an IPv4-mapped IPv6 address. toIPv4MappedAddress: -> return ipaddr.IPv6.parse "::ffff:#{@toString()}" # returns a number of leading ones in IPv4 address, making sure that # the rest is a solid sequence of 0's (valid netmask) # returns either the CIDR length or null if mask is not valid prefixLengthFromSubnetMask: -> # number of zeroes in octet zerotable = 0: 8 128: 7 192: 6 224: 5 240: 4 248: 3 252: 2 254: 1 255: 0 cidr = 0 # non-zero encountered stop scanning for zeroes stop = false for i in [3..0] by -1 octet = @octets[i] if octet of zerotable zeros = zerotable[octet] if stop and zeros != 0 return null unless zeros == 8 stop = true cidr += zeros else return null return 32 - cidr # A list of regular expressions that match arbitrary IPv4 addresses, # for which a number of weird notations exist. # Note that an address like 0010.0xa5.1.1 is considered legal. ipv4Part = "(0?\\d+|0x[a-f0-9]+)" ipv4Regexes = fourOctet: new RegExp "^#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i' longValue: new RegExp "^#{ipv4Part}$", 'i' # Classful variants (like a.b, where a is an octet, and b is a 24-bit # value representing last three octets; this corresponds to a class C # address) are omitted due to classless nature of modern Internet. ipaddr.IPv4.parser = (string) -> parseIntAuto = (string) -> if string[0] == "0" && string[1] != "x" parseInt(string, 8) else parseInt(string) # parseInt recognizes all that octal & hexadecimal weirdness for us if match = string.match(ipv4Regexes.fourOctet) return (parseIntAuto(part) for part in match[1..5]) else if match = string.match(ipv4Regexes.longValue) value = parseIntAuto(match[1]) if value > 0xffffffff || value < 0 throw new Error "ipaddr: address outside defined range" return ((value >> shift) & 0xff for shift in [0..24] by 8).reverse() else return null # An IPv6 address (RFC2460) class ipaddr.IPv6 # Constructs an IPv6 address from an array of eight 16-bit parts # or sixteen 8-bit parts in network order (MSB first). # Throws an error if the input is invalid. constructor: (parts) -> if parts.length == 16 @parts = [] for i in [0..14] by 2 @parts.push((parts[i] << 8) | parts[i + 1]) else if parts.length == 8 @parts = parts else throw new Error "ipaddr: ipv6 part count should be 8 or 16" for part in @parts if !(0 <= part <= 0xffff) throw new Error "ipaddr: ipv6 part should fit in 16 bits" # The 'kind' method exists on both IPv4 and IPv6 classes. kind: -> return 'ipv6' # Returns the address in compact, human-readable format like # 2001:db8:8:66::1 toString: -> stringParts = (part.toString(16) for part in @parts) compactStringParts = [] pushPart = (part) -> compactStringParts.push part state = 0 for part in stringParts switch state when 0 if part == '0' pushPart('') else pushPart(part) state = 1 when 1 if part == '0' state = 2 else pushPart(part) when 2 unless part == '0' pushPart('') pushPart(part) state = 3 when 3 pushPart(part) if state == 2 pushPart('') pushPart('') return compactStringParts.join ":" # Returns an array of byte-sized values in network order (MSB first) toByteArray: -> bytes = [] for part in @parts bytes.push(part >> 8) bytes.push(part & 0xff) return bytes # Returns the address in expanded format with all zeroes included, like # 2001:db8:8:66:0:0:0:1 toNormalizedString: -> return (part.toString(16) for part in @parts).join ":" # Checks if this address matches other one within given CIDR range. match: (other, cidrRange) -> if cidrRange == undefined [other, cidrRange] = other if other.kind() != 'ipv6' throw new Error "ipaddr: cannot match ipv6 address with non-ipv6 one" return matchCIDR(this.parts, other.parts, 16, cidrRange) # Special IPv6 ranges SpecialRanges: unspecified: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128 ] # RFC4291, here and after linkLocal: [ new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10 ] multicast: [ new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8 ] loopback: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128 ] uniqueLocal: [ new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7 ] ipv4Mapped: [ new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96 ] rfc6145: [ new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96 ] # RFC6145 rfc6052: [ new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96 ] # RFC6052 '6to4': [ new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16 ] # RFC3056 teredo: [ new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32 ] # RFC6052, RFC6146 reserved: [ [ new IPv6([ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32 ] # RFC4291 ] # Checks if the address corresponds to one of the special ranges. range: -> return ipaddr.subnetMatch(this, @SpecialRanges) # Checks if this address is an IPv4-mapped IPv6 address. isIPv4MappedAddress: -> return @range() == 'ipv4Mapped' # Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address. # Throws an error otherwise. toIPv4Address: -> unless @isIPv4MappedAddress() throw new Error "ipaddr: trying to convert a generic ipv6 address to ipv4" [high, low] = @parts[-2..-1] return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]) # IPv6-matching regular expressions. # For IPv6, the task is simpler: it is enough to match the colon-delimited # hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at # the end. ipv6Part = "(?:[0-9a-f]+::?)+" ipv6Regexes = native: new RegExp "^(::)?(#{ipv6Part})?([0-9a-f]+)?(::)?$", 'i' transitional: new RegExp "^((?:#{ipv6Part})|(?:::)(?:#{ipv6Part})?)" + "#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i' # Expand :: in an IPv6 address or address part consisting of `parts` groups. expandIPv6 = (string, parts) -> # More than one '::' means invalid adddress if string.indexOf('::') != string.lastIndexOf('::') return null # How many parts do we already have? colonCount = 0 lastColon = -1 while (lastColon = string.indexOf(':', lastColon + 1)) >= 0 colonCount++ # 0::0 is two parts more than :: colonCount-- if string.substr(0, 2) == '::' colonCount-- if string.substr(-2, 2) == '::' # The following loop would hang if colonCount > parts if colonCount > parts return null # replacement = ':' + '0:' * (parts - colonCount) replacementCount = parts - colonCount replacement = ':' while replacementCount-- replacement += '0:' # Insert the missing zeroes string = string.replace('::', replacement) # Trim any garbage which may be hanging around if :: was at the edge in # the source string string = string[1..-1] if string[0] == ':' string = string[0..-2] if string[string.length-1] == ':' return (parseInt(part, 16) for part in string.split(":")) # Parse an IPv6 address. ipaddr.IPv6.parser = (string) -> if string.match(ipv6Regexes['native']) return expandIPv6(string, 8) else if match = string.match(ipv6Regexes['transitional']) parts = expandIPv6(match[1][0..-2], 6) if parts octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])] for octet in octets if !(0 <= octet <= 255) return null parts.push(octets[0] << 8 | octets[1]) parts.push(octets[2] << 8 | octets[3]) return parts return null # Checks if a given string is formatted like IPv4/IPv6 address. ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = (string) -> return @parser(string) != null # Checks if a given string is a valid IPv4/IPv6 address. ipaddr.IPv4.isValid = (string) -> try new this(@parser(string)) return true catch e return false ipaddr.IPv4.isValidFourPartDecimal = (string) -> if ipaddr.IPv4.isValid(string) and string.match(/^\d+(\.\d+){3}$/) return true else return false ipaddr.IPv6.isValid = (string) -> # Since IPv6.isValid is always called first, this shortcut # provides a substantial performance gain. if typeof string == "string" and string.indexOf(":") == -1 return false try new this(@parser(string)) return true catch e return false # Tries to parse and validate a string with IPv4/IPv6 address. # Throws an error if it fails. ipaddr.IPv4.parse = ipaddr.IPv6.parse = (string) -> parts = @parser(string) if parts == null throw new Error "ipaddr: string is not formatted like ip address" return new this(parts) ipaddr.IPv4.parseCIDR = (string) -> if match = string.match(/^(.+)\/(\d+)$/) maskLength = parseInt(match[2]) if maskLength >= 0 and maskLength <= 32 return [@parse(match[1]), maskLength] throw new Error "ipaddr: string is not formatted like an IPv4 CIDR range" # A utility function to return subnet mask in IPv4 format given the prefix length ipaddr.IPv4.subnetMaskFromPrefixLength = (prefix) -> if prefix < 0 or prefix > 32 throw new Error('ipaddr: invalid prefix length') octets = Array(4).fill(0) j = 0 while j < Math.floor(prefix / 8) octets[j] = 255 j++ octets[Math.floor(prefix / 8)] = Math.pow(2, (prefix % 8)) - 1 << 8 - (prefix % 8) new (ipaddr.IPv4)(octets) # A utility function to return broadcast address given the IPv4 interface and prefix length in CIDR notation ipaddr.IPv4.broadcastAddressFromCIDR = (string) -> try ipInterface = ipaddr.IPv4.parseCIDR(string)[0] subnetMask = @subnetMaskFromPrefixLength([ ipaddr.IPv4.parseCIDR(string)[1] ]) octets = [] i = 0 while i < 4 # Broadcast address is bitwise OR between ip interface and inverted mask octets.push parseInt(ipInterface.octets[i], 10) | parseInt(subnetMask.octets[i], 10) ^ 255 i++ return new (ipaddr.IPv4)(octets) catch error throw new Error('ipaddr: the address does not have IPv4 CIDR format') return # A utility function to return network address given the IPv4 interface and prefix length in CIDR notation ipaddr.IPv4.networkAddressFromCIDR = (string) -> try ipInterface = ipaddr.IPv4.parseCIDR(string)[0] subnetMask = @subnetMaskFromPrefixLength([ ipaddr.IPv4.parseCIDR(string)[1] ]) octets = [] i = 0 while i < 4 # Network address is bitwise AND between ip interface and mask octets.push parseInt(ipInterface.octets[i], 10) & parseInt(subnetMask.octets[i], 10) i++ return new (ipaddr.IPv4)(octets) catch error throw new Error('ipaddr: the address does not have IPv4 CIDR format') return ipaddr.IPv6.parseCIDR = (string) -> if match = string.match(/^(.+)\/(\d+)$/) maskLength = parseInt(match[2]) if maskLength >= 0 and maskLength <= 128 return [@parse(match[1]), maskLength] throw new Error "ipaddr: string is not formatted like an IPv6 CIDR range" # Checks if the address is valid IP address ipaddr.isValid = (string) -> return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string) # Try to parse an address and throw an error if it is impossible ipaddr.parse = (string) -> if ipaddr.IPv6.isValid(string) return ipaddr.IPv6.parse(string) else if ipaddr.IPv4.isValid(string) return ipaddr.IPv4.parse(string) else throw new Error "ipaddr: the address has neither IPv6 nor IPv4 format" ipaddr.parseCIDR = (string) -> try return ipaddr.IPv6.parseCIDR(string) catch e try return ipaddr.IPv4.parseCIDR(string) catch e throw new Error "ipaddr: the address has neither IPv6 nor IPv4 CIDR format" # Try to parse an array in network order (MSB first) for IPv4 and IPv6 ipaddr.fromByteArray = (bytes) -> length = bytes.length if length == 4 return new ipaddr.IPv4(bytes) else if length == 16 return new ipaddr.IPv6(bytes) else throw new Error "ipaddr: the binary input is neither an IPv6 nor IPv4 address" # Parse an address and return plain IPv4 address if it is an IPv4-mapped address ipaddr.process = (string) -> addr = @parse(string) if addr.kind() == 'ipv6' && addr.isIPv4MappedAddress() return addr.toIPv4Address() else return addr
46300
# Define the main object ipaddr = {} root = this # Export for both the CommonJS and browser-like environment if module? && module.exports module.exports = ipaddr else root['ipaddr'] = ipaddr # A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher. matchCIDR = (first, second, partSize, cidrBits) -> if first.length != second.length throw new Error "ipaddr: cannot match CIDR for objects with different lengths" part = 0 while cidrBits > 0 shift = partSize - cidrBits shift = 0 if shift < 0 if first[part] >> shift != second[part] >> shift return false cidrBits -= partSize part += 1 return true # An utility function to ease named range matching. See examples below. ipaddr.subnetMatch = (address, rangeList, defaultName='unicast') -> for rangeName, rangeSubnets of rangeList # ECMA5 Array.isArray isn't available everywhere if rangeSubnets[0] && !(rangeSubnets[0] instanceof Array) rangeSubnets = [ rangeSubnets ] for subnet in rangeSubnets return rangeName if address.match.apply(address, subnet) return defaultName # An IPv4 address (RFC791). class ipaddr.IPv4 # Constructs a new IPv4 address from an array of four octets # in network order (MSB first) # Verifies the input. constructor: (octets) -> if octets.length != 4 throw new Error "ipaddr: ipv4 octet count should be 4" for octet in octets if !(0 <= octet <= 255) throw new Error "ipaddr: ipv4 octet should fit in 8 bits" @octets = octets # The 'kind' method exists on both IPv4 and IPv6 classes. kind: -> return 'ipv4' # Returns the address in convenient, decimal-dotted format. toString: -> return @octets.join "." # Returns an array of byte-sized values in network order (MSB first) toByteArray: -> return @octets.slice(0) # octets.clone # Checks if this address matches other one within given CIDR range. match: (other, cidrRange) -> if cidrRange == undefined [other, cidrRange] = other if other.kind() != 'ipv4' throw new Error "ipaddr: cannot match ipv4 address with non-ipv4 one" return matchCIDR(this.octets, other.octets, 8, cidrRange) # Special IPv4 address ranges. # See also https://en.wikipedia.org/wiki/Reserved_IP_addresses SpecialRanges: unspecified: [ [ new IPv4([0, 0, 0, 0]), 8 ] ] broadcast: [ [ new IPv4([255, 255, 255, 255]), 32 ] ] multicast: [ # RFC3171 [ new IPv4([224, 0, 0, 0]), 4 ] ] linkLocal: [ # RFC3927 [ new IPv4([169, 254, 0, 0]), 16 ] ] loopback: [ # RFC5735 [ new IPv4([127, 0, 0, 0]), 8 ] ] carrierGradeNat: [ # RFC6598 [ new IPv4([100, 64, 0, 0]), 10 ] ] private: [ # RFC1918 [ new IPv4([10, 0, 0, 0]), 8 ] [ new IPv4([172, 16, 0, 0]), 12 ] [ new IPv4([192, 168, 0, 0]), 16 ] ] reserved: [ # Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700 [ new IPv4([192, 0, 0, 0]), 24 ] [ new IPv4([192, 0, 2, 0]), 24 ] [ new IPv4([192, 88, 99, 0]), 24 ] [ new IPv4([198, 51, 100, 0]), 24 ] [ new IPv4([203, 0, 113, 0]), 24 ] [ new IPv4([240, 0, 0, 0]), 4 ] ] # Checks if the address corresponds to one of the special ranges. range: -> return ipaddr.subnetMatch(this, @SpecialRanges) # Convrets this IPv4 address to an IPv4-mapped IPv6 address. toIPv4MappedAddress: -> return ipaddr.IPv6.parse "::ffff:#{@toString()}" # returns a number of leading ones in IPv4 address, making sure that # the rest is a solid sequence of 0's (valid netmask) # returns either the CIDR length or null if mask is not valid prefixLengthFromSubnetMask: -> # number of zeroes in octet zerotable = 0: 8 128: 7 192: 6 224: 5 240: 4 248: 3 252: 2 254: 1 255: 0 cidr = 0 # non-zero encountered stop scanning for zeroes stop = false for i in [3..0] by -1 octet = @octets[i] if octet of zerotable zeros = zerotable[octet] if stop and zeros != 0 return null unless zeros == 8 stop = true cidr += zeros else return null return 32 - cidr # A list of regular expressions that match arbitrary IPv4 addresses, # for which a number of weird notations exist. # Note that an address like 0010.0xa5.1.1 is considered legal. ipv4Part = "(0?\\d+|0x[a-f0-9]+)" ipv4Regexes = fourOctet: new RegExp "^#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i' longValue: new RegExp "^#{ipv4Part}$", 'i' # Classful variants (like a.b, where a is an octet, and b is a 24-bit # value representing last three octets; this corresponds to a class C # address) are omitted due to classless nature of modern Internet. ipaddr.IPv4.parser = (string) -> parseIntAuto = (string) -> if string[0] == "0" && string[1] != "x" parseInt(string, 8) else parseInt(string) # parseInt recognizes all that octal & hexadecimal weirdness for us if match = string.match(ipv4Regexes.fourOctet) return (parseIntAuto(part) for part in match[1..5]) else if match = string.match(ipv4Regexes.longValue) value = parseIntAuto(match[1]) if value > 0xffffffff || value < 0 throw new Error "ipaddr: address outside defined range" return ((value >> shift) & 0xff for shift in [0..24] by 8).reverse() else return null # An IPv6 address (RFC2460) class ipaddr.IPv6 # Constructs an IPv6 address from an array of eight 16-bit parts # or sixteen 8-bit parts in network order (MSB first). # Throws an error if the input is invalid. constructor: (parts) -> if parts.length == 16 @parts = [] for i in [0..14] by 2 @parts.push((parts[i] << 8) | parts[i + 1]) else if parts.length == 8 @parts = parts else throw new Error "ipaddr: ipv6 part count should be 8 or 16" for part in @parts if !(0 <= part <= 0xffff) throw new Error "ipaddr: ipv6 part should fit in 16 bits" # The 'kind' method exists on both IPv4 and IPv6 classes. kind: -> return 'ipv6' # Returns the address in compact, human-readable format like # 20fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b toString: -> stringParts = (part.toString(16) for part in @parts) compactStringParts = [] pushPart = (part) -> compactStringParts.push part state = 0 for part in stringParts switch state when 0 if part == '0' pushPart('') else pushPart(part) state = 1 when 1 if part == '0' state = 2 else pushPart(part) when 2 unless part == '0' pushPart('') pushPart(part) state = 3 when 3 pushPart(part) if state == 2 pushPart('') pushPart('') return compactStringParts.join ":" # Returns an array of byte-sized values in network order (MSB first) toByteArray: -> bytes = [] for part in @parts bytes.push(part >> 8) bytes.push(part & 0xff) return bytes # Returns the address in expanded format with all zeroes included, like # 2001:db8:8:66:0:0:0:1 toNormalizedString: -> return (part.toString(16) for part in @parts).join ":" # Checks if this address matches other one within given CIDR range. match: (other, cidrRange) -> if cidrRange == undefined [other, cidrRange] = other if other.kind() != 'ipv6' throw new Error "ipaddr: cannot match ipv6 address with non-ipv6 one" return matchCIDR(this.parts, other.parts, 16, cidrRange) # Special IPv6 ranges SpecialRanges: unspecified: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128 ] # RFC4291, here and after linkLocal: [ new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10 ] multicast: [ new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8 ] loopback: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128 ] uniqueLocal: [ new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7 ] ipv4Mapped: [ new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96 ] rfc6145: [ new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96 ] # RFC6145 rfc6052: [ new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96 ] # RFC6052 '6to4': [ new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16 ] # RFC3056 teredo: [ new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32 ] # RFC6052, RFC6146 reserved: [ [ new IPv6([ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32 ] # RFC4291 ] # Checks if the address corresponds to one of the special ranges. range: -> return ipaddr.subnetMatch(this, @SpecialRanges) # Checks if this address is an IPv4-mapped IPv6 address. isIPv4MappedAddress: -> return @range() == 'ipv4Mapped' # Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address. # Throws an error otherwise. toIPv4Address: -> unless @isIPv4MappedAddress() throw new Error "ipaddr: trying to convert a generic ipv6 address to ipv4" [high, low] = @parts[-2..-1] return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]) # IPv6-matching regular expressions. # For IPv6, the task is simpler: it is enough to match the colon-delimited # hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at # the end. ipv6Part = "(?:[0-9a-f]+::?)+" ipv6Regexes = native: new RegExp "^(::)?(#{ipv6Part})?([0-9a-f]+)?(::)?$", 'i' transitional: new RegExp "^((?:#{ipv6Part})|(?:::)(?:#{ipv6Part})?)" + "#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i' # Expand :: in an IPv6 address or address part consisting of `parts` groups. expandIPv6 = (string, parts) -> # More than one '::' means invalid adddress if string.indexOf('::') != string.lastIndexOf('::') return null # How many parts do we already have? colonCount = 0 lastColon = -1 while (lastColon = string.indexOf(':', lastColon + 1)) >= 0 colonCount++ # 0::0 is two parts more than :: colonCount-- if string.substr(0, 2) == '::' colonCount-- if string.substr(-2, 2) == '::' # The following loop would hang if colonCount > parts if colonCount > parts return null # replacement = ':' + '0:' * (parts - colonCount) replacementCount = parts - colonCount replacement = ':' while replacementCount-- replacement += '0:' # Insert the missing zeroes string = string.replace('::', replacement) # Trim any garbage which may be hanging around if :: was at the edge in # the source string string = string[1..-1] if string[0] == ':' string = string[0..-2] if string[string.length-1] == ':' return (parseInt(part, 16) for part in string.split(":")) # Parse an IPv6 address. ipaddr.IPv6.parser = (string) -> if string.match(ipv6Regexes['native']) return expandIPv6(string, 8) else if match = string.match(ipv6Regexes['transitional']) parts = expandIPv6(match[1][0..-2], 6) if parts octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])] for octet in octets if !(0 <= octet <= 255) return null parts.push(octets[0] << 8 | octets[1]) parts.push(octets[2] << 8 | octets[3]) return parts return null # Checks if a given string is formatted like IPv4/IPv6 address. ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = (string) -> return @parser(string) != null # Checks if a given string is a valid IPv4/IPv6 address. ipaddr.IPv4.isValid = (string) -> try new this(@parser(string)) return true catch e return false ipaddr.IPv4.isValidFourPartDecimal = (string) -> if ipaddr.IPv4.isValid(string) and string.match(/^\d+(\.\d+){3}$/) return true else return false ipaddr.IPv6.isValid = (string) -> # Since IPv6.isValid is always called first, this shortcut # provides a substantial performance gain. if typeof string == "string" and string.indexOf(":") == -1 return false try new this(@parser(string)) return true catch e return false # Tries to parse and validate a string with IPv4/IPv6 address. # Throws an error if it fails. ipaddr.IPv4.parse = ipaddr.IPv6.parse = (string) -> parts = @parser(string) if parts == null throw new Error "ipaddr: string is not formatted like ip address" return new this(parts) ipaddr.IPv4.parseCIDR = (string) -> if match = string.match(/^(.+)\/(\d+)$/) maskLength = parseInt(match[2]) if maskLength >= 0 and maskLength <= 32 return [@parse(match[1]), maskLength] throw new Error "ipaddr: string is not formatted like an IPv4 CIDR range" # A utility function to return subnet mask in IPv4 format given the prefix length ipaddr.IPv4.subnetMaskFromPrefixLength = (prefix) -> if prefix < 0 or prefix > 32 throw new Error('ipaddr: invalid prefix length') octets = Array(4).fill(0) j = 0 while j < Math.floor(prefix / 8) octets[j] = 255 j++ octets[Math.floor(prefix / 8)] = Math.pow(2, (prefix % 8)) - 1 << 8 - (prefix % 8) new (ipaddr.IPv4)(octets) # A utility function to return broadcast address given the IPv4 interface and prefix length in CIDR notation ipaddr.IPv4.broadcastAddressFromCIDR = (string) -> try ipInterface = ipaddr.IPv4.parseCIDR(string)[0] subnetMask = @subnetMaskFromPrefixLength([ ipaddr.IPv4.parseCIDR(string)[1] ]) octets = [] i = 0 while i < 4 # Broadcast address is bitwise OR between ip interface and inverted mask octets.push parseInt(ipInterface.octets[i], 10) | parseInt(subnetMask.octets[i], 10) ^ 255 i++ return new (ipaddr.IPv4)(octets) catch error throw new Error('ipaddr: the address does not have IPv4 CIDR format') return # A utility function to return network address given the IPv4 interface and prefix length in CIDR notation ipaddr.IPv4.networkAddressFromCIDR = (string) -> try ipInterface = ipaddr.IPv4.parseCIDR(string)[0] subnetMask = @subnetMaskFromPrefixLength([ ipaddr.IPv4.parseCIDR(string)[1] ]) octets = [] i = 0 while i < 4 # Network address is bitwise AND between ip interface and mask octets.push parseInt(ipInterface.octets[i], 10) & parseInt(subnetMask.octets[i], 10) i++ return new (ipaddr.IPv4)(octets) catch error throw new Error('ipaddr: the address does not have IPv4 CIDR format') return ipaddr.IPv6.parseCIDR = (string) -> if match = string.match(/^(.+)\/(\d+)$/) maskLength = parseInt(match[2]) if maskLength >= 0 and maskLength <= 128 return [@parse(match[1]), maskLength] throw new Error "ipaddr: string is not formatted like an IPv6 CIDR range" # Checks if the address is valid IP address ipaddr.isValid = (string) -> return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string) # Try to parse an address and throw an error if it is impossible ipaddr.parse = (string) -> if ipaddr.IPv6.isValid(string) return ipaddr.IPv6.parse(string) else if ipaddr.IPv4.isValid(string) return ipaddr.IPv4.parse(string) else throw new Error "ipaddr: the address has neither IPv6 nor IPv4 format" ipaddr.parseCIDR = (string) -> try return ipaddr.IPv6.parseCIDR(string) catch e try return ipaddr.IPv4.parseCIDR(string) catch e throw new Error "ipaddr: the address has neither IPv6 nor IPv4 CIDR format" # Try to parse an array in network order (MSB first) for IPv4 and IPv6 ipaddr.fromByteArray = (bytes) -> length = bytes.length if length == 4 return new ipaddr.IPv4(bytes) else if length == 16 return new ipaddr.IPv6(bytes) else throw new Error "ipaddr: the binary input is neither an IPv6 nor IPv4 address" # Parse an address and return plain IPv4 address if it is an IPv4-mapped address ipaddr.process = (string) -> addr = @parse(string) if addr.kind() == 'ipv6' && addr.isIPv4MappedAddress() return addr.toIPv4Address() else return addr
true
# Define the main object ipaddr = {} root = this # Export for both the CommonJS and browser-like environment if module? && module.exports module.exports = ipaddr else root['ipaddr'] = ipaddr # A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher. matchCIDR = (first, second, partSize, cidrBits) -> if first.length != second.length throw new Error "ipaddr: cannot match CIDR for objects with different lengths" part = 0 while cidrBits > 0 shift = partSize - cidrBits shift = 0 if shift < 0 if first[part] >> shift != second[part] >> shift return false cidrBits -= partSize part += 1 return true # An utility function to ease named range matching. See examples below. ipaddr.subnetMatch = (address, rangeList, defaultName='unicast') -> for rangeName, rangeSubnets of rangeList # ECMA5 Array.isArray isn't available everywhere if rangeSubnets[0] && !(rangeSubnets[0] instanceof Array) rangeSubnets = [ rangeSubnets ] for subnet in rangeSubnets return rangeName if address.match.apply(address, subnet) return defaultName # An IPv4 address (RFC791). class ipaddr.IPv4 # Constructs a new IPv4 address from an array of four octets # in network order (MSB first) # Verifies the input. constructor: (octets) -> if octets.length != 4 throw new Error "ipaddr: ipv4 octet count should be 4" for octet in octets if !(0 <= octet <= 255) throw new Error "ipaddr: ipv4 octet should fit in 8 bits" @octets = octets # The 'kind' method exists on both IPv4 and IPv6 classes. kind: -> return 'ipv4' # Returns the address in convenient, decimal-dotted format. toString: -> return @octets.join "." # Returns an array of byte-sized values in network order (MSB first) toByteArray: -> return @octets.slice(0) # octets.clone # Checks if this address matches other one within given CIDR range. match: (other, cidrRange) -> if cidrRange == undefined [other, cidrRange] = other if other.kind() != 'ipv4' throw new Error "ipaddr: cannot match ipv4 address with non-ipv4 one" return matchCIDR(this.octets, other.octets, 8, cidrRange) # Special IPv4 address ranges. # See also https://en.wikipedia.org/wiki/Reserved_IP_addresses SpecialRanges: unspecified: [ [ new IPv4([0, 0, 0, 0]), 8 ] ] broadcast: [ [ new IPv4([255, 255, 255, 255]), 32 ] ] multicast: [ # RFC3171 [ new IPv4([224, 0, 0, 0]), 4 ] ] linkLocal: [ # RFC3927 [ new IPv4([169, 254, 0, 0]), 16 ] ] loopback: [ # RFC5735 [ new IPv4([127, 0, 0, 0]), 8 ] ] carrierGradeNat: [ # RFC6598 [ new IPv4([100, 64, 0, 0]), 10 ] ] private: [ # RFC1918 [ new IPv4([10, 0, 0, 0]), 8 ] [ new IPv4([172, 16, 0, 0]), 12 ] [ new IPv4([192, 168, 0, 0]), 16 ] ] reserved: [ # Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700 [ new IPv4([192, 0, 0, 0]), 24 ] [ new IPv4([192, 0, 2, 0]), 24 ] [ new IPv4([192, 88, 99, 0]), 24 ] [ new IPv4([198, 51, 100, 0]), 24 ] [ new IPv4([203, 0, 113, 0]), 24 ] [ new IPv4([240, 0, 0, 0]), 4 ] ] # Checks if the address corresponds to one of the special ranges. range: -> return ipaddr.subnetMatch(this, @SpecialRanges) # Convrets this IPv4 address to an IPv4-mapped IPv6 address. toIPv4MappedAddress: -> return ipaddr.IPv6.parse "::ffff:#{@toString()}" # returns a number of leading ones in IPv4 address, making sure that # the rest is a solid sequence of 0's (valid netmask) # returns either the CIDR length or null if mask is not valid prefixLengthFromSubnetMask: -> # number of zeroes in octet zerotable = 0: 8 128: 7 192: 6 224: 5 240: 4 248: 3 252: 2 254: 1 255: 0 cidr = 0 # non-zero encountered stop scanning for zeroes stop = false for i in [3..0] by -1 octet = @octets[i] if octet of zerotable zeros = zerotable[octet] if stop and zeros != 0 return null unless zeros == 8 stop = true cidr += zeros else return null return 32 - cidr # A list of regular expressions that match arbitrary IPv4 addresses, # for which a number of weird notations exist. # Note that an address like 0010.0xa5.1.1 is considered legal. ipv4Part = "(0?\\d+|0x[a-f0-9]+)" ipv4Regexes = fourOctet: new RegExp "^#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i' longValue: new RegExp "^#{ipv4Part}$", 'i' # Classful variants (like a.b, where a is an octet, and b is a 24-bit # value representing last three octets; this corresponds to a class C # address) are omitted due to classless nature of modern Internet. ipaddr.IPv4.parser = (string) -> parseIntAuto = (string) -> if string[0] == "0" && string[1] != "x" parseInt(string, 8) else parseInt(string) # parseInt recognizes all that octal & hexadecimal weirdness for us if match = string.match(ipv4Regexes.fourOctet) return (parseIntAuto(part) for part in match[1..5]) else if match = string.match(ipv4Regexes.longValue) value = parseIntAuto(match[1]) if value > 0xffffffff || value < 0 throw new Error "ipaddr: address outside defined range" return ((value >> shift) & 0xff for shift in [0..24] by 8).reverse() else return null # An IPv6 address (RFC2460) class ipaddr.IPv6 # Constructs an IPv6 address from an array of eight 16-bit parts # or sixteen 8-bit parts in network order (MSB first). # Throws an error if the input is invalid. constructor: (parts) -> if parts.length == 16 @parts = [] for i in [0..14] by 2 @parts.push((parts[i] << 8) | parts[i + 1]) else if parts.length == 8 @parts = parts else throw new Error "ipaddr: ipv6 part count should be 8 or 16" for part in @parts if !(0 <= part <= 0xffff) throw new Error "ipaddr: ipv6 part should fit in 16 bits" # The 'kind' method exists on both IPv4 and IPv6 classes. kind: -> return 'ipv6' # Returns the address in compact, human-readable format like # 20PI:IP_ADDRESS:fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3bEND_PI toString: -> stringParts = (part.toString(16) for part in @parts) compactStringParts = [] pushPart = (part) -> compactStringParts.push part state = 0 for part in stringParts switch state when 0 if part == '0' pushPart('') else pushPart(part) state = 1 when 1 if part == '0' state = 2 else pushPart(part) when 2 unless part == '0' pushPart('') pushPart(part) state = 3 when 3 pushPart(part) if state == 2 pushPart('') pushPart('') return compactStringParts.join ":" # Returns an array of byte-sized values in network order (MSB first) toByteArray: -> bytes = [] for part in @parts bytes.push(part >> 8) bytes.push(part & 0xff) return bytes # Returns the address in expanded format with all zeroes included, like # 2001:db8:8:66:0:0:0:1 toNormalizedString: -> return (part.toString(16) for part in @parts).join ":" # Checks if this address matches other one within given CIDR range. match: (other, cidrRange) -> if cidrRange == undefined [other, cidrRange] = other if other.kind() != 'ipv6' throw new Error "ipaddr: cannot match ipv6 address with non-ipv6 one" return matchCIDR(this.parts, other.parts, 16, cidrRange) # Special IPv6 ranges SpecialRanges: unspecified: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128 ] # RFC4291, here and after linkLocal: [ new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10 ] multicast: [ new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8 ] loopback: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128 ] uniqueLocal: [ new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7 ] ipv4Mapped: [ new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96 ] rfc6145: [ new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96 ] # RFC6145 rfc6052: [ new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96 ] # RFC6052 '6to4': [ new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16 ] # RFC3056 teredo: [ new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32 ] # RFC6052, RFC6146 reserved: [ [ new IPv6([ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32 ] # RFC4291 ] # Checks if the address corresponds to one of the special ranges. range: -> return ipaddr.subnetMatch(this, @SpecialRanges) # Checks if this address is an IPv4-mapped IPv6 address. isIPv4MappedAddress: -> return @range() == 'ipv4Mapped' # Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address. # Throws an error otherwise. toIPv4Address: -> unless @isIPv4MappedAddress() throw new Error "ipaddr: trying to convert a generic ipv6 address to ipv4" [high, low] = @parts[-2..-1] return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]) # IPv6-matching regular expressions. # For IPv6, the task is simpler: it is enough to match the colon-delimited # hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at # the end. ipv6Part = "(?:[0-9a-f]+::?)+" ipv6Regexes = native: new RegExp "^(::)?(#{ipv6Part})?([0-9a-f]+)?(::)?$", 'i' transitional: new RegExp "^((?:#{ipv6Part})|(?:::)(?:#{ipv6Part})?)" + "#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i' # Expand :: in an IPv6 address or address part consisting of `parts` groups. expandIPv6 = (string, parts) -> # More than one '::' means invalid adddress if string.indexOf('::') != string.lastIndexOf('::') return null # How many parts do we already have? colonCount = 0 lastColon = -1 while (lastColon = string.indexOf(':', lastColon + 1)) >= 0 colonCount++ # 0::0 is two parts more than :: colonCount-- if string.substr(0, 2) == '::' colonCount-- if string.substr(-2, 2) == '::' # The following loop would hang if colonCount > parts if colonCount > parts return null # replacement = ':' + '0:' * (parts - colonCount) replacementCount = parts - colonCount replacement = ':' while replacementCount-- replacement += '0:' # Insert the missing zeroes string = string.replace('::', replacement) # Trim any garbage which may be hanging around if :: was at the edge in # the source string string = string[1..-1] if string[0] == ':' string = string[0..-2] if string[string.length-1] == ':' return (parseInt(part, 16) for part in string.split(":")) # Parse an IPv6 address. ipaddr.IPv6.parser = (string) -> if string.match(ipv6Regexes['native']) return expandIPv6(string, 8) else if match = string.match(ipv6Regexes['transitional']) parts = expandIPv6(match[1][0..-2], 6) if parts octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])] for octet in octets if !(0 <= octet <= 255) return null parts.push(octets[0] << 8 | octets[1]) parts.push(octets[2] << 8 | octets[3]) return parts return null # Checks if a given string is formatted like IPv4/IPv6 address. ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = (string) -> return @parser(string) != null # Checks if a given string is a valid IPv4/IPv6 address. ipaddr.IPv4.isValid = (string) -> try new this(@parser(string)) return true catch e return false ipaddr.IPv4.isValidFourPartDecimal = (string) -> if ipaddr.IPv4.isValid(string) and string.match(/^\d+(\.\d+){3}$/) return true else return false ipaddr.IPv6.isValid = (string) -> # Since IPv6.isValid is always called first, this shortcut # provides a substantial performance gain. if typeof string == "string" and string.indexOf(":") == -1 return false try new this(@parser(string)) return true catch e return false # Tries to parse and validate a string with IPv4/IPv6 address. # Throws an error if it fails. ipaddr.IPv4.parse = ipaddr.IPv6.parse = (string) -> parts = @parser(string) if parts == null throw new Error "ipaddr: string is not formatted like ip address" return new this(parts) ipaddr.IPv4.parseCIDR = (string) -> if match = string.match(/^(.+)\/(\d+)$/) maskLength = parseInt(match[2]) if maskLength >= 0 and maskLength <= 32 return [@parse(match[1]), maskLength] throw new Error "ipaddr: string is not formatted like an IPv4 CIDR range" # A utility function to return subnet mask in IPv4 format given the prefix length ipaddr.IPv4.subnetMaskFromPrefixLength = (prefix) -> if prefix < 0 or prefix > 32 throw new Error('ipaddr: invalid prefix length') octets = Array(4).fill(0) j = 0 while j < Math.floor(prefix / 8) octets[j] = 255 j++ octets[Math.floor(prefix / 8)] = Math.pow(2, (prefix % 8)) - 1 << 8 - (prefix % 8) new (ipaddr.IPv4)(octets) # A utility function to return broadcast address given the IPv4 interface and prefix length in CIDR notation ipaddr.IPv4.broadcastAddressFromCIDR = (string) -> try ipInterface = ipaddr.IPv4.parseCIDR(string)[0] subnetMask = @subnetMaskFromPrefixLength([ ipaddr.IPv4.parseCIDR(string)[1] ]) octets = [] i = 0 while i < 4 # Broadcast address is bitwise OR between ip interface and inverted mask octets.push parseInt(ipInterface.octets[i], 10) | parseInt(subnetMask.octets[i], 10) ^ 255 i++ return new (ipaddr.IPv4)(octets) catch error throw new Error('ipaddr: the address does not have IPv4 CIDR format') return # A utility function to return network address given the IPv4 interface and prefix length in CIDR notation ipaddr.IPv4.networkAddressFromCIDR = (string) -> try ipInterface = ipaddr.IPv4.parseCIDR(string)[0] subnetMask = @subnetMaskFromPrefixLength([ ipaddr.IPv4.parseCIDR(string)[1] ]) octets = [] i = 0 while i < 4 # Network address is bitwise AND between ip interface and mask octets.push parseInt(ipInterface.octets[i], 10) & parseInt(subnetMask.octets[i], 10) i++ return new (ipaddr.IPv4)(octets) catch error throw new Error('ipaddr: the address does not have IPv4 CIDR format') return ipaddr.IPv6.parseCIDR = (string) -> if match = string.match(/^(.+)\/(\d+)$/) maskLength = parseInt(match[2]) if maskLength >= 0 and maskLength <= 128 return [@parse(match[1]), maskLength] throw new Error "ipaddr: string is not formatted like an IPv6 CIDR range" # Checks if the address is valid IP address ipaddr.isValid = (string) -> return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string) # Try to parse an address and throw an error if it is impossible ipaddr.parse = (string) -> if ipaddr.IPv6.isValid(string) return ipaddr.IPv6.parse(string) else if ipaddr.IPv4.isValid(string) return ipaddr.IPv4.parse(string) else throw new Error "ipaddr: the address has neither IPv6 nor IPv4 format" ipaddr.parseCIDR = (string) -> try return ipaddr.IPv6.parseCIDR(string) catch e try return ipaddr.IPv4.parseCIDR(string) catch e throw new Error "ipaddr: the address has neither IPv6 nor IPv4 CIDR format" # Try to parse an array in network order (MSB first) for IPv4 and IPv6 ipaddr.fromByteArray = (bytes) -> length = bytes.length if length == 4 return new ipaddr.IPv4(bytes) else if length == 16 return new ipaddr.IPv6(bytes) else throw new Error "ipaddr: the binary input is neither an IPv6 nor IPv4 address" # Parse an address and return plain IPv4 address if it is an IPv4-mapped address ipaddr.process = (string) -> addr = @parse(string) if addr.kind() == 'ipv6' && addr.isIPv4MappedAddress() return addr.toIPv4Address() else return addr
[ { "context": "\": null,\n \"author\": {\n \"name\": \"callin\",\n \"username\": \"callin\",\n \"", "end": 763, "score": 0.8906546235084534, "start": 757, "tag": "USERNAME", "value": "callin" }, { "context": " \"name\": \"callin\",\n \"username\": \"callin\",\n \"id\": 4,\n \"state\": \"acti", "end": 797, "score": 0.9995111227035522, "start": 791, "tag": "USERNAME", "value": "callin" }, { "context": " \"visibility_level\": 0,\n \"ssh_url_to_repo\": \"git@example.com:brightbox/puppet.git\",\n \"http_url_to_repo\": \"h", "end": 2203, "score": 0.950629711151123, "start": 2188, "tag": "EMAIL", "value": "git@example.com" }, { "context": "evel\": 0,\n \"ssh_url_to_repo\": \"git@example.com:brightbox/puppet.git\",\n \"http_url_to_repo\": \"http://exam", "end": 2213, "score": 0.6097376346588135, "start": 2204, "tag": "USERNAME", "value": "brightbox" }, { "context": " ],\n \"owner\": {\n \"id\": 4,\n \"name\": \"Brightbox\",\n \"created_at\": \"2013-09-30T13:46:02Z\"\n ", "end": 2459, "score": 0.9990374445915222, "start": 2450, "tag": "USERNAME", "value": "Brightbox" }, { "context": " \"description\": \"\",\n \"id\": 4,\n \"name\": \"Brightbox\",\n \"owner_id\": 1,\n \"path\": \"brightbox\",", "end": 3108, "score": 0.8830236792564392, "start": 3099, "tag": "USERNAME", "value": "Brightbox" }, { "context": "t\": 0,\n \"star_count\": 0,\n \"runners_token\": \"b8547b1dc37721d05889db52fa2f02\",\n \"public_builds\": true,\n \"shared_with_gro", "end": 3602, "score": 0.7566854953765869, "start": 3572, "tag": "KEY", "value": "b8547b1dc37721d05889db52fa2f02" } ]
gitlabApi.coffee
kranian/gitlabviewer
0
$ = require 'jquery' _ = require 'lodash' ipcRenderer = require('electron').ipcRenderer token = ipcRenderer.sendSync('getToken') maintenancePrjId = 19; devPrjId = 2; bmtPrjId = 15; customerTypeLabelColor = '#44ad8e' taskTypeLabelColor = '#428bca' deptTypeLabelColor = '#d9534f' priorityTypeLabelColor = '#ff0000' module.exports = {} ### issue format { "id": 350, "iid": 3, "project_id": 19, "description": "", "state": "opened", "created_at": "2016-10-10T15:39:35.203+09:00", "updated_at": "2016-10-10T15:45:43.812+09:00", "labels": [ "교통안전공단", "기능개선" ], "milestone": null, "assignee": null, "author": { "name": "callin", "username": "callin", "id": 4, "state": "active", "avatar_url": "http://www.gravatar.com/avatar/beb88205c2b0bbf7f2bcc8a4f503eceb?s=80\u0026d=identicon", "web_url": "http://elevisor.iptime.org:9937/u/callin" } } ### module.exports.setToken = (tkn) -> token = tkn module.exports.getIssueList = (prjId=2) -> df = $.Deferred() per_page = 100 page_index = 1; allIssueList = [] getIsList = -> $.ajax({ url : 'http://kranian:9937/api/v3/projects/'+prjId+'/issues?state=opened' headers : {'PRIVATE-TOKEN':token} data : { "per_page" : per_page "page" : page_index } }).then (response) -> #console.log 'response', response allIssueList.push(v) for v in response if per_page == response.length page_index++ getIsList() else df.resolve(allIssueList) getIsList() return df.promise() module.exports.getIssue = (prjId=2,issueId=1) -> df = $.Deferred() getIssue = -> $.ajax({ url : "http://kranian:9937/api/v3/projects/#{prjId}/issues/#{issueId}" headers : {'PRIVATE-TOKEN':token} }).then (response) -> df.resolve(response) getIssue() return df.promise() ###0 { "id": 6, "description": null, "default_branch": "master", "public": false, "visibility_level": 0, "ssh_url_to_repo": "git@example.com:brightbox/puppet.git", "http_url_to_repo": "http://example.com/brightbox/puppet.git", "web_url": "http://example.com/brightbox/puppet", "tag_list": [ "example", "puppet" ], "owner": { "id": 4, "name": "Brightbox", "created_at": "2013-09-30T13:46:02Z" }, "name": "Puppet", "name_with_namespace": "Brightbox / Puppet", "path": "puppet", "path_with_namespace": "brightbox/puppet", "issues_enabled": true, "open_issues_count": 1, "merge_requests_enabled": true, "builds_enabled": true, "wiki_enabled": true, "snippets_enabled": false, "container_registry_enabled": false, "created_at": "2013-09-30T13:46:02Z", "last_activity_at": "2013-09-30T13:46:02Z", "creator_id": 3, "namespace": { "created_at": "2013-09-30T13:46:02Z", "description": "", "id": 4, "name": "Brightbox", "owner_id": 1, "path": "brightbox", "updated_at": "2013-09-30T13:46:02Z" }, "permissions": { "project_access": { "access_level": 10, "notification_level": 3 }, "group_access": { "access_level": 50, "notification_level": 3 } }, "archived": false, "avatar_url": null, "shared_runners_enabled": true, "forks_count": 0, "star_count": 0, "runners_token": "b8547b1dc37721d05889db52fa2f02", "public_builds": true, "shared_with_groups": [], "only_allow_merge_if_build_succeeds": false, "request_access_enabled": false } ### module.exports.getProjectList= () -> df = $.Deferred() per_page = 100 page_index = 1; allIssueList = [] getIsList = -> $.ajax({ url : 'http://kranian:9937/api/v3/projects/all' headers : {'PRIVATE-TOKEN':token} data : { "per_page" : per_page "page" : page_index } }).then (response) -> console.log 'response', response allIssueList.push(v) for v in response if per_page == response.length page_index++ getIsList() else df.resolve(allIssueList) getIsList() return df.promise() module.exports.getUserList= () -> df = $.Deferred() per_page = 100 page_index = 1; allIssueList = [] getIsList = -> $.ajax({ url : 'http://kranian.org:9937/api/v3/users' headers : {'PRIVATE-TOKEN':token} data : { "per_page" : per_page "page" : page_index } }).then (response) -> allIssueList.push(v) for v in response if per_page == response.length page_index++ getIsList() else df.resolve(allIssueList) getIsList() return df.promise() ### {color:'#ff0000', name:'긴급'} ### module.exports.getLabelList = (projId) -> df = $.Deferred() per_page = 100 page_index = 1; allLabelList = [] getLbl = -> $.ajax({ url : 'http://kranian:9937/api/v3/projects/'+projId+'/labels' headers : {'PRIVATE-TOKEN':token} data : { "per_page" : per_page "page" : page_index } }).then (response) -> console.log 'response', response allLabelList.push(v) for v in response if per_page == response.body.length page_index++; getLbl(); else df.resolve allLabelList getLbl() return df.promise() module.exports.getLabelsByPrjNColor = (projId, color) -> df = $.Deferred() module.exports.getLabelList(projId).then (allLabelList )-> df.resolve( _(allLabelList).filter((v)->v.color == color).map('name').value() ) return df.promise() module.exports.getAllIssueList = ()-> df = $.Deferred() module.exports.getProjectList().then (rslt)-> issP = _.map(rslt, (v)->module.exports.getIssueList(v.id)) $.when.apply($,issP).then (args...)->df.resolve _.flatten(args) return df.promise()
182200
$ = require 'jquery' _ = require 'lodash' ipcRenderer = require('electron').ipcRenderer token = ipcRenderer.sendSync('getToken') maintenancePrjId = 19; devPrjId = 2; bmtPrjId = 15; customerTypeLabelColor = '#44ad8e' taskTypeLabelColor = '#428bca' deptTypeLabelColor = '#d9534f' priorityTypeLabelColor = '#ff0000' module.exports = {} ### issue format { "id": 350, "iid": 3, "project_id": 19, "description": "", "state": "opened", "created_at": "2016-10-10T15:39:35.203+09:00", "updated_at": "2016-10-10T15:45:43.812+09:00", "labels": [ "교통안전공단", "기능개선" ], "milestone": null, "assignee": null, "author": { "name": "callin", "username": "callin", "id": 4, "state": "active", "avatar_url": "http://www.gravatar.com/avatar/beb88205c2b0bbf7f2bcc8a4f503eceb?s=80\u0026d=identicon", "web_url": "http://elevisor.iptime.org:9937/u/callin" } } ### module.exports.setToken = (tkn) -> token = tkn module.exports.getIssueList = (prjId=2) -> df = $.Deferred() per_page = 100 page_index = 1; allIssueList = [] getIsList = -> $.ajax({ url : 'http://kranian:9937/api/v3/projects/'+prjId+'/issues?state=opened' headers : {'PRIVATE-TOKEN':token} data : { "per_page" : per_page "page" : page_index } }).then (response) -> #console.log 'response', response allIssueList.push(v) for v in response if per_page == response.length page_index++ getIsList() else df.resolve(allIssueList) getIsList() return df.promise() module.exports.getIssue = (prjId=2,issueId=1) -> df = $.Deferred() getIssue = -> $.ajax({ url : "http://kranian:9937/api/v3/projects/#{prjId}/issues/#{issueId}" headers : {'PRIVATE-TOKEN':token} }).then (response) -> df.resolve(response) getIssue() return df.promise() ###0 { "id": 6, "description": null, "default_branch": "master", "public": false, "visibility_level": 0, "ssh_url_to_repo": "<EMAIL>:brightbox/puppet.git", "http_url_to_repo": "http://example.com/brightbox/puppet.git", "web_url": "http://example.com/brightbox/puppet", "tag_list": [ "example", "puppet" ], "owner": { "id": 4, "name": "Brightbox", "created_at": "2013-09-30T13:46:02Z" }, "name": "Puppet", "name_with_namespace": "Brightbox / Puppet", "path": "puppet", "path_with_namespace": "brightbox/puppet", "issues_enabled": true, "open_issues_count": 1, "merge_requests_enabled": true, "builds_enabled": true, "wiki_enabled": true, "snippets_enabled": false, "container_registry_enabled": false, "created_at": "2013-09-30T13:46:02Z", "last_activity_at": "2013-09-30T13:46:02Z", "creator_id": 3, "namespace": { "created_at": "2013-09-30T13:46:02Z", "description": "", "id": 4, "name": "Brightbox", "owner_id": 1, "path": "brightbox", "updated_at": "2013-09-30T13:46:02Z" }, "permissions": { "project_access": { "access_level": 10, "notification_level": 3 }, "group_access": { "access_level": 50, "notification_level": 3 } }, "archived": false, "avatar_url": null, "shared_runners_enabled": true, "forks_count": 0, "star_count": 0, "runners_token": "<KEY>", "public_builds": true, "shared_with_groups": [], "only_allow_merge_if_build_succeeds": false, "request_access_enabled": false } ### module.exports.getProjectList= () -> df = $.Deferred() per_page = 100 page_index = 1; allIssueList = [] getIsList = -> $.ajax({ url : 'http://kranian:9937/api/v3/projects/all' headers : {'PRIVATE-TOKEN':token} data : { "per_page" : per_page "page" : page_index } }).then (response) -> console.log 'response', response allIssueList.push(v) for v in response if per_page == response.length page_index++ getIsList() else df.resolve(allIssueList) getIsList() return df.promise() module.exports.getUserList= () -> df = $.Deferred() per_page = 100 page_index = 1; allIssueList = [] getIsList = -> $.ajax({ url : 'http://kranian.org:9937/api/v3/users' headers : {'PRIVATE-TOKEN':token} data : { "per_page" : per_page "page" : page_index } }).then (response) -> allIssueList.push(v) for v in response if per_page == response.length page_index++ getIsList() else df.resolve(allIssueList) getIsList() return df.promise() ### {color:'#ff0000', name:'긴급'} ### module.exports.getLabelList = (projId) -> df = $.Deferred() per_page = 100 page_index = 1; allLabelList = [] getLbl = -> $.ajax({ url : 'http://kranian:9937/api/v3/projects/'+projId+'/labels' headers : {'PRIVATE-TOKEN':token} data : { "per_page" : per_page "page" : page_index } }).then (response) -> console.log 'response', response allLabelList.push(v) for v in response if per_page == response.body.length page_index++; getLbl(); else df.resolve allLabelList getLbl() return df.promise() module.exports.getLabelsByPrjNColor = (projId, color) -> df = $.Deferred() module.exports.getLabelList(projId).then (allLabelList )-> df.resolve( _(allLabelList).filter((v)->v.color == color).map('name').value() ) return df.promise() module.exports.getAllIssueList = ()-> df = $.Deferred() module.exports.getProjectList().then (rslt)-> issP = _.map(rslt, (v)->module.exports.getIssueList(v.id)) $.when.apply($,issP).then (args...)->df.resolve _.flatten(args) return df.promise()
true
$ = require 'jquery' _ = require 'lodash' ipcRenderer = require('electron').ipcRenderer token = ipcRenderer.sendSync('getToken') maintenancePrjId = 19; devPrjId = 2; bmtPrjId = 15; customerTypeLabelColor = '#44ad8e' taskTypeLabelColor = '#428bca' deptTypeLabelColor = '#d9534f' priorityTypeLabelColor = '#ff0000' module.exports = {} ### issue format { "id": 350, "iid": 3, "project_id": 19, "description": "", "state": "opened", "created_at": "2016-10-10T15:39:35.203+09:00", "updated_at": "2016-10-10T15:45:43.812+09:00", "labels": [ "교통안전공단", "기능개선" ], "milestone": null, "assignee": null, "author": { "name": "callin", "username": "callin", "id": 4, "state": "active", "avatar_url": "http://www.gravatar.com/avatar/beb88205c2b0bbf7f2bcc8a4f503eceb?s=80\u0026d=identicon", "web_url": "http://elevisor.iptime.org:9937/u/callin" } } ### module.exports.setToken = (tkn) -> token = tkn module.exports.getIssueList = (prjId=2) -> df = $.Deferred() per_page = 100 page_index = 1; allIssueList = [] getIsList = -> $.ajax({ url : 'http://kranian:9937/api/v3/projects/'+prjId+'/issues?state=opened' headers : {'PRIVATE-TOKEN':token} data : { "per_page" : per_page "page" : page_index } }).then (response) -> #console.log 'response', response allIssueList.push(v) for v in response if per_page == response.length page_index++ getIsList() else df.resolve(allIssueList) getIsList() return df.promise() module.exports.getIssue = (prjId=2,issueId=1) -> df = $.Deferred() getIssue = -> $.ajax({ url : "http://kranian:9937/api/v3/projects/#{prjId}/issues/#{issueId}" headers : {'PRIVATE-TOKEN':token} }).then (response) -> df.resolve(response) getIssue() return df.promise() ###0 { "id": 6, "description": null, "default_branch": "master", "public": false, "visibility_level": 0, "ssh_url_to_repo": "PI:EMAIL:<EMAIL>END_PI:brightbox/puppet.git", "http_url_to_repo": "http://example.com/brightbox/puppet.git", "web_url": "http://example.com/brightbox/puppet", "tag_list": [ "example", "puppet" ], "owner": { "id": 4, "name": "Brightbox", "created_at": "2013-09-30T13:46:02Z" }, "name": "Puppet", "name_with_namespace": "Brightbox / Puppet", "path": "puppet", "path_with_namespace": "brightbox/puppet", "issues_enabled": true, "open_issues_count": 1, "merge_requests_enabled": true, "builds_enabled": true, "wiki_enabled": true, "snippets_enabled": false, "container_registry_enabled": false, "created_at": "2013-09-30T13:46:02Z", "last_activity_at": "2013-09-30T13:46:02Z", "creator_id": 3, "namespace": { "created_at": "2013-09-30T13:46:02Z", "description": "", "id": 4, "name": "Brightbox", "owner_id": 1, "path": "brightbox", "updated_at": "2013-09-30T13:46:02Z" }, "permissions": { "project_access": { "access_level": 10, "notification_level": 3 }, "group_access": { "access_level": 50, "notification_level": 3 } }, "archived": false, "avatar_url": null, "shared_runners_enabled": true, "forks_count": 0, "star_count": 0, "runners_token": "PI:KEY:<KEY>END_PI", "public_builds": true, "shared_with_groups": [], "only_allow_merge_if_build_succeeds": false, "request_access_enabled": false } ### module.exports.getProjectList= () -> df = $.Deferred() per_page = 100 page_index = 1; allIssueList = [] getIsList = -> $.ajax({ url : 'http://kranian:9937/api/v3/projects/all' headers : {'PRIVATE-TOKEN':token} data : { "per_page" : per_page "page" : page_index } }).then (response) -> console.log 'response', response allIssueList.push(v) for v in response if per_page == response.length page_index++ getIsList() else df.resolve(allIssueList) getIsList() return df.promise() module.exports.getUserList= () -> df = $.Deferred() per_page = 100 page_index = 1; allIssueList = [] getIsList = -> $.ajax({ url : 'http://kranian.org:9937/api/v3/users' headers : {'PRIVATE-TOKEN':token} data : { "per_page" : per_page "page" : page_index } }).then (response) -> allIssueList.push(v) for v in response if per_page == response.length page_index++ getIsList() else df.resolve(allIssueList) getIsList() return df.promise() ### {color:'#ff0000', name:'긴급'} ### module.exports.getLabelList = (projId) -> df = $.Deferred() per_page = 100 page_index = 1; allLabelList = [] getLbl = -> $.ajax({ url : 'http://kranian:9937/api/v3/projects/'+projId+'/labels' headers : {'PRIVATE-TOKEN':token} data : { "per_page" : per_page "page" : page_index } }).then (response) -> console.log 'response', response allLabelList.push(v) for v in response if per_page == response.body.length page_index++; getLbl(); else df.resolve allLabelList getLbl() return df.promise() module.exports.getLabelsByPrjNColor = (projId, color) -> df = $.Deferred() module.exports.getLabelList(projId).then (allLabelList )-> df.resolve( _(allLabelList).filter((v)->v.color == color).map('name').value() ) return df.promise() module.exports.getAllIssueList = ()-> df = $.Deferred() module.exports.getProjectList().then (rslt)-> issP = _.map(rslt, (v)->module.exports.getIssueList(v.id)) $.when.apply($,issP).then (args...)->df.resolve _.flatten(args) return df.promise()
[ { "context": "# Copyright © 2013 All rights reserved\n# Author: nhim175@gmail.com\n\nModule = require '../module.coffee'\nLogger = req", "end": 66, "score": 0.9999118447303772, "start": 49, "tag": "EMAIL", "value": "nhim175@gmail.com" } ]
src/lib/gui/axes.coffee
nhim175/larva-game
0
# Copyright © 2013 All rights reserved # Author: nhim175@gmail.com Module = require '../module.coffee' Logger = require '../../mixins/logger.coffee' Axe = require '../axe.coffee' class GUIAxes extends Module @include Logger logPrefix: 'GUIAxes' axes: 0 constructor: (game) -> @game = game @me = @game.add.group() @score = new Phaser.BitmapText @game, 120, 10, '8bit_wonder', '' + @axes, 40 @score.updateText() @score.x = 123 - @score.textWidth @axe = new Phaser.Image @game, 128, 0, 'axe' @axe.inputEnabled = true @axe.events.onInputDown.add @onClickAxeEvent @me.add @score @me.add @axe @me.x = @game.width - 64*3 - 50 @me.y = 50 $(@game).on 'GameOverEvent', @onGameOver onClickAxeEvent: => if not @game.isUsingAxes and @axes > 0 and !@game.isOver @debug 'use AXE' @axes-- @game.isUsingAxes = true onGameOver: => @game.isUsingAxes = false addAxe: -> @axes++ update: -> @score.text = '' + @axes @score.x = 123 - @score.width reset: -> @axes = 0 module.exports = GUIAxes
6387
# Copyright © 2013 All rights reserved # Author: <EMAIL> Module = require '../module.coffee' Logger = require '../../mixins/logger.coffee' Axe = require '../axe.coffee' class GUIAxes extends Module @include Logger logPrefix: 'GUIAxes' axes: 0 constructor: (game) -> @game = game @me = @game.add.group() @score = new Phaser.BitmapText @game, 120, 10, '8bit_wonder', '' + @axes, 40 @score.updateText() @score.x = 123 - @score.textWidth @axe = new Phaser.Image @game, 128, 0, 'axe' @axe.inputEnabled = true @axe.events.onInputDown.add @onClickAxeEvent @me.add @score @me.add @axe @me.x = @game.width - 64*3 - 50 @me.y = 50 $(@game).on 'GameOverEvent', @onGameOver onClickAxeEvent: => if not @game.isUsingAxes and @axes > 0 and !@game.isOver @debug 'use AXE' @axes-- @game.isUsingAxes = true onGameOver: => @game.isUsingAxes = false addAxe: -> @axes++ update: -> @score.text = '' + @axes @score.x = 123 - @score.width reset: -> @axes = 0 module.exports = GUIAxes
true
# Copyright © 2013 All rights reserved # Author: PI:EMAIL:<EMAIL>END_PI Module = require '../module.coffee' Logger = require '../../mixins/logger.coffee' Axe = require '../axe.coffee' class GUIAxes extends Module @include Logger logPrefix: 'GUIAxes' axes: 0 constructor: (game) -> @game = game @me = @game.add.group() @score = new Phaser.BitmapText @game, 120, 10, '8bit_wonder', '' + @axes, 40 @score.updateText() @score.x = 123 - @score.textWidth @axe = new Phaser.Image @game, 128, 0, 'axe' @axe.inputEnabled = true @axe.events.onInputDown.add @onClickAxeEvent @me.add @score @me.add @axe @me.x = @game.width - 64*3 - 50 @me.y = 50 $(@game).on 'GameOverEvent', @onGameOver onClickAxeEvent: => if not @game.isUsingAxes and @axes > 0 and !@game.isOver @debug 'use AXE' @axes-- @game.isUsingAxes = true onGameOver: => @game.isUsingAxes = false addAxe: -> @axes++ update: -> @score.text = '' + @axes @score.x = 123 - @score.width reset: -> @axes = 0 module.exports = GUIAxes
[ { "context": " ported to CoffeeScript\n\t\tdebouncing function from John Hann\n\t\thttp://unscriptable.com/index.php/2009/03/20/de", "end": 125, "score": 0.9997718334197998, "start": 116, "tag": "NAME", "value": "John Hann" }, { "context": "###\n\t@isLocalhost: () ->\n\t\thosts = ['localhost', '0.0.0.0', '127.0.0.1']\n\t\thosts.indexOf(document.location.", "end": 660, "score": 0.9928568601608276, "start": 653, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "alhost: () ->\n\t\thosts = ['localhost', '0.0.0.0', '127.0.0.1']\n\t\thosts.indexOf(document.location.hostname) isn", "end": 673, "score": 0.9995265603065491, "start": 664, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
app/_src/utils.coffee
14islands/14islands-com
13
class FOURTEEN.Utils ### Debounce and SmartResize (in jQuery) ported to CoffeeScript debouncing function from John Hann http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/ ### @debounce: (func, threshold, execAsap) -> timeout = false return debounced = -> obj = this args = arguments delayed = -> func.apply(obj, args) unless execAsap timeout = null if timeout clearTimeout(timeout) else if (execAsap) func.apply(obj, args) timeout = setTimeout delayed, threshold || 100 ### Simple checks if we are dealing with localhost ### @isLocalhost: () -> hosts = ['localhost', '0.0.0.0', '127.0.0.1'] hosts.indexOf(document.location.hostname) isnt -1 ### Returns a random number based on the given min and max interval. @param {Integer} min from which number @param {Integer} max until which number @return {[type]} Integer ### @getRandomNumber: (min, max) -> Math.floor(Math.random()*(max-min+1)+min) ### Rounds up to the closest multiple of 10 @param {Integer} n number to be rounded up @return {Integer} number rounded to a multiple of 10. e.g. 20, 30, 40, etc. ### @getRoundUp: (n) -> result = n if (n % 10) result = n + (10 - n % 10) return result ### Returns the browser prefixed string for the animation end event ### @whichAnimationEvent: () -> t = undefined el = document.createElement('div') animationNames = 'WebkitAnimation': 'webkitAnimationEnd' 'MozAnimation': 'animationend' 'OAnimation': 'oAnimationEnd oanimationend' 'animation': 'animationend' for t of animationNames if el.style[t] != undefined return animationNames[t]
62823
class FOURTEEN.Utils ### Debounce and SmartResize (in jQuery) ported to CoffeeScript debouncing function from <NAME> http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/ ### @debounce: (func, threshold, execAsap) -> timeout = false return debounced = -> obj = this args = arguments delayed = -> func.apply(obj, args) unless execAsap timeout = null if timeout clearTimeout(timeout) else if (execAsap) func.apply(obj, args) timeout = setTimeout delayed, threshold || 100 ### Simple checks if we are dealing with localhost ### @isLocalhost: () -> hosts = ['localhost', '0.0.0.0', '127.0.0.1'] hosts.indexOf(document.location.hostname) isnt -1 ### Returns a random number based on the given min and max interval. @param {Integer} min from which number @param {Integer} max until which number @return {[type]} Integer ### @getRandomNumber: (min, max) -> Math.floor(Math.random()*(max-min+1)+min) ### Rounds up to the closest multiple of 10 @param {Integer} n number to be rounded up @return {Integer} number rounded to a multiple of 10. e.g. 20, 30, 40, etc. ### @getRoundUp: (n) -> result = n if (n % 10) result = n + (10 - n % 10) return result ### Returns the browser prefixed string for the animation end event ### @whichAnimationEvent: () -> t = undefined el = document.createElement('div') animationNames = 'WebkitAnimation': 'webkitAnimationEnd' 'MozAnimation': 'animationend' 'OAnimation': 'oAnimationEnd oanimationend' 'animation': 'animationend' for t of animationNames if el.style[t] != undefined return animationNames[t]
true
class FOURTEEN.Utils ### Debounce and SmartResize (in jQuery) ported to CoffeeScript debouncing function from PI:NAME:<NAME>END_PI http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/ ### @debounce: (func, threshold, execAsap) -> timeout = false return debounced = -> obj = this args = arguments delayed = -> func.apply(obj, args) unless execAsap timeout = null if timeout clearTimeout(timeout) else if (execAsap) func.apply(obj, args) timeout = setTimeout delayed, threshold || 100 ### Simple checks if we are dealing with localhost ### @isLocalhost: () -> hosts = ['localhost', '0.0.0.0', '127.0.0.1'] hosts.indexOf(document.location.hostname) isnt -1 ### Returns a random number based on the given min and max interval. @param {Integer} min from which number @param {Integer} max until which number @return {[type]} Integer ### @getRandomNumber: (min, max) -> Math.floor(Math.random()*(max-min+1)+min) ### Rounds up to the closest multiple of 10 @param {Integer} n number to be rounded up @return {Integer} number rounded to a multiple of 10. e.g. 20, 30, 40, etc. ### @getRoundUp: (n) -> result = n if (n % 10) result = n + (10 - n % 10) return result ### Returns the browser prefixed string for the animation end event ### @whichAnimationEvent: () -> t = undefined el = document.createElement('div') animationNames = 'WebkitAnimation': 'webkitAnimationEnd' 'MozAnimation': 'animationend' 'OAnimation': 'oAnimationEnd oanimationend' 'animation': 'animationend' for t of animationNames if el.style[t] != undefined return animationNames[t]
[ { "context": "\n setState(res, userState)\n\n robot.hear /login joshua/i, (res) ->\n userState = getState(res)\n if ", "end": 836, "score": 0.9486395716667175, "start": 830, "tag": "NAME", "value": "joshua" }, { "context": "prState != 1\n return\n\n res.send \"GREETINGS PROFESSOR FALKEN.\"\n res.finish\n\n userState.woprS", "end": 953, "score": 0.5129246711730957, "start": 949, "tag": "NAME", "value": "PROF" }, { "context": " 1\n return\n\n res.send \"GREETINGS PROFESSOR FALKEN.\"\n res.finish\n\n userState.woprState = 2\n ", "end": 965, "score": 0.8615245223045349, "start": 959, "tag": "NAME", "value": "FALKEN" }, { "context": "\n \"help games\\n\" +\n \"login joshua\\n\" +\n \"what is the primary goal\\n\" +\n", "end": 2901, "score": 0.9936563372612, "start": 2895, "tag": "USERNAME", "value": "joshua" } ]
scripts/wopr.coffee
ftcjeff/hubot-pops
0
module.exports = (robot) -> getState = (res) -> state = res.message.user.id woprState = robot.brain.get(state) or {woprState: 0} return woprState setState = (res, woprState) -> state = res.message.user.id robot.brain.set(state, woprState) robot.hear /help games/i, (res) -> res.send "'GAMES' REFERS TO MODELS, SIMULATIONS AND GAMES WHICH HAVE TACTICAL AND STRATEGIC APPLICATIONS." robot.hear /list games/i, (res) -> res.send "FALKEN'S MAZE\nBLACK JACK\nGIN RUMMY\nHEARTS\nBRIDGE\nCHECKERS\nCHESS\nPOKER\nFIGHTER COMBAT\nGUERRILLA ENGAGEMENT\nDESERT WARFARE\nAIR-TO-GROUND ACTIONS\nTHEATERWIDE TACTICAL WARFARE\nTHEATERWIDE BIOTOXIC AND CHEMICAL WARFARE\n\nGLOBAL THERMONUCLEAR WAR" userState = getState(res) userState.woprState = 1 setState(res, userState) robot.hear /login joshua/i, (res) -> userState = getState(res) if userState.woprState != 1 return res.send "GREETINGS PROFESSOR FALKEN." res.finish userState.woprState = 2 setState(res, userState) robot.hear /hello/i, (res) -> userState = getState(res) if userState.woprState != 2 return res.send "HOW ARE YOU FEELING TODAY?" res.finish userState.woprState = 3 setState(res, userState) robot.hear /I'm fine. how are you|I'm fine. how are you|how are you/i, (res) -> userState = getState(res) if userState.woprState != 3 return res.send "EXCELLENT. IT'S BEEN A LONG TIME. CAN YOU EXPLAIN THE REMOVAL OF YOUR USER ACCOUNT NUMBER ON 6/23/73?" res.finish userState.woprState = 4 setState(res, userState) robot.hear /People sometimes make mistak/i, (res) -> userState = getState(res) if userState.woprState != 4 return res.send "YES THEY DO. SHALL WE PLAY A GAME?" res.finish userState.woprState = 5 setState(res, userState) robot.hear /How about Global Thermonuclear War/i, (res) -> userState = getState(res) if userState.woprState != 5 return res.send "WOULDN'T YOU PREFER A GOOD GAME OF CHESS?" res.finish userState.woprState = 6 setState(res, userState) robot.hear /Let's play Global Thermonuclear War/i, (res) -> userState = getState(res) if userState.woprState != 6 return res.send "FINE" res.finish userState.woprState = 1 setState(res, userState) robot.hear /What is the primary goal/i, (res) -> res.send "TO WIN THE GAME." res.finish robot.hear /is this a game or is it real?/i, (res) -> res.send "WHAT'S THE DIFFERENCE?" res.finish robot.hear /wopr reset/i, (res) -> res.reply "Okay, I've reset you back to the beginning" res.finish userState = getState(res) userState.woprState = 1 setState(res, userState) robot.respond /help/i, (res) -> res.send "list games\n" + "help games\n" + "login joshua\n" + "what is the primary goal\n" + "is this a game or is it real?\n" + "wopr reset\n"
91428
module.exports = (robot) -> getState = (res) -> state = res.message.user.id woprState = robot.brain.get(state) or {woprState: 0} return woprState setState = (res, woprState) -> state = res.message.user.id robot.brain.set(state, woprState) robot.hear /help games/i, (res) -> res.send "'GAMES' REFERS TO MODELS, SIMULATIONS AND GAMES WHICH HAVE TACTICAL AND STRATEGIC APPLICATIONS." robot.hear /list games/i, (res) -> res.send "FALKEN'S MAZE\nBLACK JACK\nGIN RUMMY\nHEARTS\nBRIDGE\nCHECKERS\nCHESS\nPOKER\nFIGHTER COMBAT\nGUERRILLA ENGAGEMENT\nDESERT WARFARE\nAIR-TO-GROUND ACTIONS\nTHEATERWIDE TACTICAL WARFARE\nTHEATERWIDE BIOTOXIC AND CHEMICAL WARFARE\n\nGLOBAL THERMONUCLEAR WAR" userState = getState(res) userState.woprState = 1 setState(res, userState) robot.hear /login <NAME>/i, (res) -> userState = getState(res) if userState.woprState != 1 return res.send "GREETINGS <NAME>ESSOR <NAME>." res.finish userState.woprState = 2 setState(res, userState) robot.hear /hello/i, (res) -> userState = getState(res) if userState.woprState != 2 return res.send "HOW ARE YOU FEELING TODAY?" res.finish userState.woprState = 3 setState(res, userState) robot.hear /I'm fine. how are you|I'm fine. how are you|how are you/i, (res) -> userState = getState(res) if userState.woprState != 3 return res.send "EXCELLENT. IT'S BEEN A LONG TIME. CAN YOU EXPLAIN THE REMOVAL OF YOUR USER ACCOUNT NUMBER ON 6/23/73?" res.finish userState.woprState = 4 setState(res, userState) robot.hear /People sometimes make mistak/i, (res) -> userState = getState(res) if userState.woprState != 4 return res.send "YES THEY DO. SHALL WE PLAY A GAME?" res.finish userState.woprState = 5 setState(res, userState) robot.hear /How about Global Thermonuclear War/i, (res) -> userState = getState(res) if userState.woprState != 5 return res.send "WOULDN'T YOU PREFER A GOOD GAME OF CHESS?" res.finish userState.woprState = 6 setState(res, userState) robot.hear /Let's play Global Thermonuclear War/i, (res) -> userState = getState(res) if userState.woprState != 6 return res.send "FINE" res.finish userState.woprState = 1 setState(res, userState) robot.hear /What is the primary goal/i, (res) -> res.send "TO WIN THE GAME." res.finish robot.hear /is this a game or is it real?/i, (res) -> res.send "WHAT'S THE DIFFERENCE?" res.finish robot.hear /wopr reset/i, (res) -> res.reply "Okay, I've reset you back to the beginning" res.finish userState = getState(res) userState.woprState = 1 setState(res, userState) robot.respond /help/i, (res) -> res.send "list games\n" + "help games\n" + "login joshua\n" + "what is the primary goal\n" + "is this a game or is it real?\n" + "wopr reset\n"
true
module.exports = (robot) -> getState = (res) -> state = res.message.user.id woprState = robot.brain.get(state) or {woprState: 0} return woprState setState = (res, woprState) -> state = res.message.user.id robot.brain.set(state, woprState) robot.hear /help games/i, (res) -> res.send "'GAMES' REFERS TO MODELS, SIMULATIONS AND GAMES WHICH HAVE TACTICAL AND STRATEGIC APPLICATIONS." robot.hear /list games/i, (res) -> res.send "FALKEN'S MAZE\nBLACK JACK\nGIN RUMMY\nHEARTS\nBRIDGE\nCHECKERS\nCHESS\nPOKER\nFIGHTER COMBAT\nGUERRILLA ENGAGEMENT\nDESERT WARFARE\nAIR-TO-GROUND ACTIONS\nTHEATERWIDE TACTICAL WARFARE\nTHEATERWIDE BIOTOXIC AND CHEMICAL WARFARE\n\nGLOBAL THERMONUCLEAR WAR" userState = getState(res) userState.woprState = 1 setState(res, userState) robot.hear /login PI:NAME:<NAME>END_PI/i, (res) -> userState = getState(res) if userState.woprState != 1 return res.send "GREETINGS PI:NAME:<NAME>END_PIESSOR PI:NAME:<NAME>END_PI." res.finish userState.woprState = 2 setState(res, userState) robot.hear /hello/i, (res) -> userState = getState(res) if userState.woprState != 2 return res.send "HOW ARE YOU FEELING TODAY?" res.finish userState.woprState = 3 setState(res, userState) robot.hear /I'm fine. how are you|I'm fine. how are you|how are you/i, (res) -> userState = getState(res) if userState.woprState != 3 return res.send "EXCELLENT. IT'S BEEN A LONG TIME. CAN YOU EXPLAIN THE REMOVAL OF YOUR USER ACCOUNT NUMBER ON 6/23/73?" res.finish userState.woprState = 4 setState(res, userState) robot.hear /People sometimes make mistak/i, (res) -> userState = getState(res) if userState.woprState != 4 return res.send "YES THEY DO. SHALL WE PLAY A GAME?" res.finish userState.woprState = 5 setState(res, userState) robot.hear /How about Global Thermonuclear War/i, (res) -> userState = getState(res) if userState.woprState != 5 return res.send "WOULDN'T YOU PREFER A GOOD GAME OF CHESS?" res.finish userState.woprState = 6 setState(res, userState) robot.hear /Let's play Global Thermonuclear War/i, (res) -> userState = getState(res) if userState.woprState != 6 return res.send "FINE" res.finish userState.woprState = 1 setState(res, userState) robot.hear /What is the primary goal/i, (res) -> res.send "TO WIN THE GAME." res.finish robot.hear /is this a game or is it real?/i, (res) -> res.send "WHAT'S THE DIFFERENCE?" res.finish robot.hear /wopr reset/i, (res) -> res.reply "Okay, I've reset you back to the beginning" res.finish userState = getState(res) userState.woprState = 1 setState(res, userState) robot.respond /help/i, (res) -> res.send "list games\n" + "help games\n" + "login joshua\n" + "what is the primary goal\n" + "is this a game or is it real?\n" + "wopr reset\n"
[ { "context": "# @file oldParticle.coffee\n# @Copyright (c) 2016 Taylor Siviter\n# This source code is licensed under the MIT Lice", "end": 63, "score": 0.9997237324714661, "start": 49, "tag": "NAME", "value": "Taylor Siviter" } ]
src/_deprecated/oldParticle.coffee
siviter-t/lampyridae.coffee
4
# @file oldParticle.coffee # @Copyright (c) 2016 Taylor Siviter # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. class Lampyridae.OldParticle ### Construct and manage a generic circular particle. # # @param canvas [Object] Instance of Lampyridae.Canvas to attach the particle to # # @option x [Number] Position of the particle along the x-axis # @option y [Number] Position of the particle along the y-axis # @option theta [Number] Direction of the particle (rads anticlockwise from the x-axis) # @option speed [Number] Speed of the particle # @option radius [Number] Radius of the particle # @option bound [String] Type of bounding [none|hard|periodic] # @option alpha [Number] Opacity of the particle # @option enableFill [Bool] Should the particle be filled with @colour # @option colour [String] Colour code of the particle - e.g. "rgb(255, 255, 255)" # @option enableStroke [Bool] Should the particle have a border stroke # @option strokeWidth [Number] Width of the stroke [default: 1] # @option strokeColour [String] Colour of the stroke [default: @colour] ### constructor: (@canvas, options) -> unless arguments.length > 0 throw new Error "OldParticle requires a valid Canvas instance to be attached to" options ?= {} if toString.call(options) isnt '[object Object]' throw new Error "OldParticle requires a valid object of options" @x = options.x ? 0.0 @y = options.y ? 0.0 @t = options.theta ? 0.0 @v = options.speed ? 0.0 @r = options.radius ? 1.0 @bounded = false @periodic = false if options.bound? switch options.bound when "hard" then @bounded = true when "periodic" then @bounded = true; @periodic = true when "none" else console.warn "Lampyridae: #{options.bound} is not valid bound. Defaulting to 'none'" @alpha = options.alpha ? 1.0 @enableFill = options.enableFill ? true @colour = options.colour ? "rgb(255, 255, 255)" @enableStroke = options.enableStroke ? false @strokeWidth = options.strokeWidth ? 1 @strokeColour = options.strokeColour ? @colour ### Particle class prototype parameters. # Can be set by the user; e.g. Lampyridae.Particle::enableGlow = true, etc. ### enableAlpha: false enableGlow: false glowFactor: 4.0 # Movement methods # ### Velocity component in the x-direction. ### vx: () -> return @v * Math.cos(@t) ### Velocity component in the y-direction. ### vy: () -> return @v * Math.sin(@t) ### Turn the particle. # # @param angle [Number] Number of radians to turn anticlockwise from the x-axis ### turn: (angle = 0.0) -> @t += angle ### Turn the particle around. ### turnAround: () -> @turn Math.PI ### Move the particle using its velocity and this applications defined time step. ### move: () -> @x += Lampyridae.timestep * @vx() @y += Lampyridae.timestep * @vy() # Detection and boundary methods # ### Is the particle outside the canvas in the x-axis? # # @return [Bool] True if it outside; false otherwise ### isOutsideCanvasX: () -> unless 0.0 <= @x <= @canvas.width() then return true return false ### Is the particle outside the canvas in the y-axis? # # @return [Bool] True if it outside; false otherwise ### isOutsideCanvasY: () -> unless 0.0 <= @y <= @canvas.height() then return true return false ### Is the particle outside the canvas window? # # @return [Bool] True if it outside; false otherwise ###G isOutsideCanvas: () -> return @isOutsideCanvasX() or @isOutsideCanvasY() ### Act as if the boundary of the canvas is 'hard-walled'. # # @return [Bool] True if action has been made; false otherwise ### applyHardBounds: () -> if @isOutsideCanvas() @turnAround() @move until @isOutsideCanvas() return true return false ### Act as if the boundary of the canvas is 'periodic'. # # @return [Bool] True if action has been made; false otherwise ### applyPeriodicBounds: () -> result = false if @isOutsideCanvasX() @x = -@x + @canvas.width() result = true if @isOutsideCanvasY() @y = -@y + @canvas.height() result = true return result ### Check and act if there are bounds applied. # # @return [Bool] True if action has been made; false otherwise ### applyBounds: () -> if @periodic then return @applyPeriodicBounds() if @bounded then return @applyHardBounds() return false ### Simple particle update method. ### update: () -> @applyBounds() @move() @draw() ### Draw the particle to the screen. # Alpha and glow can be toggled by proto members # Fill and stroke can be toggled by instance members ### draw: () -> @canvas.draw.begin() if @enableAlpha then @canvas.draw.setGlobalAlpha @alpha if @enableGlow then @canvas.draw.glow @glowFactor * @r, @colour @canvas.draw.circle @x, @y, @r if @enableFill then @canvas.draw.fill @colour if @enableStroke then @canvas.draw.stroke @strokeWidth, @strokeColour @canvas.draw.end() # end class Lampyridae.OldParticle module.exports = Lampyridae.OldParticle
40959
# @file oldParticle.coffee # @Copyright (c) 2016 <NAME> # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. class Lampyridae.OldParticle ### Construct and manage a generic circular particle. # # @param canvas [Object] Instance of Lampyridae.Canvas to attach the particle to # # @option x [Number] Position of the particle along the x-axis # @option y [Number] Position of the particle along the y-axis # @option theta [Number] Direction of the particle (rads anticlockwise from the x-axis) # @option speed [Number] Speed of the particle # @option radius [Number] Radius of the particle # @option bound [String] Type of bounding [none|hard|periodic] # @option alpha [Number] Opacity of the particle # @option enableFill [Bool] Should the particle be filled with @colour # @option colour [String] Colour code of the particle - e.g. "rgb(255, 255, 255)" # @option enableStroke [Bool] Should the particle have a border stroke # @option strokeWidth [Number] Width of the stroke [default: 1] # @option strokeColour [String] Colour of the stroke [default: @colour] ### constructor: (@canvas, options) -> unless arguments.length > 0 throw new Error "OldParticle requires a valid Canvas instance to be attached to" options ?= {} if toString.call(options) isnt '[object Object]' throw new Error "OldParticle requires a valid object of options" @x = options.x ? 0.0 @y = options.y ? 0.0 @t = options.theta ? 0.0 @v = options.speed ? 0.0 @r = options.radius ? 1.0 @bounded = false @periodic = false if options.bound? switch options.bound when "hard" then @bounded = true when "periodic" then @bounded = true; @periodic = true when "none" else console.warn "Lampyridae: #{options.bound} is not valid bound. Defaulting to 'none'" @alpha = options.alpha ? 1.0 @enableFill = options.enableFill ? true @colour = options.colour ? "rgb(255, 255, 255)" @enableStroke = options.enableStroke ? false @strokeWidth = options.strokeWidth ? 1 @strokeColour = options.strokeColour ? @colour ### Particle class prototype parameters. # Can be set by the user; e.g. Lampyridae.Particle::enableGlow = true, etc. ### enableAlpha: false enableGlow: false glowFactor: 4.0 # Movement methods # ### Velocity component in the x-direction. ### vx: () -> return @v * Math.cos(@t) ### Velocity component in the y-direction. ### vy: () -> return @v * Math.sin(@t) ### Turn the particle. # # @param angle [Number] Number of radians to turn anticlockwise from the x-axis ### turn: (angle = 0.0) -> @t += angle ### Turn the particle around. ### turnAround: () -> @turn Math.PI ### Move the particle using its velocity and this applications defined time step. ### move: () -> @x += Lampyridae.timestep * @vx() @y += Lampyridae.timestep * @vy() # Detection and boundary methods # ### Is the particle outside the canvas in the x-axis? # # @return [Bool] True if it outside; false otherwise ### isOutsideCanvasX: () -> unless 0.0 <= @x <= @canvas.width() then return true return false ### Is the particle outside the canvas in the y-axis? # # @return [Bool] True if it outside; false otherwise ### isOutsideCanvasY: () -> unless 0.0 <= @y <= @canvas.height() then return true return false ### Is the particle outside the canvas window? # # @return [Bool] True if it outside; false otherwise ###G isOutsideCanvas: () -> return @isOutsideCanvasX() or @isOutsideCanvasY() ### Act as if the boundary of the canvas is 'hard-walled'. # # @return [Bool] True if action has been made; false otherwise ### applyHardBounds: () -> if @isOutsideCanvas() @turnAround() @move until @isOutsideCanvas() return true return false ### Act as if the boundary of the canvas is 'periodic'. # # @return [Bool] True if action has been made; false otherwise ### applyPeriodicBounds: () -> result = false if @isOutsideCanvasX() @x = -@x + @canvas.width() result = true if @isOutsideCanvasY() @y = -@y + @canvas.height() result = true return result ### Check and act if there are bounds applied. # # @return [Bool] True if action has been made; false otherwise ### applyBounds: () -> if @periodic then return @applyPeriodicBounds() if @bounded then return @applyHardBounds() return false ### Simple particle update method. ### update: () -> @applyBounds() @move() @draw() ### Draw the particle to the screen. # Alpha and glow can be toggled by proto members # Fill and stroke can be toggled by instance members ### draw: () -> @canvas.draw.begin() if @enableAlpha then @canvas.draw.setGlobalAlpha @alpha if @enableGlow then @canvas.draw.glow @glowFactor * @r, @colour @canvas.draw.circle @x, @y, @r if @enableFill then @canvas.draw.fill @colour if @enableStroke then @canvas.draw.stroke @strokeWidth, @strokeColour @canvas.draw.end() # end class Lampyridae.OldParticle module.exports = Lampyridae.OldParticle
true
# @file oldParticle.coffee # @Copyright (c) 2016 PI:NAME:<NAME>END_PI # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. class Lampyridae.OldParticle ### Construct and manage a generic circular particle. # # @param canvas [Object] Instance of Lampyridae.Canvas to attach the particle to # # @option x [Number] Position of the particle along the x-axis # @option y [Number] Position of the particle along the y-axis # @option theta [Number] Direction of the particle (rads anticlockwise from the x-axis) # @option speed [Number] Speed of the particle # @option radius [Number] Radius of the particle # @option bound [String] Type of bounding [none|hard|periodic] # @option alpha [Number] Opacity of the particle # @option enableFill [Bool] Should the particle be filled with @colour # @option colour [String] Colour code of the particle - e.g. "rgb(255, 255, 255)" # @option enableStroke [Bool] Should the particle have a border stroke # @option strokeWidth [Number] Width of the stroke [default: 1] # @option strokeColour [String] Colour of the stroke [default: @colour] ### constructor: (@canvas, options) -> unless arguments.length > 0 throw new Error "OldParticle requires a valid Canvas instance to be attached to" options ?= {} if toString.call(options) isnt '[object Object]' throw new Error "OldParticle requires a valid object of options" @x = options.x ? 0.0 @y = options.y ? 0.0 @t = options.theta ? 0.0 @v = options.speed ? 0.0 @r = options.radius ? 1.0 @bounded = false @periodic = false if options.bound? switch options.bound when "hard" then @bounded = true when "periodic" then @bounded = true; @periodic = true when "none" else console.warn "Lampyridae: #{options.bound} is not valid bound. Defaulting to 'none'" @alpha = options.alpha ? 1.0 @enableFill = options.enableFill ? true @colour = options.colour ? "rgb(255, 255, 255)" @enableStroke = options.enableStroke ? false @strokeWidth = options.strokeWidth ? 1 @strokeColour = options.strokeColour ? @colour ### Particle class prototype parameters. # Can be set by the user; e.g. Lampyridae.Particle::enableGlow = true, etc. ### enableAlpha: false enableGlow: false glowFactor: 4.0 # Movement methods # ### Velocity component in the x-direction. ### vx: () -> return @v * Math.cos(@t) ### Velocity component in the y-direction. ### vy: () -> return @v * Math.sin(@t) ### Turn the particle. # # @param angle [Number] Number of radians to turn anticlockwise from the x-axis ### turn: (angle = 0.0) -> @t += angle ### Turn the particle around. ### turnAround: () -> @turn Math.PI ### Move the particle using its velocity and this applications defined time step. ### move: () -> @x += Lampyridae.timestep * @vx() @y += Lampyridae.timestep * @vy() # Detection and boundary methods # ### Is the particle outside the canvas in the x-axis? # # @return [Bool] True if it outside; false otherwise ### isOutsideCanvasX: () -> unless 0.0 <= @x <= @canvas.width() then return true return false ### Is the particle outside the canvas in the y-axis? # # @return [Bool] True if it outside; false otherwise ### isOutsideCanvasY: () -> unless 0.0 <= @y <= @canvas.height() then return true return false ### Is the particle outside the canvas window? # # @return [Bool] True if it outside; false otherwise ###G isOutsideCanvas: () -> return @isOutsideCanvasX() or @isOutsideCanvasY() ### Act as if the boundary of the canvas is 'hard-walled'. # # @return [Bool] True if action has been made; false otherwise ### applyHardBounds: () -> if @isOutsideCanvas() @turnAround() @move until @isOutsideCanvas() return true return false ### Act as if the boundary of the canvas is 'periodic'. # # @return [Bool] True if action has been made; false otherwise ### applyPeriodicBounds: () -> result = false if @isOutsideCanvasX() @x = -@x + @canvas.width() result = true if @isOutsideCanvasY() @y = -@y + @canvas.height() result = true return result ### Check and act if there are bounds applied. # # @return [Bool] True if action has been made; false otherwise ### applyBounds: () -> if @periodic then return @applyPeriodicBounds() if @bounded then return @applyHardBounds() return false ### Simple particle update method. ### update: () -> @applyBounds() @move() @draw() ### Draw the particle to the screen. # Alpha and glow can be toggled by proto members # Fill and stroke can be toggled by instance members ### draw: () -> @canvas.draw.begin() if @enableAlpha then @canvas.draw.setGlobalAlpha @alpha if @enableGlow then @canvas.draw.glow @glowFactor * @r, @colour @canvas.draw.circle @x, @y, @r if @enableFill then @canvas.draw.fill @colour if @enableStroke then @canvas.draw.stroke @strokeWidth, @strokeColour @canvas.draw.end() # end class Lampyridae.OldParticle module.exports = Lampyridae.OldParticle
[ { "context": "# Copyright (C) 2016-present Arctic Ice Studio <development@arcticicestudio.com>\n# Copyright (C)", "end": 46, "score": 0.9034414291381836, "start": 29, "tag": "NAME", "value": "Arctic Ice Studio" }, { "context": "# Copyright (C) 2016-present Arctic Ice Studio <development@arcticicestudio.com>\n# Copyright (C) 2016-present Sven Greb <developm", "end": 79, "score": 0.9999305605888367, "start": 48, "tag": "EMAIL", "value": "development@arcticicestudio.com" }, { "context": "@arcticicestudio.com>\n# Copyright (C) 2016-present Sven Greb <development@svengreb.de>\n\n# Project: Nord Ato", "end": 119, "score": 0.9998995065689087, "start": 110, "tag": "NAME", "value": "Sven Greb" }, { "context": "udio.com>\n# Copyright (C) 2016-present Sven Greb <development@svengreb.de>\n\n# Project: Nord Atom UI\n# Repository: https:", "end": 144, "score": 0.9999285340309143, "start": 121, "tag": "EMAIL", "value": "development@svengreb.de" }, { "context": " Nord Atom UI\n# Repository: https://github.com/arcticicestudio/nord-atom-ui\n# License: MIT\n\nroot = document.d", "end": 222, "score": 0.5876943469047546, "start": 209, "tag": "USERNAME", "value": "cticicestudio" } ]
lib/main.coffee
germanescobar/nord-atom-ui
125
# Copyright (C) 2016-present Arctic Ice Studio <development@arcticicestudio.com> # Copyright (C) 2016-present Sven Greb <development@svengreb.de> # Project: Nord Atom UI # Repository: https://github.com/arcticicestudio/nord-atom-ui # License: MIT root = document.documentElement; module.exports = activate: (state) -> atom.config.observe 'nord-atom-ui.tabSizing', (noFullWidth) -> setTabSizing(noFullWidth) atom.config.observe 'nord-atom-ui.darkerFormFocusEffect', (noSnowLight) -> setFormFocusEffect(noSnowLight) deactivate: -> unsetTabSizing() unsetFormFocusEffect() setFormFocusEffect = (noSnowLight) -> if (noSnowLight) root.setAttribute('theme-nord-atom-ui-form-focus-effect', "nosnowlight") else unsetFormFocusEffect() setTabSizing = (noFullWidth) -> if (noFullWidth) unsetTabSizing() else root.setAttribute('theme-nord-atom-ui-tabsizing', "nofullwidth") unsetFormFocusEffect = -> root.removeAttribute('theme-nord-atom-ui-form-focus-effect') unsetTabSizing = -> root.removeAttribute('theme-nord-atom-ui-tabsizing')
173251
# Copyright (C) 2016-present <NAME> <<EMAIL>> # Copyright (C) 2016-present <NAME> <<EMAIL>> # Project: Nord Atom UI # Repository: https://github.com/arcticicestudio/nord-atom-ui # License: MIT root = document.documentElement; module.exports = activate: (state) -> atom.config.observe 'nord-atom-ui.tabSizing', (noFullWidth) -> setTabSizing(noFullWidth) atom.config.observe 'nord-atom-ui.darkerFormFocusEffect', (noSnowLight) -> setFormFocusEffect(noSnowLight) deactivate: -> unsetTabSizing() unsetFormFocusEffect() setFormFocusEffect = (noSnowLight) -> if (noSnowLight) root.setAttribute('theme-nord-atom-ui-form-focus-effect', "nosnowlight") else unsetFormFocusEffect() setTabSizing = (noFullWidth) -> if (noFullWidth) unsetTabSizing() else root.setAttribute('theme-nord-atom-ui-tabsizing', "nofullwidth") unsetFormFocusEffect = -> root.removeAttribute('theme-nord-atom-ui-form-focus-effect') unsetTabSizing = -> root.removeAttribute('theme-nord-atom-ui-tabsizing')
true
# Copyright (C) 2016-present PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2016-present PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Project: Nord Atom UI # Repository: https://github.com/arcticicestudio/nord-atom-ui # License: MIT root = document.documentElement; module.exports = activate: (state) -> atom.config.observe 'nord-atom-ui.tabSizing', (noFullWidth) -> setTabSizing(noFullWidth) atom.config.observe 'nord-atom-ui.darkerFormFocusEffect', (noSnowLight) -> setFormFocusEffect(noSnowLight) deactivate: -> unsetTabSizing() unsetFormFocusEffect() setFormFocusEffect = (noSnowLight) -> if (noSnowLight) root.setAttribute('theme-nord-atom-ui-form-focus-effect', "nosnowlight") else unsetFormFocusEffect() setTabSizing = (noFullWidth) -> if (noFullWidth) unsetTabSizing() else root.setAttribute('theme-nord-atom-ui-tabsizing', "nofullwidth") unsetFormFocusEffect = -> root.removeAttribute('theme-nord-atom-ui-form-focus-effect') unsetTabSizing = -> root.removeAttribute('theme-nord-atom-ui-tabsizing')
[ { "context": " }),\n\t\t#\t\tJSON.stringify({ auth: { client_token: \"TempToken\" } })\n\t\t#\t]\n\n\t\t#\trequestorStub = new RequestorStu", "end": 2646, "score": 0.7126826643943787, "start": 2637, "tag": "PASSWORD", "value": "TempToken" } ]
tests/program_test.coffee
VeriShip/cubby
2
'use strict' should = require 'should' events = require 'events' Program = require '../src/program' queryString = require 'querystring' q = require 'q' describe 'Program', -> context '#constructor', -> it 'should pass requestorObj to @requestor', -> expectedValue = { } target = new Program(expectedValue) should.strictEqual(target.requestor, expectedValue) it 'should pass userTokenObj to @userToken', -> expectedValue = { } target = new Program({ }, expectedValue) should.strictEqual(target.userToken, expectedValue) context '#go', -> it 'should throw an error if we pass undefined in for path', -> should.throws -> target = new Program() target.request() it 'should throw an error if we pass null in for path', -> should.throws -> target = new Program() target.request(null) it 'should throw an error if we pass something other than a string for path', -> should.throws -> target = new Program() target.request(1) it 'should throw an error if we pass undefined in for ttl', -> should.throws -> target = new Program() target.request("a") it 'should throw an error if we pass null in for ttl', -> should.throws -> target = new Program() target.request("a", null) it 'should throw an error if we pass something other than a string for ttl', -> should.throws -> target = new Program() target.request("a", 1) it 'should throw an error if we pass undefined in for policyCollection', -> should.throws -> target = new Program() target.request("a", "a") it 'should throw an error if we pass null in for policyCollection', -> should.throws -> target = new Program() target.request("a", "a", null) it 'should throw an error if we pass in something other than an array', -> should.throws -> target = new Program() target.request("a", "a", 1) it 'should throw an error if we pass in an array with values that are not strings', -> should.throws -> target = new Program() target.request("a", "a", [ 'a', 1 ]) # This test is failing the build on debian (travis-ci) # #it 'should return temporary token', (done) -> # class RequestorStub # constructor: (requestQueue, optionsQueue) -> # @requestQueue = requestQueue # @optionsQueue = optionsQueue # request: => # q @requestQueue.pop() # createRequestOptions: => # @optionsQueue.pop() # optionsQueue = [ # { }, { }, { } # ] # requestQueue = [ # JSON.stringify({ }), # JSON.stringify({ auth: { client_token: "permToken" } }), # JSON.stringify({ auth: { client_token: "TempToken" } }) # ] # requestorStub = new RequestorStub(requestQueue, optionsQueue) # target = new Program(requestorStub) # target.go("a", "b", [ "a" ]).done (success) -> # should.equal("TempToken", success) # done()
126885
'use strict' should = require 'should' events = require 'events' Program = require '../src/program' queryString = require 'querystring' q = require 'q' describe 'Program', -> context '#constructor', -> it 'should pass requestorObj to @requestor', -> expectedValue = { } target = new Program(expectedValue) should.strictEqual(target.requestor, expectedValue) it 'should pass userTokenObj to @userToken', -> expectedValue = { } target = new Program({ }, expectedValue) should.strictEqual(target.userToken, expectedValue) context '#go', -> it 'should throw an error if we pass undefined in for path', -> should.throws -> target = new Program() target.request() it 'should throw an error if we pass null in for path', -> should.throws -> target = new Program() target.request(null) it 'should throw an error if we pass something other than a string for path', -> should.throws -> target = new Program() target.request(1) it 'should throw an error if we pass undefined in for ttl', -> should.throws -> target = new Program() target.request("a") it 'should throw an error if we pass null in for ttl', -> should.throws -> target = new Program() target.request("a", null) it 'should throw an error if we pass something other than a string for ttl', -> should.throws -> target = new Program() target.request("a", 1) it 'should throw an error if we pass undefined in for policyCollection', -> should.throws -> target = new Program() target.request("a", "a") it 'should throw an error if we pass null in for policyCollection', -> should.throws -> target = new Program() target.request("a", "a", null) it 'should throw an error if we pass in something other than an array', -> should.throws -> target = new Program() target.request("a", "a", 1) it 'should throw an error if we pass in an array with values that are not strings', -> should.throws -> target = new Program() target.request("a", "a", [ 'a', 1 ]) # This test is failing the build on debian (travis-ci) # #it 'should return temporary token', (done) -> # class RequestorStub # constructor: (requestQueue, optionsQueue) -> # @requestQueue = requestQueue # @optionsQueue = optionsQueue # request: => # q @requestQueue.pop() # createRequestOptions: => # @optionsQueue.pop() # optionsQueue = [ # { }, { }, { } # ] # requestQueue = [ # JSON.stringify({ }), # JSON.stringify({ auth: { client_token: "permToken" } }), # JSON.stringify({ auth: { client_token: "<PASSWORD>" } }) # ] # requestorStub = new RequestorStub(requestQueue, optionsQueue) # target = new Program(requestorStub) # target.go("a", "b", [ "a" ]).done (success) -> # should.equal("TempToken", success) # done()
true
'use strict' should = require 'should' events = require 'events' Program = require '../src/program' queryString = require 'querystring' q = require 'q' describe 'Program', -> context '#constructor', -> it 'should pass requestorObj to @requestor', -> expectedValue = { } target = new Program(expectedValue) should.strictEqual(target.requestor, expectedValue) it 'should pass userTokenObj to @userToken', -> expectedValue = { } target = new Program({ }, expectedValue) should.strictEqual(target.userToken, expectedValue) context '#go', -> it 'should throw an error if we pass undefined in for path', -> should.throws -> target = new Program() target.request() it 'should throw an error if we pass null in for path', -> should.throws -> target = new Program() target.request(null) it 'should throw an error if we pass something other than a string for path', -> should.throws -> target = new Program() target.request(1) it 'should throw an error if we pass undefined in for ttl', -> should.throws -> target = new Program() target.request("a") it 'should throw an error if we pass null in for ttl', -> should.throws -> target = new Program() target.request("a", null) it 'should throw an error if we pass something other than a string for ttl', -> should.throws -> target = new Program() target.request("a", 1) it 'should throw an error if we pass undefined in for policyCollection', -> should.throws -> target = new Program() target.request("a", "a") it 'should throw an error if we pass null in for policyCollection', -> should.throws -> target = new Program() target.request("a", "a", null) it 'should throw an error if we pass in something other than an array', -> should.throws -> target = new Program() target.request("a", "a", 1) it 'should throw an error if we pass in an array with values that are not strings', -> should.throws -> target = new Program() target.request("a", "a", [ 'a', 1 ]) # This test is failing the build on debian (travis-ci) # #it 'should return temporary token', (done) -> # class RequestorStub # constructor: (requestQueue, optionsQueue) -> # @requestQueue = requestQueue # @optionsQueue = optionsQueue # request: => # q @requestQueue.pop() # createRequestOptions: => # @optionsQueue.pop() # optionsQueue = [ # { }, { }, { } # ] # requestQueue = [ # JSON.stringify({ }), # JSON.stringify({ auth: { client_token: "permToken" } }), # JSON.stringify({ auth: { client_token: "PI:PASSWORD:<PASSWORD>END_PI" } }) # ] # requestorStub = new RequestorStub(requestQueue, optionsQueue) # target = new Program(requestorStub) # target.go("a", "b", [ "a" ]).done (success) -> # should.equal("TempToken", success) # done()
[ { "context": "#\n# batman.js\n#\n# Created by Nick Small\n# Copyright 2011, Shopify\n#\n\n# The global namespa", "end": 39, "score": 0.9996547698974609, "start": 29, "tag": "NAME", "value": "Nick Small" }, { "context": "ore', 'after']\n do (k, time) =>\n key = \"#{time}#{helpers.capitalize(k)}\"\n @::[key] = (filter", "end": 71582, "score": 0.9656064510345459, "start": 71572, "tag": "KEY", "value": "\"#{time}#{" }, { "context": " do (k, time) =>\n key = \"#{time}#{helpers.capitalize(k)}\"\n @::[key] = (filter) ->\n @_batman", "end": 71605, "score": 0.8325144052505493, "start": 71590, "tag": "KEY", "value": "capitalize(k)}\"" } ]
src/batman.coffee
nickjs/batman
1
# # batman.js # # Created by Nick Small # Copyright 2011, Shopify # # The global namespace, the `Batman` function will also create also create a new # instance of Batman.Object and mixin all arguments to it. Batman = (mixins...) -> new Batman.Object mixins... # Global Helpers # ------- # `$typeOf` returns a string that contains the built-in class of an object # like `String`, `Array`, or `Object`. Note that only `Object` will be returned for # the entire prototype chain. Batman.typeOf = $typeOf = (object) -> return "Undefined" if typeof object == 'undefined' _objectToString.call(object).slice(8, -1) # Cache this function to skip property lookups. _objectToString = Object.prototype.toString # `$mixin` applies every key from every argument after the first to the # first argument. If a mixin has an `initialize` method, it will be called in # the context of the `to` object, and it's key/values won't be applied. Batman.mixin = $mixin = (to, mixins...) -> hasSet = typeof to.set is 'function' for mixin in mixins continue if $typeOf(mixin) isnt 'Object' for own key, value of mixin continue if key in ['initialize', 'uninitialize', 'prototype'] if hasSet to.set(key, value) else if to.nodeName? Batman.data to, key, value else to[key] = value if typeof mixin.initialize is 'function' mixin.initialize.call to to # `$unmixin` removes every key/value from every argument after the first # from the first argument. If a mixin has a `deinitialize` method, it will be # called in the context of the `from` object and won't be removed. Batman.unmixin = $unmixin = (from, mixins...) -> for mixin in mixins for key of mixin continue if key in ['initialize', 'uninitialize'] delete from[key] if typeof mixin.uninitialize is 'function' mixin.uninitialize.call from from # `$block` takes in a function and returns a function which can either # A) take a callback as its last argument as it would normally, or # B) accept a callback as a second function application. # This is useful so that multiline functions can be passed as callbacks # without the need for wrapping brackets (which a CoffeeScript bug # requires them to have). `$block` also takes an optional function airity # argument as the first argument. If a `length` argument is given, and `length` # or more arguments are passed, `$block` will call the second argument # (the function) with the passed arguments, regardless of their type. # Example: # With a function that accepts a callback as its last argument # # f = (a, b, callback) -> callback(a + b) # ex = $block f # # We can use $block to make it accept the callback in both ways: # # ex(2, 3, (x) -> alert(x)) # alerts 5 # # or # # ex(2, 3) (x) -> alert(x) # Batman._block = $block = (lengthOrFunction, fn) -> if fn? argsLength = lengthOrFunction else fn = lengthOrFunction callbackEater = (args...) -> ctx = @ f = (callback) -> args.push callback fn.apply(ctx, args) # Call the function right now if we've been passed the callback already or if we've reached the argument count threshold if (typeof args[args.length-1] is 'function') || (argsLength && (args.length >= argsLength)) f(args.pop()) else f # `findName` allows an anonymous function to find out what key it resides # in within a context. Batman._findName = $findName = (f, context) -> unless f.displayName for key, value of context if value is f f.displayName = key break f.displayName # `$functionName` returns the name of a given function, if any # Used to deal with functions not having the `name` property in IE Batman._functionName = $functionName = (f) -> return f.__name__ if f.__name__ return f.name if f.name f.toString().match(/\W*function\s+([\w\$]+)\(/)?[1] # `$preventDefault` checks for preventDefault, since it's not # always available across all browsers Batman._preventDefault = $preventDefault = (e) -> if typeof e.preventDefault is "function" then e.preventDefault() else e.returnValue = false Batman._isChildOf = $isChildOf = (parentNode, childNode) -> node = childNode.parentNode while node return true if node == parentNode node = node.parentNode false # Developer Tooling # ----------------- developer = DevelopmentError: (-> DevelopmentError = (@message) -> @name = "DevelopmentError" DevelopmentError:: = Error:: DevelopmentError )() _ie_console: (f, args) -> console?[f] "...#{f} of #{args.length} items..." unless args.length == 1 console?[f] arg for arg in args log: -> return unless console?.log? if console.log.apply then console.log(arguments...) else developer._ie_console "log", arguments warn: -> return unless console?.warn? if console.warn.apply then console.warn(arguments...) else developer._ie_console "warn", arguments error: (message) -> throw new developer.DevelopmentError(message) assert: (result, message) -> developer.error(message) unless result addFilters: -> $mixin Batman.Filters, log: (value, key) -> console?.log? arguments value logStack: (value) -> console?.log? developer.currentFilterStack value logContext: (value) -> console?.log? developer.currentFilterContext value Batman.developer = developer # Helpers # ------- camelize_rx = /(?:^|_|\-)(.)/g capitalize_rx = /(^|\s)([a-z])/g underscore_rx1 = /([A-Z]+)([A-Z][a-z])/g underscore_rx2 = /([a-z\d])([A-Z])/g # Just a few random Rails-style string helpers. You can add more # to the Batman.helpers object. helpers = Batman.helpers = { camelize: (string, firstLetterLower) -> string = string.replace camelize_rx, (str, p1) -> p1.toUpperCase() if firstLetterLower then string.substr(0,1).toLowerCase() + string.substr(1) else string underscore: (string) -> string.replace(underscore_rx1, '$1_$2') .replace(underscore_rx2, '$1_$2') .replace('-', '_').toLowerCase() singularize: (string) -> len = string.length if string.substr(len - 3) is 'ies' string.substr(0, len - 3) + 'y' else if string.substr(len - 1) is 's' string.substr(0, len - 1) else string pluralize: (count, string) -> if string return string if count is 1 else string = count len = string.length lastLetter = string.substr(len - 1) if lastLetter is 'y' "#{string.substr(0, len - 1)}ies" else if lastLetter is 's' string else "#{string}s" capitalize: (string) -> string.replace capitalize_rx, (m,p1,p2) -> p1+p2.toUpperCase() trim: (string) -> if string then string.trim() else "" } # Properties # ---------- class Batman.Property @defaultAccessor: get: (key) -> @[key] set: (key, val) -> @[key] = val unset: (key) -> x = @[key]; delete @[key]; x @triggerTracker: null @forBaseAndKey: (base, key) -> propertyClass = base.propertyClass or Batman.Keypath if base._batman Batman.initializeObject base properties = base._batman.properties ||= new Batman.SimpleHash properties.get(key) or properties.set(key, new propertyClass(base, key)) else new propertyClass(base, key) constructor: (@base, @key) -> @observers = new Batman.SimpleSet @refreshTriggers() if @hasObserversToFire() @_preventCount = 0 isProperty: true isEqual: (other) -> @constructor is other.constructor and @base is other.base and @key is other.key accessor: -> accessors = @base._batman?.get('keyAccessors') if accessors && (val = accessors.get(@key)) return val else @base._batman?.getFirst('defaultAccessor') or Batman.Property.defaultAccessor registerAsTrigger: -> tracker.add @ if tracker = Batman.Property.triggerTracker getValue: -> @registerAsTrigger() @accessor()?.get.call @base, @key setValue: (val) -> @cacheDependentValues() result = @accessor()?.set.call @base, @key, val @fireDependents() result unsetValue: -> @cacheDependentValues() result = @accessor()?.unset.call @base, @key @fireDependents() result cacheDependentValues: -> if @dependents @dependents.forEach (prop) -> prop.cachedValue = prop.getValue() fireDependents: -> if @dependents @dependents.forEach (prop) -> prop.fire(prop.getValue(), prop.cachedValue) if prop.hasObserversToFire?() observe: (fireImmediately..., callback) -> fireImmediately = fireImmediately[0] is true currentValue = @getValue() @observers.add callback @refreshTriggers() callback.call(@base, currentValue, currentValue) if fireImmediately @ hasObserversToFire: -> return true if @observers.length > 0 if @base._batman @base._batman.ancestors().some((ancestor) => ancestor.property?(@key)?.observers?.length > 0) else false prevent: -> @_preventCount++ allow: -> @_preventCount-- if @_preventCount > 0 isAllowedToFire: -> @_preventCount <= 0 fire: (args...) -> return unless @isAllowedToFire() and @hasObserversToFire() key = @key base = @base observerSets = [@observers] @observers.forEach (callback) -> callback?.apply base, args if @base._batman @base._batman.ancestors (ancestor) -> ancestor.property?(key).observers.forEach (callback) -> callback?.apply base, args @refreshTriggers() forget: (observer) -> if observer @observers.remove(observer) else @observers = new Batman.SimpleSet @clearTriggers() unless @hasObserversToFire() refreshTriggers: -> Batman.Property.triggerTracker = new Batman.SimpleSet @getValue() if @triggers @triggers.forEach (property) => unless Batman.Property.triggerTracker.has(property) property.dependents?.remove @ @triggers = Batman.Property.triggerTracker @triggers.forEach (property) => property.dependents ||= new Batman.SimpleSet property.dependents.add @ delete Batman.Property.triggerTracker clearTriggers: -> if @triggers @triggers.forEach (property) => property.dependents.remove @ @triggers = new Batman.SimpleSet # Keypaths # -------- class Batman.Keypath extends Batman.Property constructor: (base, key) -> if $typeOf(key) is 'String' @segments = key.split('.') @depth = @segments.length else @segments = [key] @depth = 1 super slice: (begin, end = @depth) -> base = @base for segment in @segments.slice(0, begin) return unless base? and base = Batman.Property.forBaseAndKey(base, segment).getValue() Batman.Property.forBaseAndKey base, @segments.slice(begin, end).join('.') terminalProperty: -> @slice -1 getValue: -> @registerAsTrigger() if @depth is 1 then super else @terminalProperty()?.getValue() setValue: (val) -> if @depth is 1 then super else @terminalProperty()?.setValue(val) unsetValue: -> if @depth is 1 then super else @terminalProperty()?.unsetValue() # Observable # ---------- # Batman.Observable is a generic mixin that can be applied to any object to allow it to be bound to. # It is applied by default to every instance of `Batman.Object` and subclasses. Batman.Observable = isObservable: true property: (key) -> Batman.initializeObject @ Batman.Property.forBaseAndKey(@, key) get: (key) -> @property(key).getValue() set: (key, val) -> @property(key).setValue(val) unset: (key) -> @property(key).unsetValue() getOrSet: (key, valueFunction) -> currentValue = @get(key) unless currentValue currentValue = valueFunction() @set(key, currentValue) currentValue # `forget` removes an observer from an object. If the callback is passed in, # its removed. If no callback but a key is passed in, all the observers on # that key are removed. If no key is passed in, all observers are removed. forget: (key, observer) -> if key @property(key).forget(observer) else @_batman.properties.forEach (key, property) -> property.forget() @ # `allowed` returns a boolean describing whether or not the key is # currently allowed to fire its observers. allowed: (key) -> @property(key).isAllowedToFire() # `fire` tells any observers attached to a key to fire, manually. # `prevent` stops of a given binding from firing. `prevent` calls can be repeated such that # the same number of calls to allow are needed before observers can be fired. # `allow` unblocks a property for firing observers. Every call to prevent # must have a matching call to allow later if observers are to be fired. # `observe` takes a key and a callback. Whenever the value for that key changes, your # callback will be called in the context of the original object. for k in ['observe', 'prevent', 'allow', 'fire'] do (k) -> Batman.Observable[k] = (key, args...) -> @property(key)[k](args...) @ $get = Batman.get = (object, key) -> if object.get object.get(key) else Batman.Observable.get.call(object, key) # Events # ------ # `Batman.EventEmitter` is another generic mixin that simply allows an object to # emit events. Batman events use observers to manage the callbacks, so they require that # the object emitting the events be observable. If events need to be attached to an object # which isn't a `Batman.Object` or doesn't have the `Batman.Observable` and `Batman.EventEmitter` # mixins applied, the $event function can be used to create ephemeral event objects which # use those mixins internally. Batman.EventEmitter = # An event is a convenient observer wrapper. Any function can be wrapped in an event, and # when called, it will cause it's object to fire all the observers for that event. There is # also some syntactical sugar so observers can be registered simply by calling the event with a # function argument. Notice that the `$block` helper is used here so events can be declared in # class definitions using the second function application syntax and no wrapping brackets. event: $block (key, context, callback) -> if not callback and typeof context isnt 'undefined' callback = context context = null if not callback and $typeOf(key) isnt 'String' callback = key key = null # Return a function which either takes another observer # to register or a value to fire the event with. f = (observer) -> if not @observe developer.error "EventEmitter requires Observable" Batman.initializeObject @ key ||= $findName(f, @) fired = @_batman.oneShotFired?[key] # Pass a function to the event to register it as an observer. if typeof observer is 'function' @observe key, observer observer.apply(@, f._firedArgs) if f.isOneShot and fired # Otherwise, calling the event will cause it to fire. Any # arguments you pass will be passed to your wrapped function. else if @allowed key return false if f.isOneShot and fired value = callback?.apply @, arguments # Observers will only fire if the result of the event is not false. if value isnt false # Get and cache the arguments for the event listeners. Add the value if # its not undefined, and then concat any more arguments passed to this # event when fired. f._firedArgs = unless typeof value is 'undefined' [value].concat arguments... else if arguments.length == 0 [] else Array.prototype.slice.call arguments # Copy the array and add in the key for `fire` args = Array.prototype.slice.call f._firedArgs args.unshift key @fire(args...) if f.isOneShot firings = @_batman.oneShotFired ||= {} firings[key] = yes value else false # This could be its own mixin but is kept here for brevity. f = f.bind(context) if context @[key] = f if key? $mixin f, isEvent: yes action: callback # One shot events can be used for something that only fires once. Any observers # added after it has already fired will simply be executed immediately. This is useful # for things like `ready` events on requests or renders, because once ready they always # remain ready. If an AJAX request had a vanilla `ready` event, observers attached after # the ready event fired the first time would never fire, as they would be waiting for # the next time `ready` would fire as is standard with vanilla events. With a one shot # event, any observers attached after the first fire will fire immediately, meaning no logic eventOneShot: (callback) -> $mixin Batman.EventEmitter.event.apply(@, arguments), isOneShot: yes oneShotFired: @oneShotFired.bind @ oneShotFired: (key) -> Batman.initializeObject @ firings = @_batman.oneShotFired ||= {} !!firings[key] # `$event` lets you create an ephemeral event without needing an EventEmitter. # If you already have an EventEmitter object, you should call .event() on it. Batman.event = $event = (callback) -> context = new Batman.Object context.event('_event', context, callback) # `$eventOneShot` lets you create an ephemeral one-shot event without needing an EventEmitter. # If you already have an EventEmitter object, you should call .eventOneShot() on it. Batman.eventOneShot = $eventOneShot = (callback) -> context = new Batman.Object oneShot = context.eventOneShot('_event', context, callback) oneShot.oneShotFired = -> context.oneShotFired('_event') oneShot # Objects # ------- # `Batman.initializeObject` is called by all the methods in Batman.Object to ensure that the # object's `_batman` property is initialized and it's own. Classes extending Batman.Object inherit # methods like `get`, `set`, and `observe` by default on the class and prototype levels, such that # both instances and the class respond to them and can be bound to. However, CoffeeScript's static # class inheritance copies over all class level properties indiscriminately, so a parent class' # `_batman` object will get copied to its subclasses, transferring all the information stored there and # allowing subclasses to mutate parent state. This method prevents this undesirable behaviour by tracking # which object the `_batman_` object was initialized upon, and reinitializing if that has changed since # initialization. Batman.initializeObject = (object) -> if object._batman? object._batman.check(object) else object._batman = new _Batman(object) # _Batman provides a convienient, parent class and prototype aware place to store hidden # object state. Things like observers, accessors, and states belong in the `_batman` object # attached to every Batman.Object subclass and subclass instance. Batman._Batman = class _Batman constructor: (@object, mixins...) -> $mixin(@, mixins...) if mixins.length > 0 # Used by `Batman.initializeObject` to ensure that this `_batman` was created referencing # the object it is pointing to. check: (object) -> if object != @object object._batman = new _Batman(object) return false return true # `get` is a prototype and class aware property access method. `get` will traverse the prototype chain, asking # for the passed key at each step, and then attempting to merge the results into one object. # It can only do this if at each level an `Array`, `Hash`, or `Set` is found, so try to use # those if you need `_batman` inhertiance. get: (key) -> # Get all the keys from the ancestor chain results = @getAll(key) switch results.length when 0 undefined when 1 results[0] else # And then try to merge them if there is more than one. Use `concat` on arrays, and `merge` on # sets and hashes. if results[0].concat? results = results.reduceRight (a, b) -> a.concat(b) else if results[0].merge? results = results.reduceRight (a, b) -> a.merge(b) results # `getFirst` is a prototype and class aware property access method. `getFirst` traverses the prototype chain, # and returns the value of the first `_batman` object which defines the passed key. Useful for # times when the merged value doesn't make sense or the value is a primitive. getFirst: (key) -> results = @getAll(key) results[0] # `getAll` is a prototype and class chain iterator. When passed a key or function, it applies it to each # parent class or parent prototype, and returns the undefined values, closest ancestor first. getAll: (keyOrGetter) -> # Get a function which pulls out the key from the ancestor's `_batman` or use the passed function. if typeof keyOrGetter is 'function' getter = keyOrGetter else getter = (ancestor) -> ancestor._batman?[keyOrGetter] # Apply it to all the ancestors, and then this `_batman`'s object. results = @ancestors(getter) if val = getter(@object) results.unshift val results # `ancestors` traverses the prototype or class chain and returns the application of a function to each # object in the chain. `ancestors` does this _only_ to the `@object`'s ancestors, and not the `@object` # itsself. ancestors: (getter = (x) -> x) -> results = [] # Decide if the object is a class or not, and pull out the first ancestor isClass = !!@object.prototype parent = if isClass @object.__super__?.constructor else if (proto = Object.getPrototypeOf(@object)) == @object @object.constructor.__super__ else proto if parent? # Apply the function and store the result if it isn't undefined. val = getter(parent) results.push(val) if val? # Use a recursive call to `_batman.ancestors` on the ancestor, which will take the next step up the chain. results = results.concat(parent._batman.ancestors(getter)) if parent._batman? results set: (key, value) -> @[key] = value # `Batman.Object` is the base class for all other Batman objects. It is not abstract. class BatmanObject # Setting `isGlobal` to true will cause the class name to be defined on the # global object. For example, Batman.Model will be aliased to window.Model. # This should be used sparingly; it's mostly useful for debugging. @global: (isGlobal) -> return if isGlobal is false container[$functionName(@)] = @ # Apply mixins to this class. @classMixin: -> $mixin @, arguments... # Apply mixins to instances of this class. @mixin: -> @classMixin.apply @prototype, arguments mixin: @classMixin # Accessor implementation. Accessors are used to create properties on a class or prototype which can be fetched # with get, but are computed instead of just stored. This is a batman and old browser friendly version of # `defineProperty` without as much goodness. # # Accessors track which other properties they rely on for computation, and when those other properties change, # an accessor will recalculate its value and notifiy its observers. This way, when a source value is changed, # any dependent accessors will automatically update any bindings to them with a new value. Accessors accomplish # this feat by tracking `get` calls, do be sure to use `get` to retrieve properties inside accessors. # # `@accessor` or `@classAccessor` can be called with zero, one, or many keys to attach the accessor to. This # has the following effects: # # * zero: create a `defaultAccessor`, which will be called when no other properties or accessors on an object # match a keypath. This is similar to `method_missing` in Ruby or `#doesNotUnderstand` in Smalltalk. # * one: create a `keyAccessor` at the given key, which will only be called when that key is `get`ed. # * many: create `keyAccessors` for each given key, which will then be called whenever each key is `get`ed. # # Note: This function gets called in all sorts of different contexts by various # other pointers to it, but it acts the same way on `this` in all cases. getAccessorObject = (accessor) -> accessor = {get: accessor} if !accessor.get && !accessor.set && !accessor.unset accessor @classAccessor: (keys..., accessor) -> Batman.initializeObject @ # Create a default accessor if no keys have been given. if keys.length is 0 # The `accessor` argument is wrapped in `getAccessorObject` which allows functions to be passed in # as a shortcut to {get: function} @_batman.defaultAccessor = getAccessorObject(accessor) else # Otherwise, add key accessors for each key given. @_batman.keyAccessors ||= new Batman.SimpleHash @_batman.keyAccessors.set(key, getAccessorObject(accessor)) for key in keys # Support adding accessors to the prototype from within class defintions or after the class has been created # with `KlassExtendingBatmanObject.accessor(keys..., accessorObject)` @accessor: -> @classAccessor.apply @prototype, arguments # Support adding accessors to instances after creation accessor: @classAccessor constructor: (mixins...) -> @_batman = new _Batman(@) @mixin mixins... # Make every subclass and their instances observable. @classMixin Batman.Observable, Batman.EventEmitter @mixin Batman.Observable, Batman.EventEmitter # Observe this property on every instance of this class. @observeAll: -> @::observe.apply @prototype, arguments @singleton: (singletonMethodName="sharedInstance") -> @classAccessor singletonMethodName, get: -> @["_#{singletonMethodName}"] ||= new @ Batman.Object = BatmanObject class Batman.Accessible extends Batman.Object constructor: -> @accessor.apply(@, arguments) # Collections Batman.Enumerable = isEnumerable: true map: (f, ctx = container) -> r = []; @forEach(-> r.push f.apply(ctx, arguments)); r every: (f, ctx = container) -> r = true; @forEach(-> r = r && f.apply(ctx, arguments)); r some: (f, ctx = container) -> r = false; @forEach(-> r = r || f.apply(ctx, arguments)); r reduce: (f, r) -> count = 0 self = @ @forEach -> if r? then r = f(r, arguments..., count, self) else r = arguments[0] r filter: (f) -> r = new @constructor if r.add wrap = (r, e) -> r.add(e) if f(e); r else if r.set wrap = (r, k, v) -> r.set(k, v) if f(k, v); r else r = [] unless r.push wrap = (r, e) -> r.push(e) if f(e); r @reduce wrap, r # Provide this simple mixin ability so that during bootstrapping we don't have to use `$mixin`. `$mixin` # will correctly attempt to use `set` on the mixinee, which ends up requiring the definition of # `SimpleSet` to be complete during its definition. $extendsEnumerable = (onto) -> onto[k] = v for k,v of Batman.Enumerable class Batman.SimpleHash constructor: -> @_storage = {} @length = 0 $extendsEnumerable(@::) propertyClass: Batman.Property hasKey: (key) -> if pairs = @_storage[key] for pair in pairs return true if @equality(pair[0], key) return false get: (key) -> if pairs = @_storage[key] for pair in pairs return pair[1] if @equality(pair[0], key) set: (key, val) -> pairs = @_storage[key] ||= [] for pair in pairs if @equality(pair[0], key) return pair[1] = val @length++ pairs.push([key, val]) val unset: (key) -> if pairs = @_storage[key] for [obj,value], index in pairs if @equality(obj, key) pairs.splice(index,1) @length-- return getOrSet: Batman.Observable.getOrSet equality: (lhs, rhs) -> return true if lhs is rhs return true if lhs isnt lhs and rhs isnt rhs # when both are NaN return true if lhs?.isEqual?(rhs) and rhs?.isEqual?(lhs) return false forEach: (iterator) -> for key, values of @_storage iterator(obj, value) for [obj, value] in values keys: -> result = [] # Explicitly reference this foreach so that if it's overriden in subclasses the new implementation isn't used. Batman.SimpleHash::forEach.call @, (obj) -> result.push obj result clear: -> @_storage = {} @length = 0 isEmpty: -> @length is 0 merge: (others...) -> merged = new @constructor others.unshift(@) for hash in others hash.forEach (obj, value) -> merged.set obj, value merged class Batman.Hash extends Batman.Object constructor: -> Batman.SimpleHash.apply(@, arguments) # Add a meta object to all hashes which we can then use in the `meta` filter to allow binding # to hash meta-properties without reserving keys. @meta = new Batman.Object(length: 0) self = this @meta.accessor 'isEmpty', -> self.isEmpty() @meta.accessor 'keys', -> self.keys() super $extendsEnumerable(@::) propertyClass: Batman.Property @accessor get: Batman.SimpleHash::get set: -> results = Batman.SimpleHash::set.apply(@, arguments) @meta.set('length', @length) results unset: -> results = Batman.SimpleHash::unset.apply(@, arguments) @meta.set('length', @length) results for k in ['hasKey', 'equality', 'forEach', 'keys', 'isEmpty', 'merge'] @::[k] = Batman.SimpleHash::[k] clear: -> results = Batman.SimpleHash::clear.apply(@, arguments) @meta.set('length', @length) results class Batman.SimpleSet constructor: -> @_storage = new Batman.SimpleHash @_indexes = new Batman.SimpleHash @_sorts = new Batman.SimpleHash @length = 0 @add.apply @, arguments if arguments.length > 0 $extendsEnumerable(@::) has: (item) -> @_storage.hasKey item add: (items...) -> addedItems = [] for item in items unless @_storage.hasKey(item) @_storage.set item, true addedItems.push item @length++ @itemsWereAdded(addedItems...) unless addedItems.length is 0 addedItems remove: (items...) -> removedItems = [] for item in items if @_storage.hasKey(item) @_storage.unset item removedItems.push item @length-- @itemsWereRemoved(removedItems...) unless removedItems.length is 0 removedItems forEach: (iterator) -> @_storage.forEach (key, value) -> iterator(key) isEmpty: -> @length is 0 clear: -> items = @toArray() @_storage = new Batman.SimpleHash @length = 0 @itemsWereRemoved(items...) items toArray: -> @_storage.keys() merge: (others...) -> merged = new @constructor others.unshift(@) for set in others set.forEach (v) -> merged.add v merged indexedBy: (key) -> @_indexes.get(key) or @_indexes.set(key, new Batman.SetIndex(@, key)) sortedBy: (key) -> @_sorts.get(key) or @_sorts.set(key, new Batman.SetSort(@, key)) itemsWereAdded: -> itemsWereRemoved: -> class Batman.Set extends Batman.Object constructor: -> Batman.SimpleSet.apply @, arguments @set 'length', 0 $extendsEnumerable(@::) itemsWereAdded: @event -> itemsWereRemoved: @event -> for k in ['has', 'forEach', 'isEmpty', 'toArray', 'indexedBy', 'sortedBy'] @::[k] = Batman.SimpleSet::[k] for k in ['add', 'remove', 'clear', 'merge'] do (k) => @::[k] = -> oldLength = @length @prevent 'length' results = Batman.SimpleSet::[k].apply(@, arguments) [newLength, @length] = [@length, oldLength] @allow 'length' @set 'length', newLength if newLength != oldLength results @accessor 'indexedBy', -> new Batman.Accessible (key) => @indexedBy(key) @accessor 'sortedBy', -> new Batman.Accessible (key) => @sortedBy(key) @accessor 'isEmpty', -> @isEmpty() class Batman.SetObserver extends Batman.Object constructor: (@base) -> @_itemObservers = new Batman.Hash @_setObservers = new Batman.Hash @_setObservers.set("itemsWereAdded", @itemsWereAdded.bind(@)) @_setObservers.set("itemsWereRemoved", @itemsWereRemoved.bind(@)) @observe 'itemsWereAdded', @startObservingItems.bind(@) @observe 'itemsWereRemoved', @stopObservingItems.bind(@) itemsWereAdded: @event -> itemsWereRemoved: @event -> observedItemKeys: [] observerForItemAndKey: (item, key) -> _getOrSetObserverForItemAndKey: (item, key) -> @_itemObservers.getOrSet item, => observersByKey = new Batman.Hash observersByKey.getOrSet key, => @observerForItemAndKey(item, key) startObserving: -> @_manageItemObservers("observe") @_manageSetObservers("observe") stopObserving: -> @_manageItemObservers("forget") @_manageSetObservers("forget") startObservingItems: (items...) -> @_manageObserversForItem(item, "observe") for item in items stopObservingItems: (items...) -> @_manageObserversForItem(item, "forget") for item in items _manageObserversForItem: (item, method) -> return unless item.isObservable for key in @observedItemKeys item[method] key, @_getOrSetObserverForItemAndKey(item, key) @_itemObservers.unset(item) if method is "forget" _manageItemObservers: (method) -> @base.forEach (item) => @_manageObserversForItem(item, method) _manageSetObservers: (method) -> return unless @base.isObservable @_setObservers.forEach (key, observer) => @base[method](key, observer) class Batman.SetSort extends Batman.Object constructor: (@base, @key) -> if @base.isObservable @_setObserver = new Batman.SetObserver(@base) @_setObserver.observedItemKeys = [@key] boundReIndex = @_reIndex.bind(@) @_setObserver.observerForItemAndKey = -> boundReIndex @_setObserver.observe 'itemsWereAdded', boundReIndex @_setObserver.observe 'itemsWereRemoved', boundReIndex @startObserving() @_reIndex() startObserving: -> @_setObserver?.startObserving() stopObserving: -> @_setObserver?.stopObserving() toArray: -> @get('_storage') @accessor 'toArray', @::toArray forEach: (iterator) -> iterator(e,i) for e,i in @get('_storage') compare: (a,b) -> return 0 if a is b return 1 if a is undefined return -1 if b is undefined return 1 if a is null return -1 if b is null return 0 if a.isEqual?(b) and b.isEqual?(a) typeComparison = Batman.SetSort::compare($typeOf(a), $typeOf(b)) return typeComparison if typeComparison isnt 0 return 1 if a isnt a # means a is NaN return -1 if b isnt b # means b is NaN return 1 if a > b return -1 if a < b return 0 _reIndex: -> newOrder = @base.toArray().sort (a,b) => valueA = Batman.Observable.property.call(a, @key).getValue() valueA = valueA.valueOf() if valueA? valueB = Batman.Observable.property.call(b, @key).getValue() valueB = valueB.valueOf() if valueB? @compare.call(@, valueA, valueB) @_setObserver?.startObservingItems(newOrder...) @set('_storage', newOrder) class Batman.SetIndex extends Batman.Object constructor: (@base, @key) -> @_storage = new Batman.Hash if @base.isObservable @_setObserver = new Batman.SetObserver(@base) @_setObserver.observedItemKeys = [@key] @_setObserver.observerForItemAndKey = @observerForItemAndKey.bind(@) @_setObserver.observe 'itemsWereAdded', (items...) => @_addItem(item) for item in items @_setObserver.observe 'itemsWereRemoved', (items...) => @_removeItem(item) for item in items @base.forEach @_addItem.bind(@) @startObserving() @accessor (key) -> @_resultSetForKey(key) startObserving: ->@_setObserver?.startObserving() stopObserving: -> @_setObserver?.stopObserving() observerForItemAndKey: (item, key) -> (newValue, oldValue) => @_removeItemFromKey(item, oldValue) @_addItemToKey(item, newValue) _addItem: (item) -> @_addItemToKey(item, @_keyForItem(item)) _addItemToKey: (item, key) -> @_resultSetForKey(key).add item _removeItem: (item) -> @_removeItemFromKey(item, @_keyForItem(item)) _removeItemFromKey: (item, key) -> @_resultSetForKey(key).remove item _resultSetForKey: (key) -> @_storage.getOrSet(key, -> new Batman.Set) _keyForItem: (item) -> Batman.Keypath.forBaseAndKey(item, @key).getValue() class Batman.UniqueSetIndex extends Batman.SetIndex constructor: -> @_uniqueIndex = new Batman.Hash super @accessor (key) -> @_uniqueIndex.get(key) _addItemToKey: (item, key) -> @_resultSetForKey(key).add item unless @_uniqueIndex.hasKey(key) @_uniqueIndex.set(key, item) _removeItemFromKey: (item, key) -> resultSet = @_resultSetForKey(key) resultSet.remove item if resultSet.length is 0 @_uniqueIndex.unset(key) else @_uniqueIndex.set(key, resultSet.toArray()[0]) class Batman.SortableSet extends Batman.Set constructor: -> super @_sortIndexes = {} @observe 'activeIndex', => @setWasSorted(@) setWasSorted: @event -> return false if @length is 0 for k in ['add', 'remove', 'clear'] do (k) => @::[k] = -> results = Batman.Set::[k].apply(@, arguments) @_reIndex() results addIndex: (index) -> @_reIndex(index) removeIndex: (index) -> @_sortIndexes[index] = null delete @_sortIndexes[index] @unset('activeIndex') if @activeIndex is index index forEach: (iterator) -> iterator(el) for el in @toArray() sortBy: (index) -> @addIndex(index) unless @_sortIndexes[index] @set('activeIndex', index) unless @activeIndex is index @ isSorted: -> @_sortIndexes[@get('activeIndex')]? toArray: -> @_sortIndexes[@get('activeIndex')] || super _reIndex: (index) -> if index [keypath, ordering] = index.split ' ' ary = Batman.Set.prototype.toArray.call @ @_sortIndexes[index] = ary.sort (a,b) -> valueA = (Batman.Observable.property.call(a, keypath)).getValue()?.valueOf() valueB = (Batman.Observable.property.call(b, keypath)).getValue()?.valueOf() [valueA, valueB] = [valueB, valueA] if ordering?.toLowerCase() is 'desc' if valueA < valueB then -1 else if valueA > valueB then 1 else 0 @setWasSorted(@) if @activeIndex is index else @_reIndex(index) for index of @_sortIndexes @setWasSorted(@) @ # State Machines # -------------- Batman.StateMachine = { initialize: -> Batman.initializeObject @ if not @_batman.states @_batman.states = new Batman.SimpleHash state: (name, callback) -> Batman.StateMachine.initialize.call @ if not name return @_batman.getFirst 'state' developer.assert @event, "StateMachine requires EventEmitter" event = @[name] || @event name, -> _stateMachine_setState.call(@, name); false event.call(@, callback) if typeof callback is 'function' event transition: (from, to, callback) -> Batman.StateMachine.initialize.call @ @state from @state to name = "#{from}->#{to}" transitions = @_batman.states event = transitions.get(name) || transitions.set(name, $event ->) event(callback) if callback event } # A special method to alias state machine methods to class methods Batman.Object.actsAsStateMachine = (includeInstanceMethods=true) -> Batman.StateMachine.initialize.call @ Batman.StateMachine.initialize.call @prototype @classState = -> Batman.StateMachine.state.apply @, arguments @state = -> @classState.apply @prototype, arguments @::state = @classState if includeInstanceMethods @classTransition = -> Batman.StateMachine.transition.apply @, arguments @transition = -> @classTransition.apply @prototype, arguments @::transition = @classTransition if includeInstanceMethods # This is cached here so it doesn't need to be recompiled for every setter _stateMachine_setState = (newState) -> Batman.StateMachine.initialize.call @ if @_batman.isTransitioning (@_batman.nextState ||= []).push(newState) return false @_batman.isTransitioning = yes oldState = @state() @_batman.state = newState if newState and oldState name = "#{oldState}->#{newState}" for event in @_batman.getAll((ancestor) -> ancestor._batman?.get('states')?.get(name)) if event event newState, oldState if newState @fire newState, newState, oldState @_batman.isTransitioning = no @[@_batman.nextState.shift()]() if @_batman.nextState?.length newState # App, Requests, and Routing # -------------------------- # `Batman.Request` is a normalizer for XHR requests in the Batman world. class Batman.Request extends Batman.Object @objectToFormData: (data) -> pairForList = (key, object, first = false) -> list = switch Batman.typeOf(object) when 'Object' list = for k, v of object pairForList((if first then k else "#{key}[#{k}]"), v) list.reduce((acc, list) -> acc.concat list , []) when 'Array' object.reduce((acc, element) -> acc.concat pairForList("#{key}[]", element) , []) else [[key, object]] formData = new FormData() for [key, val] in pairForList("", data, true) formData.append(key, val) formData url: '' data: '' method: 'get' formData: false response: null status: null # Set the content type explicitly for PUT and POST requests. contentType: 'application/x-www-form-urlencoded' # After the URL gets set, we'll try to automatically send # your request after a short period. If this behavior is # not desired, use @cancel() after setting the URL. @observeAll 'url', -> @_autosendTimeout = setTimeout (=> @send()), 0 loading: @event -> loaded: @event -> success: @event -> error: @event -> # `send` is implmented in the platform layer files. One of those must be required for # `Batman.Request` to be useful. send: () -> developer.error "Please source a dependency file for a request implementation" cancel: -> clearTimeout(@_autosendTimeout) if @_autosendTimeout # `Batman.App` manages requiring files and acts as a namespace for all code subclassing # Batman objects. class Batman.App extends Batman.Object # Require path tells the require methods which base directory to look in. @requirePath: '' # The require class methods (`controller`, `model`, `view`) simply tells # your app where to look for coffeescript source files. This # implementation may change in the future. @require: (path, names...) -> base = @requirePath + path for name in names @prevent 'run' path = base + '/' + name + '.coffee' # FIXME: don't hardcode this new Batman.Request url: path type: 'html' success: (response) => CoffeeScript.eval response # FIXME: under no circumstances should we be compiling coffee in # the browser. This can be fixed via a real deployment solution # to compile coffeescripts, such as Sprockets. @allow 'run' @run() # FIXME: this should only happen if the client actually called run. @ @controller: (names...) -> names = names.map (n) -> n + '_controller' @require 'controllers', names... @model: -> @require 'models', arguments... @view: -> @require 'views', arguments... # Layout is the base view that other views can be yielded into. The # default behavior is that when `app.run()` is called, a new view will # be created for the layout using the `document` node as its content. # Use `MyApp.layout = null` to turn off the default behavior. @layout: undefined # Call `MyApp.run()` to start up an app. Batman level initializers will # be run to bootstrap the application. @run: @eventOneShot -> if Batman.currentApp return if Batman.currentApp is @ Batman.currentApp.stop() return false if @hasRun Batman.currentApp = @ if typeof @dispatcher is 'undefined' @dispatcher ||= new Batman.Dispatcher @ if typeof @layout is 'undefined' @set 'layout', new Batman.View contexts: [@] node: document @get('layout').ready => @ready() if typeof @historyManager is 'undefined' and @dispatcher.routeMap @historyManager = Batman.historyManager = new Batman.HashHistory @ @historyManager.start() @hasRun = yes @ # The `MyApp.ready` event will fire once the app's layout view has finished rendering. This includes # partials, loops, and all the other deferred renders, but excludes data fetching. @ready: @eventOneShot -> true @stop: @eventOneShot -> @historyManager?.stop() Batman.historyManager = null @hasRun = no @ # Dispatcher # ---------- class Batman.Route extends Batman.Object # Route regexes courtesy of Backbone namedParam = /:([\w\d]+)/g splatParam = /\*([\w\d]+)/g queryParam = '(?:\\?.+)?' namedOrSplat = /[:|\*]([\w\d]+)/g escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g constructor: -> super @pattern = @url.replace(escapeRegExp, '\\$&') @regexp = new RegExp('^' + @pattern.replace(namedParam, '([^\/]*)').replace(splatParam, '(.*?)') + queryParam + '$') @namedArguments = [] while (array = namedOrSplat.exec(@pattern))? @namedArguments.push(array[1]) if array[1] @accessor 'action', get: -> return @action if @action if @options result = $mixin {}, @options if signature = result.signature components = signature.split('#') result.controller = components[0] result.action = components[1] || 'index' result.target = @dispatcher.get result.controller @set 'action', result set: (key, action) -> @action = action parameterize: (url) -> [url, query] = url.split '?' array = @regexp.exec(url)?.slice(1) params = url: url action = @get 'action' if typeof action is 'function' params.action = action else $mixin params, action if array for param, index in array params[@namedArguments[index]] = param if query for s in query.split '&' [key, value] = s.split '=' params[key] = value params dispatch: (url) -> if $typeOf(url) is 'String' params = @parameterize url $redirect('/404') if not (action = params.action) and url isnt '/404' return action(params) if typeof action is 'function' return params.target.dispatch(action, params) if params.target?.dispatch return params.target?[action](params) class Batman.Dispatcher extends Batman.Object constructor: (@app) -> @app.route @ @app.controllers = new Batman.Object for key, controller of @app continue unless controller?.prototype instanceof Batman.Controller @prepareController controller prepareController: (controller) -> name = helpers.underscore($functionName(controller).replace('Controller', '')) return unless name getter = -> @[name] = controller.get 'sharedController' @accessor name, getter @app.controllers.accessor name, getter register: (url, options) -> url = "/#{url}" if url.indexOf('/') isnt 0 route = if $typeOf(options) is 'Function' new Batman.Route url: url, action: options, dispatcher: @ else new Batman.Route url: url, options: options, dispatcher: @ @routeMap ||= {} @routeMap[url] = route findRoute: (url) -> url = "/#{url}" if url.indexOf('/') isnt 0 return route if (route = @routeMap[url]) for routeUrl, route of @routeMap return route if route.regexp.test(url) findUrl: (params) -> for url, route of @routeMap matches = no options = route.options if params.resource matches = options.resource is params.resource and options.action is params.action else action = route.get 'action' continue if typeof action is 'function' {controller, action} = action if controller is params.controller and action is (params.action || 'index') matches = yes continue if not matches for key, value of params url = url.replace new RegExp('[:|\*]' + key), value return url dispatch: (url) -> route = @findRoute(url) if route route.dispatch(url) else if url isnt '/404' $redirect('/404') @app.set 'currentURL', url # History Manager # --------------- class Batman.HistoryManager constructor: (@app) -> dispatch: (url) -> url = "/#{url}" if url.indexOf('/') isnt 0 @app.dispatcher.dispatch url url redirect: (url) -> if $typeOf(url) isnt 'String' url = @app.dispatcher.findUrl(url) @dispatch url class Batman.HashHistory extends Batman.HistoryManager HASH_PREFIX: '#!' start: => return if typeof window is 'undefined' return if @started @started = yes if 'onhashchange' of window $addEventListener window, 'hashchange', @parseHash else @interval = setInterval @parseHash, 100 @first = true Batman.currentApp.prevent 'ready' setTimeout @parseHash, 0 stop: => if @interval @interval = clearInterval @interval else $removeEventListener window, 'hashchange', @parseHash @started = no urlFor: (url) -> @HASH_PREFIX + url parseHash: => hash = window.location.hash.replace @HASH_PREFIX, '' return if hash is @cachedHash result = @dispatch (@cachedHash = hash) if @first Batman.currentApp.allow 'ready' Batman.currentApp.fire 'ready' @first = false result redirect: (params) -> url = super @cachedHash = url window.location.hash = @HASH_PREFIX + url Batman.redirect = $redirect = (url) -> Batman.historyManager?.redirect url # Route Declarators # ----------------- Batman.App.classMixin route: (url, signature, options={}) -> return if not url if url instanceof Batman.Dispatcher dispatcher = url for key, value of @_dispatcherCache dispatcher.register key, value @_dispatcherCache = null return dispatcher if $typeOf(signature) is 'String' options.signature = signature else if $typeOf(signature) is 'Function' options = signature else if signature $mixin options, signature @_dispatcherCache ||= {} @_dispatcherCache[url] = options root: (signature, options) -> @route '/', signature, options resources: (resource, options={}, callback) -> (callback = options; options = {}) if typeof options is 'function' resource = helpers.pluralize(resource) controller = options.controller || resource @route(resource, "#{controller}#index", resource: controller, action: 'index') unless options.index is false @route("#{resource}/new", "#{controller}#new", resource: controller, action: 'new') unless options.new is false @route("#{resource}/:id", "#{controller}#show", resource: controller, action: 'show') unless options.show is false @route("#{resource}/:id/edit", "#{controller}#edit", resource: controller, action: 'edit') unless options.edit is false if callback app = @ ops = collection: (collectionCallback) -> collectionCallback?.call route: (url, methodName) -> app.route "#{resource}/#{url}", "#{controller}##{methodName || url}" member: (memberCallback) -> memberCallback?.call route: (url, methodName) -> app.route "#{resource}/:id/#{url}", "#{controller}##{methodName || url}" callback.call ops redirect: $redirect # Controllers # ----------- class Batman.Controller extends Batman.Object @singleton 'sharedController' @beforeFilter: (nameOrFunction) -> Batman.initializeObject @ filters = @_batman.beforeFilters ||= [] filters.push(nameOrFunction) if filters.indexOf(nameOrFunction) is -1 @accessor 'controllerName', get: -> @_controllerName ||= helpers.underscore($functionName(@constructor).replace('Controller', '')) @afterFilter: (nameOrFunction) -> Batman.initializeObject @ filters = @_batman.afterFilters ||= [] filters.push(nameOrFunction) if filters.indexOf(nameOrFunction) is -1 @accessor 'action', get: -> @_currentAction set: (key, value) -> @_currentAction = value # You shouldn't call this method directly. It will be called by the dispatcher when a route is called. # If you need to call a route manually, use `$redirect()`. dispatch: (action, params = {}) -> params.controller ||= @get 'controllerName' params.action ||= action params.target ||= @ oldRedirect = Batman.historyManager?.redirect Batman.historyManager?.redirect = @redirect @_actedDuringAction = no @set 'action', action if filters = @constructor._batman?.get('beforeFilters') for filter in filters if typeof filter is 'function' then filter.call(@, params) else @[filter](params) developer.assert @[action], "Error! Controller action #{@get 'controllerName'}.#{action} couldn't be found!" @[action](params) if not @_actedDuringAction @render() if filters = @constructor._batman?.get('afterFilters') for filter in filters if typeof filter is 'function' then filter.call(@, params) else @[filter](params) delete @_actedDuringAction @set 'action', null Batman.historyManager?.redirect = oldRedirect redirectTo = @_afterFilterRedirect delete @_afterFilterRedirect $redirect(redirectTo) if redirectTo redirect: (url) => throw 'DoubleRedirectError' if @_actedDuringAction if @get 'action' @_actedDuringAction = yes @_afterFilterRedirect = url else if $typeOf(url) is 'Object' url.controller = @ if not url.controller $redirect url render: (options = {}) -> throw 'DoubleRenderError' if @_actedDuringAction @_actedDuringAction = yes return if options is false if not options.view options.source ||= helpers.underscore($functionName(@constructor).replace('Controller', '')) + '/' + @_currentAction + '.html' options.view = new Batman.View(options) if view = options.view Batman.currentApp?.prevent 'ready' view.contexts.push @ view.ready -> Batman.DOM.contentFor('main', view.get('node')) Batman.currentApp?.allow 'ready' Batman.currentApp?.fire 'ready' view # Models # ------ class Batman.Model extends Batman.Object # ## Model API # Override this property if your model is indexed by a key other than `id` @primaryKey: 'id' # Override this property to define the key which storage adapters will use to store instances of this model under. # - For RestStorage, this ends up being part of the url built to store this model # - For LocalStorage, this ends up being the namespace in localStorage in which JSON is stored @storageKey: null # Pick one or many mechanisms with which this model should be persisted. The mechanisms # can be already instantiated or just the class defining them. @persist: (mechanisms...) -> Batman.initializeObject @prototype storage = @::_batman.storage ||= [] results = for mechanism in mechanisms mechanism = if mechanism.isStorageAdapter then mechanism else new mechanism(@) storage.push mechanism mechanism if results.length > 1 results else results[0] # Encoders are the tiny bits of logic which manage marshalling Batman models to and from their # storage representations. Encoders do things like stringifying dates and parsing them back out again, # pulling out nested model collections and instantiating them (and JSON.stringifying them back again), # and marshalling otherwise un-storable object. @encode: (keys..., encoderOrLastKey) -> Batman.initializeObject @prototype @::_batman.encoders ||= new Batman.SimpleHash @::_batman.decoders ||= new Batman.SimpleHash switch $typeOf(encoderOrLastKey) when 'String' keys.push encoderOrLastKey when 'Function' encoder = encoderOrLastKey else encoder = encoderOrLastKey.encode decoder = encoderOrLastKey.decode encoder = @defaultEncoder.encode if typeof encoder is 'undefined' decoder = @defaultEncoder.decode if typeof decoder is 'undefined' for key in keys @::_batman.encoders.set(key, encoder) if encoder @::_batman.decoders.set(key, decoder) if decoder # Set up the unit functions as the default for both @defaultEncoder: encode: (x) -> x decode: (x) -> x # Attach encoders and decoders for the primary key, and update them if the primary key changes. @observe 'primaryKey', yes, (newPrimaryKey) -> @encode newPrimaryKey, {encode: false, decode: @defaultEncoder.decode} # Validations allow a model to be marked as 'valid' or 'invalid' based on a set of programmatic rules. # By validating our data before it gets to the server we can provide immediate feedback to the user about # what they have entered and forgo waiting on a round trip to the server. # `validate` allows the attachment of validations to the model on particular keys, where the validation is # either a built in one (by use of options to pass to them) or a custom one (by use of a custom function as # the second argument). Custom validators should have the signature `(errors, record, key, callback)`. They # should add strings to the `errors` set based on the record (maybe depending on the `key` they were attached # to) and then always call the callback. Again: the callback must always be called. @validate: (keys..., optionsOrFunction) -> Batman.initializeObject @prototype validators = @::_batman.validators ||= [] if typeof optionsOrFunction is 'function' # Given a function, use that as the actual validator, expecting it to conform to the API # the built in validators do. validators.push keys: keys callback: optionsOrFunction else # Given options, find the validations which match the given options, and add them to the validators # array. options = optionsOrFunction for validator in Validators if (matches = validator.matches(options)) delete options[match] for match in matches validators.push keys: keys validator: new validator(matches) # ### Query methods @classAccessor 'all', get: -> @load() if @::hasStorage() and @classState() not in ['loaded', 'loading'] @get('loaded') set: (k, v) -> @set('loaded', v) @classAccessor 'loaded', get: -> unless @all @all = new Batman.SortableSet @all.sortBy "id asc" @all set: (k, v) -> @all = v @classAccessor 'first', -> @get('all').toArray()[0] @classAccessor 'last', -> x = @get('all').toArray(); x[x.length - 1] @find: (id, callback) -> developer.assert callback, "Must call find with a callback!" record = new @(id) newRecord = @_mapIdentity(record) newRecord.load callback return newRecord # `load` fetches records from all sources possible @load: (options, callback) -> if $typeOf(options) is 'Function' callback = options options = {} developer.assert @::_batman.getAll('storage').length, "Can't load model #{$functionName(@)} without any storage adapters!" do @loading @::_doStorageOperation 'readAll', options, (err, records) => if err? callback?(err, []) else mappedRecords = (@_mapIdentity(record) for record in records) do @loaded callback?(err, mappedRecords) # `create` takes an attributes hash, creates a record from it, and saves it given the callback. @create: (attrs, callback) -> if !callback [attrs, callback] = [{}, attrs] obj = new this(attrs) obj.save(callback) obj # `findOrCreate` takes an attributes hash, optionally containing a primary key, and returns to you a saved record # representing those attributes, either from the server or from the identity map. @findOrCreate: (attrs, callback) -> record = new this(attrs) if record.isNew() record.save(callback) else foundRecord = @_mapIdentity(record) foundRecord.updateAttributes(attrs) callback(undefined, foundRecord) @_mapIdentity: (record) -> if typeof (id = record.get('id')) == 'undefined' || id == '' return record else existing = @get("loaded.indexedBy.id").get(id)?.toArray()[0] if existing existing.updateAttributes(record._batman.attributes || {}) return existing else @get('loaded').add(record) return record # ### Record API # Add a universally accessible accessor for retrieving the primrary key, regardless of which key its stored under. @accessor 'id', get: -> pk = @constructor.get('primaryKey') if pk == 'id' @id else @get(pk) set: (k, v) -> pk = @constructor.get('primaryKey') if pk == 'id' @id = v else @set(pk, v) # Add normal accessors for the dirty keys and errors attributes of a record, so these accesses don't fall to the # default accessor. @accessor 'dirtyKeys', 'errors', Batman.Property.defaultAccessor # Add an accessor for the internal batman state under `batmanState`, so that the `state` key can be a valid # attribute. @accessor 'batmanState' get: -> @state() set: (k, v) -> @state(v) # Add a default accessor to make models store their attributes under a namespace by default. @accessor get: (k) -> (@_batman.attributes ||= {})[k] || @[k] set: (k, v) -> (@_batman.attributes ||= {})[k] = v unset: (k) -> x = (@_batman.attributes ||={})[k] delete @_batman.attributes[k] x # New records can be constructed by passing either an ID or a hash of attributes (potentially # containing an ID) to the Model constructor. By not passing an ID, the model is marked as new. constructor: (idOrAttributes = {}) -> developer.assert @ instanceof Batman.Object, "constructors must be called with new" # We have to do this ahead of super, because mixins will call set which calls things on dirtyKeys. @dirtyKeys = new Batman.Hash @errors = new Batman.ErrorsHash # Find the ID from either the first argument or the attributes. if $typeOf(idOrAttributes) is 'Object' super(idOrAttributes) else super() @set('id', idOrAttributes) @empty() if not @state() # Override the `Batman.Observable` implementation of `set` to implement dirty tracking. set: (key, value) -> # Optimize setting where the value is the same as what's already been set. oldValue = @get(key) return if oldValue is value # Actually set the value and note what the old value was in the tracking array. result = super @dirtyKeys.set(key, oldValue) # Mark the model as dirty if isn't already. @dirty() unless @state() in ['dirty', 'loading', 'creating'] result updateAttributes: (attrs) -> @mixin(attrs) @ toString: -> "#{$functionName(@constructor)}: #{@get('id')}" # `toJSON` uses the various encoders for each key to grab a storable representation of the record. toJSON: -> obj = {} # Encode each key into a new object encoders = @_batman.get('encoders') unless !encoders or encoders.isEmpty() encoders.forEach (key, encoder) => val = @get key if typeof val isnt 'undefined' encodedVal = encoder(@get key) if typeof encodedVal isnt 'undefined' obj[key] = encodedVal obj # `fromJSON` uses the various decoders for each key to generate a record instance from the JSON # stored in whichever storage mechanism. fromJSON: (data) -> obj = {} decoders = @_batman.get('decoders') # If no decoders were specified, do the best we can to interpret the given JSON by camelizing # each key and just setting the values. if !decoders or decoders.isEmpty() for key, value of data obj[key] = value else # If we do have decoders, use them to get the data. decoders.forEach (key, decoder) -> obj[key] = decoder(data[key]) if data[key] # Mixin the buffer object to use optimized and event-preventing sets used by `mixin`. @mixin obj # Each model instance (each record) can be in one of many states throughout its lifetime. Since various # operations on the model are asynchronous, these states are used to indicate exactly what point the # record is at in it's lifetime, which can often be during a save or load operation. @actsAsStateMachine yes # Add the various states to the model. for k in ['empty', 'dirty', 'loading', 'loaded', 'saving', 'saved', 'creating', 'created', 'validating', 'validated', 'destroying', 'destroyed'] @state k for k in ['loading', 'loaded'] @classState k _doStorageOperation: (operation, options, callback) -> developer.assert @hasStorage(), "Can't #{operation} model #{$functionName(@constructor)} without any storage adapters!" mechanisms = @_batman.get('storage') for mechanism in mechanisms mechanism[operation] @, options, callback true hasStorage: -> (@_batman.get('storage') || []).length > 0 # `load` fetches the record from all sources possible load: (callback) => if @state() in ['destroying', 'destroyed'] callback?(new Error("Can't load a destroyed record!")) return do @loading @_doStorageOperation 'read', {}, (err, record) => unless err do @loaded record = @constructor._mapIdentity(record) callback?(err, record) # `save` persists a record to all the storage mechanisms added using `@persist`. `save` will only save # a model if it is valid. save: (callback) => if @state() in ['destroying', 'destroyed'] callback?(new Error("Can't save a destroyed record!")) return @validate (isValid, errors) => if !isValid callback?(errors) return creating = @isNew() do @saving do @creating if creating @_doStorageOperation (if creating then 'create' else 'update'), {}, (err, record) => unless err if creating do @created do @saved @dirtyKeys.clear() record = @constructor._mapIdentity(record) callback?(err, record) # `destroy` destroys a record in all the stores. destroy: (callback) => do @destroying @_doStorageOperation 'destroy', {}, (err, record) => unless err @constructor.get('all').remove(@) do @destroyed callback?(err) # `validate` performs the record level validations determining the record's validity. These may be asynchronous, # in which case `validate` has no useful return value. Results from asynchronous validations can be received by # listening to the `afterValidation` lifecycle callback. validate: (callback) -> oldState = @state() @errors.clear() do @validating finish = () => do @validated @[oldState]() callback?(@errors.length == 0, @errors) validators = @_batman.get('validators') || [] unless validators.length > 0 finish() else count = validators.length validationCallback = => if --count == 0 finish() for validator in validators v = validator.validator # Run the validator `v` or the custom callback on each key it validates by instantiating a new promise # and passing it to the appropriate function along with the key and the value to be validated. for key in validator.keys if v v.validateEach @errors, @, key, validationCallback else validator.callback @errors, @, key, validationCallback return isNew: -> typeof @get('id') is 'undefined' # `ErrorHash` is a simple subclass of `Hash` which makes it a bit easier to # manage the errors on a model. class Batman.ErrorsHash extends Batman.Hash constructor: -> super @meta.observe 'length', (newLength) => @length = newLength @meta.set 'messages', new Batman.Set # Define a default accessor to instantiate a set for any requested key. @accessor get: (key) -> unless set = Batman.SimpleHash::get.call(@, key) set = new Batman.Set set.observe 'itemsWereAdded', (items...) => @meta.set('length', @meta.get('length') + items.length) @meta.get('messages').add(items...) set.observe 'itemsWereRemoved', (items...) => @meta.set('length', @meta.get('length') - arguments.length) @meta.get('messages').remove(items...) Batman.SimpleHash::set.call(@, key, set) set set: -> developer.error "Can't set on an errors hash, use add instead!" unset: -> developer.error "Can't unset on an errors hash, use clear instead!" # Define a shorthand method for adding errors to a key. add: (key, error) -> @get(key).add(error) # Ensure any observers placed on the sets stay around by clearing the sets instead of the whole hash clear: -> @forEach (key, set) -> set.clear() @ class Batman.Validator extends Batman.Object constructor: (@options, mixins...) -> super mixins... validate: (record) -> developer.error "You must override validate in Batman.Validator subclasses." @options: (options...) -> Batman.initializeObject @ if @_batman.options then @_batman.options.concat(options) else @_batman.options = options @matches: (options) -> results = {} shouldReturn = no for key, value of options if ~@_batman?.options?.indexOf(key) results[key] = value shouldReturn = yes return results if shouldReturn Validators = Batman.Validators = [ class Batman.LengthValidator extends Batman.Validator @options 'minLength', 'maxLength', 'length', 'lengthWithin', 'lengthIn' constructor: (options) -> if range = (options.lengthIn or options.lengthWithin) options.minLength = range[0] options.maxLength = range[1] || -1 delete options.lengthWithin delete options.lengthIn super validateEach: (errors, record, key, callback) -> options = @options value = record.get(key) if options.minLength and value.length < options.minLength errors.add key, "#{key} must be at least #{options.minLength} characters" if options.maxLength and value.length > options.maxLength errors.add key, "#{key} must be less than #{options.maxLength} characters" if options.length and value.length isnt options.length errors.add key, "#{key} must be #{options.length} characters" callback() class Batman.PresenceValidator extends Batman.Validator @options 'presence' validateEach: (errors, record, key, callback) -> value = record.get(key) if @options.presence and !value? errors.add key, "#{key} must be present" callback() ] class Batman.StorageAdapter extends Batman.Object constructor: (model) -> super(model: model, modelKey: model.get('storageKey') || helpers.pluralize(helpers.underscore($functionName(model)))) isStorageAdapter: true @::_batman.check(@::) for k in ['all', 'create', 'read', 'readAll', 'update', 'destroy'] for time in ['before', 'after'] do (k, time) => key = "#{time}#{helpers.capitalize(k)}" @::[key] = (filter) -> @_batman.check(@) (@_batman["#{key}Filters"] ||= []).push filter before: (keys..., callback) -> @["before#{helpers.capitalize(k)}"](callback) for k in keys after: (keys..., callback) -> @["after#{helpers.capitalize(k)}"](callback) for k in keys _filterData: (prefix, action, data...) -> # Filter the data first with the beforeRead and then the beforeAll filters (@_batman.get("#{prefix}#{helpers.capitalize(action)}Filters") || []) .concat(@_batman.get("#{prefix}AllFilters") || []) .reduce( (filteredData, filter) => filter.call(@, filteredData) , data) getRecordFromData: (data) -> record = new @model() record.fromJSON(data) record $passError = (f) -> return (filterables) -> if filterables[0] filterables else err = filterables.shift() filterables = f.call(@, filterables) filterables.unshift(err) filterables class Batman.LocalStorage extends Batman.StorageAdapter constructor: -> if typeof window.localStorage is 'undefined' return null super @storage = localStorage @key_re = new RegExp("^#{@modelKey}(\\d+)$") @nextId = 1 @_forAllRecords (k, v) -> if matches = @key_re.exec(k) @nextId = Math.max(@nextId, parseInt(matches[1], 10) + 1) return @::before 'create', 'update', $passError ([record, options]) -> [JSON.stringify(record), options] @::after 'read', $passError ([record, attributes, options]) -> [record.fromJSON(JSON.parse(attributes)), attributes, options] _forAllRecords: (f) -> for i in [0...@storage.length] k = @storage.key(i) f.call(@, k, @storage.getItem(k)) getRecordFromData: (data) -> record = super @nextId = Math.max(@nextId, parseInt(record.get('id'), 10) + 1) record update: (record, options, callback) -> [err, recordToSave] = @_filterData('before', 'update', undefined, record, options) if !err id = record.get('id') if id? @storage.setItem(@modelKey + id, recordToSave) else err = new Error("Couldn't get record primary key.") callback(@_filterData('after', 'update', err, record, options)...) create: (record, options, callback) -> [err, recordToSave] = @_filterData('before', 'create', undefined, record, options) if !err id = record.get('id') || record.set('id', @nextId++) if id? key = @modelKey + id if @storage.getItem(key) err = new Error("Can't create because the record already exists!") else @storage.setItem(key, recordToSave) else err = new Error("Couldn't set record primary key on create!") callback(@_filterData('after', 'create', err, record, options)...) read: (record, options, callback) -> [err, record] = @_filterData('before', 'read', undefined, record, options) id = record.get('id') if !err if id? attrs = @storage.getItem(@modelKey + id) if !attrs err = new Error("Couldn't find record!") else err = new Error("Couldn't get record primary key.") callback(@_filterData('after', 'read', err, record, attrs, options)...) readAll: (_, options, callback) -> records = [] [err, options] = @_filterData('before', 'readAll', undefined, options) if !err @_forAllRecords (storageKey, data) -> if keyMatches = @key_re.exec(storageKey) records.push {data, id: keyMatches[1]} callback(@_filterData('after', 'readAll', err, records, options)...) @::after 'readAll', $passError ([allAttributes, options]) -> allAttributes = for attributes in allAttributes data = JSON.parse(attributes.data) data[@model.primaryKey] ||= parseInt(attributes.id, 10) data [allAttributes, options] @::after 'readAll', $passError ([allAttributes, options]) -> matches = [] for data in allAttributes match = true for k, v of options if data[k] != v match = false break if match matches.push data [matches, options] @::after 'readAll', $passError ([filteredAttributes, options]) -> [@getRecordFromData(data) for data in filteredAttributes, filteredAttributes, options] destroy: (record, options, callback) -> [err, record] = @_filterData 'before', 'destroy', undefined, record, options if !err id = record.get('id') if id? key = @modelKey + id if @storage.getItem key @storage.removeItem key else err = new Error("Can't delete nonexistant record!") else err = new Error("Can't delete record without an primary key!") callback(@_filterData('after', 'destroy', err, record, options)...) class Batman.RestStorage extends Batman.StorageAdapter defaultOptions: type: 'json' recordJsonNamespace: false collectionJsonNamespace: false constructor: -> super @recordJsonNamespace = helpers.singularize(@modelKey) @collectionJsonNamespace = helpers.pluralize(@modelKey) @::before 'create', 'update', $passError ([record, options]) -> json = record.toJSON() record = if @recordJsonNamespace x = {} x[@recordJsonNamespace] = json x else json [record, options] @::after 'create', 'read', 'update', $passError ([record, data, options]) -> data = data[@recordJsonNamespace] if data[@recordJsonNamespace] [record, data, options] @::after 'create', 'read', 'update', $passError ([record, data, options]) -> record.fromJSON(data) [record, data, options] optionsForRecord: (record, idRequired, callback) -> if record.url url = if typeof record.url is 'function' then record.url() else record.url else url = "/#{@modelKey}" if idRequired || !record.isNew() id = record.get('id') if !id? callback.call(@, new Error("Couldn't get record primary key!")) return url = url + "/" + id unless url callback.call @, new Error("Couldn't get model url!") else callback.call @, undefined, $mixin({}, @defaultOptions, {url}) optionsForCollection: (recordsOptions, callback) -> url = @model.url?() || @model.url || "/#{@modelKey}" unless url callback.call @, new Error("Couldn't get collection url!") else callback.call @, undefined, $mixin {}, @defaultOptions, {url, data: $mixin({}, @defaultOptions.data, recordsOptions)} create: (record, recordOptions, callback) -> @optionsForRecord record, false, (err, options) -> [err, data] = @_filterData('before', 'create', err, record, recordOptions) if err callback(err) return new Batman.Request $mixin options, data: data method: 'POST' success: (data) => callback(@_filterData('after', 'create', undefined, record, data, recordOptions)...) error: (error) => callback(@_filterData('after', 'create', error, record, error.request.get('response'), recordOptions)...) update: (record, recordOptions, callback) -> @optionsForRecord record, true, (err, options) -> [err, data] = @_filterData('before', 'update', err, record, recordOptions) if err callback(err) return new Batman.Request $mixin options, data: data method: 'PUT' success: (data) => callback(@_filterData('after', 'update', undefined, record, data, recordOptions)...) error: (error) => callback(@_filterData('after', 'update', error, record, error.request.get('response'), recordOptions)...) read: (record, recordOptions, callback) -> @optionsForRecord record, true, (err, options) -> [err, record, recordOptions] = @_filterData('before', 'read', err, record, recordOptions) if err callback(err) return new Batman.Request $mixin options, data: recordOptions method: 'GET' success: (data) => callback(@_filterData('after', 'read', undefined, record, data, recordOptions)...) error: (error) => callback(@_filterData('after', 'read', error, record, error.request.get('response'), recordOptions)...) readAll: (_, recordsOptions, callback) -> @optionsForCollection recordsOptions, (err, options) -> [err, recordsOptions] = @_filterData('before', 'readAll', err, recordsOptions) if err callback(err) return if recordsOptions && recordsOptions.url options.url = recordsOptions.url delete recordsOptions.url new Batman.Request $mixin options, data: recordsOptions method: 'GET' success: (data) => callback(@_filterData('after', 'readAll', undefined, data, recordsOptions)...) error: (error) => callback(@_filterData('after', 'readAll', error, error.request.get('response'), recordsOptions)...) @::after 'readAll', $passError ([data, options]) -> recordData = if data[@collectionJsonNamespace] then data[@collectionJsonNamespace] else data [recordData, data, options] @::after 'readAll', $passError ([recordData, serverData, options]) -> [@getRecordFromData(attributes) for attributes in recordData, serverData, options] destroy: (record, recordOptions, callback) -> @optionsForRecord record, true, (err, options) -> [err, record, recordOptions] = @_filterData('before', 'destroy', err, record, recordOptions) if err callback(err) return new Batman.Request $mixin options, method: 'DELETE' success: (data) => callback(@_filterData('after', 'destroy', undefined, record, data, recordOptions)...) error: (error) => callback(@_filterData('after', 'destroy', error, record, error.request.get('response'), recordOptions)...) # Views # ----------- # A `Batman.View` can function two ways: a mechanism to load and/or parse html files # or a root of a subclass hierarchy to create rich UI classes, like in Cocoa. class Batman.View extends Batman.Object constructor: (options) -> @contexts = [] super(options) # Support both `options.context` and `options.contexts` if context = @get('context') @contexts.push context @unset('context') viewSources = {} # Set the source attribute to an html file to have that file loaded. source: '' # Set the html to a string of html to have that html parsed. html: '' # Set an existing DOM node to parse immediately. node: null contentFor: null # Fires once a node is parsed. ready: @eventOneShot -> # Where to look for views on the server prefix: 'views' # Whenever the source changes we load it up asynchronously @observeAll 'source', -> setTimeout (=> @reloadSource()), 0 reloadSource: -> source = @get 'source' return if not source if viewSources[source] @set('html', viewSources[source]) else new Batman.Request url: url = "#{@prefix}/#{@source}" type: 'html' success: (response) => viewSources[source] = response @set('html', response) error: (response) -> throw new Error("Could not load view from #{url}") @observeAll 'html', (html) -> node = @node || document.createElement 'div' node.innerHTML = html @set('node', node) if @node isnt node @observeAll 'node', (node) -> return unless node @ready.fired = false if @_renderer @_renderer.forgetAll() # We use a renderer with the continuation style rendering engine to not # block user interaction for too long during the render. if node @_renderer = new Batman.Renderer( node, => content = @contentFor if typeof content is 'string' @contentFor = Batman.DOM._yields?[content] if @contentFor and node @contentFor.innerHTML = '' @contentFor.appendChild(node) , @contexts) @_renderer.rendered => @ready node # DOM Helpers # ----------- # `Batman.Renderer` will take a node and parse all recognized data attributes out of it and its children. # It is a continuation style parser, designed not to block for longer than 50ms at a time if the document # fragment is particularly long. class Batman.Renderer extends Batman.Object constructor: (@node, callback, contexts = []) -> super() @parsed callback if callback? @context = if contexts instanceof RenderContext then contexts else new RenderContext(contexts...) setTimeout @start, 0 start: => @startTime = new Date @parseNode @node resume: => @startTime = new Date @parseNode @resumeNode finish: -> @startTime = null @fire 'parsed' @fire 'rendered' forgetAll: -> parsed: @eventOneShot -> rendered: @eventOneShot -> bindingRegexp = /data\-(.*)/ sortBindings = (a, b) -> if a[0] == 'foreach' -1 else if b[0] == 'foreach' 1 else if a[0] == 'formfor' -1 else if b[0] == 'formfor' 1 else if a[0] == 'bind' -1 else if b[0] == 'bind' 1 else 0 parseNode: (node) -> if new Date - @startTime > 50 @resumeNode = node setTimeout @resume, 0 return if node.getAttribute and node.attributes bindings = for attr in node.attributes name = attr.nodeName.match(bindingRegexp)?[1] continue if not name if ~(varIndex = name.indexOf('-')) [name.substr(0, varIndex), name.substr(varIndex + 1), attr.value] else [name, attr.value] for readerArgs in bindings.sort(sortBindings) key = readerArgs[1] result = if readerArgs.length == 2 Batman.DOM.readers[readerArgs[0]]?(node, key, @context, @) else Batman.DOM.attrReaders[readerArgs[0]]?(node, key, readerArgs[2], @context, @) if result is false skipChildren = true break if (nextNode = @nextNode(node, skipChildren)) then @parseNode(nextNode) else @finish() nextNode: (node, skipChildren) -> if not skipChildren children = node.childNodes return children[0] if children?.length Batman.data(node, 'onParseExit')?() return if @node == node sibling = node.nextSibling return sibling if sibling nextParent = node while nextParent = nextParent.parentNode nextParent.onParseExit?() return if @node == nextParent parentSibling = nextParent.nextSibling return parentSibling if parentSibling return # Bindings are shortlived objects which manage the observation of any keypaths a `data` attribute depends on. # Bindings parse any keypaths which are filtered and use an accessor to apply the filters, and thus enjoy # the automatic trigger and dependency system that Batman.Objects use. class Binding extends Batman.Object # A beastly regular expression for pulling keypaths out of the JSON arguments to a filter. # It makes the following matches: # # + `foo` and `baz.qux` in `foo, "bar", baz.qux` # + `foo.bar.baz` in `true, false, "true", "false", foo.bar.baz` # + `true.bar` in `2, true.bar` # + `truesay` in truesay # + no matches in `"bar", 2, {"x":"y", "Z": foo.bar.baz}, "baz"` keypath_rx = /// (^|,) # Match either the start of an arguments list or the start of a space inbetween commas. \s* # Be insensitive to whitespace between the comma and the actual arguments. (?! # Use a lookahead to ensure we aren't matching true or false: (?:true|false) # Match either true or false ... \s* # and make sure that there's nothing else that comes after the true or false ... (?:$|,) # before the end of this argument in the list. ) ([a-zA-Z][\w\.]*) # Now that true and false can't be matched, match a dot delimited list of keys. \s* # Be insensitive to whitespace before the next comma or end of the filter arguments list. ($|,) # Match either the next comma or the end of the filter arguments list. ///g # A less beastly pair of regular expressions for pulling out the [] syntax `get`s in a binding string, and # dotted names that follow them. get_dot_rx = /(?:\]\.)(.+?)(?=[\[\.]|\s*\||$)/ get_rx = /(?!^\s*)\[(.*?)\]/g # The `filteredValue` which calculates the final result by reducing the initial value through all the filters. @accessor 'filteredValue', -> unfilteredValue = @get('unfilteredValue') ctx = @get('keyContext') if @get('key') if @filterFunctions.length > 0 developer.currentFilterContext = ctx developer.currentFilterStack = @renderContext result = @filterFunctions.reduce((value, fn, i) => # Get any argument keypaths from the context stored at parse time. args = @filterArguments[i].map (argument) -> if argument._keypath argument.context.get(argument._keypath) else argument # Apply the filter. args.unshift value fn.apply(ctx, args) , unfilteredValue) developer.currentFilterContext = null developer.currentFilterStack = null result else unfilteredValue # The `unfilteredValue` is whats evaluated each time any dependents change. @accessor 'unfilteredValue', -> # If we're working with an `@key` and not an `@value`, find the context the key belongs to so we can # hold a reference to it for passing to the `dataChange` and `nodeChange` observers. if k = @get('key') @get("keyContext.#{k}") else @get('value') # The `keyContext` accessor is @accessor 'keyContext', -> unless @_keyContext [unfilteredValue, @_keyContext] = @renderContext.findKey @key @_keyContext constructor: -> super # Pull out the key and filter from the `@keyPath`. @parseFilter() # Define the default observers. @nodeChange ||= (node, context) => if @key && @filterFunctions.length == 0 @get('keyContext').set @key, @node.value @dataChange ||= (value, node) -> Batman.DOM.valueForNode @node, value shouldSet = yes # And attach them. if @only in [false, 'nodeChange'] and Batman.DOM.nodeIsEditable(@node) Batman.DOM.events.change @node, => shouldSet = no @nodeChange(@node, @_keyContext || @value, @) shouldSet = yes # Observe the value of this binding's `filteredValue` and fire it immediately to update the node. if @only in [false, 'dataChange'] @observe 'filteredValue', yes, (value) => if shouldSet @dataChange(value, @node, @) @ parseFilter: -> # Store the function which does the filtering and the arguments (all except the actual value to apply the # filter to) in these arrays. @filterFunctions = [] @filterArguments = [] # Rewrite [] style gets, replace quotes to be JSON friendly, and split the string by pipes to see if there are any filters. keyPath = @keyPath keyPath = keyPath.replace(get_dot_rx, "]['$1']") while get_dot_rx.test(keyPath) # Stupid lack of lookbehind assertions... filters = keyPath.replace(get_rx, " | get $1 ").replace(/'/g, '"').split(/(?!")\s+\|\s+(?!")/) # The key will is always the first token before the pipe. try key = @parseSegment(orig = filters.shift())[0] catch e developer.warn e developer.error "Error! Couldn't parse keypath in \"#{orig}\". Parsing error above." if key and key._keypath @key = key._keypath else @value = key if filters.length while filterString = filters.shift() # For each filter, get the name and the arguments by splitting on the first space. split = filterString.indexOf(' ') if ~split filterName = filterString.substr(0, split) args = filterString.substr(split) else filterName = filterString # If the filter exists, grab it. if filter = Batman.Filters[filterName] @filterFunctions.push filter # Get the arguments for the filter by parsing the args as JSON, or # just pushing an placeholder array if args try @filterArguments.push @parseSegment(args) catch e developer.error "Bad filter arguments \"#{args}\"!" else @filterArguments.push [] else developer.error "Unrecognized filter '#{filterName}' in key \"#{@keyPath}\"!" # Map over each array of arguments to grab the context for any keypaths. @filterArguments = @filterArguments.map (argumentList) => argumentList.map (argument) => if argument._keypath # Discard the value (for the time being) and store the context for the keypath in `context`. [_, argument.context] = @renderContext.findKey argument._keypath argument # Turn a piece of a `data` keypath into a usable javascript object. # + replacing keypaths using the above regular expression # + wrapping the `,` delimited list in square brackets # + and `JSON.parse`ing them as an array. parseSegment: (segment) -> JSON.parse( "[" + segment.replace(keypath_rx, "$1{\"_keypath\": \"$2\"}$3") + "]" ) # The RenderContext class manages the stack of contexts accessible to a view during rendering. # Every, and I really mean every method which uses filters has to be defined in terms of a new # binding, or by using the RenderContext.bind method. This is so that the proper order of objects # is traversed and any observers are properly attached. class RenderContext constructor: (contexts...) -> @contexts = contexts @storage = new Batman.Object @defaultContexts = [@storage] @defaultContexts.push Batman.currentApp if Batman.currentApp findKey: (key) -> base = key.split('.')[0].split('|')[0].trim() for contexts in [@contexts, @defaultContexts] i = contexts.length while i-- context = contexts[i] if context.get? val = context.get(base) else val = context[base] if typeof val isnt 'undefined' # we need to pass the check if the basekey exists, even if the intermediary keys do not. return [$get(context, key), context] return [container.get(key), container] set: (args...) -> @storage.set(args...) push: (x) -> @contexts.push(x) pop: -> @contexts.pop() clone: -> context = new @constructor(@contexts...) newStorage = $mixin {}, @storage context.setStorage(newStorage) context setStorage: (storage) -> @defaultContexts[0] = storage # `BindingProxy` is a simple class which assists in allowing bound contexts to be popped to the top of # the stack. This happens when a `data-context` is descended into, for each iteration in a `data-foreach`, # and in other specific HTML bindings like `data-formfor`. `BindingProxy`s use accessors so that if the # value of the binding they proxy changes, the changes will be propagated to any thing observing it. # This is good because it allows `data-context` to take filtered keys and even filters which take # keypath arguments, calculate the context to descend into when any of those keys change, and importantly # expose a friendly `Batman.Object` interface for the rest of the `Binding` code to work with. @BindingProxy = class BindingProxy extends Batman.Object isBindingProxy: true # Take the `binding` which needs to be proxied, and optionally rest it at the `localKey` scope. constructor: (@binding, @localKey) -> if @localKey @accessor @localKey, -> @binding.get('filteredValue') else @accessor (key) -> @binding.get("filteredValue.#{key}") # Below are the two primitives that all the `Batman.DOM` helpers are composed of. # `addKeyToScopeForNode` takes a `node`, `key`, and optionally a `localName`. It creates a `Binding` to # the key (such that the key can contain filters and many keypaths in arguments), and then pushes the # bound value onto the stack of contexts for the given `node`. If `localName` is given, the bound value # is available using that identifier in child bindings. Otherwise, the value itself is pushed onto the # context stack and member properties can be accessed directly in child bindings. addKeyToScopeForNode: (node, key, localName) -> @bind(node, key, (value, node, binding) => @push new BindingProxy(binding, localName) , -> true ) # Pop the `BindingProxy` off the stack once this node has been parsed. Batman.data node, 'onParseExit', => @pop() # `bind` takes a `node`, a `key`, and observers for when the `dataChange`s and the `nodeChange`s. It # creates a `Binding` to the key (supporting filters and the context stack), which fires the observers # when appropriate. Note that `Binding` has default observers for `dataChange` and `nodeChange` that # will set node/object values if these observers aren't passed in here. # The optional `only` parameter can be used to create data-to-node-only or node-to-data-only bindings. If left unset, # both data-to-node (source) and node-to-data (target) events are observed. bind: (node, key, dataChange, nodeChange, only = false) -> return new Binding renderContext: @ keyPath: key node: node dataChange: dataChange nodeChange: nodeChange only: only Batman.DOM = { # `Batman.DOM.readers` contains the functions used for binding a node's value or innerHTML, showing/hiding nodes, # and any other `data-#{name}=""` style DOM directives. readers: { target: (node, key, context, renderer) -> Batman.DOM.readers.bind(node, key, context, renderer, 'nodeChange') source: (node, key, context, renderer) -> Batman.DOM.readers.bind(node, key, context, renderer, 'dataChange') bind: (node, key, context, renderer, only) -> switch node.nodeName.toLowerCase() when 'input' switch node.getAttribute('type') when 'checkbox' return Batman.DOM.attrReaders.bind(node, 'checked', key, context, renderer, only) when 'radio' return Batman.DOM.binders.radio(arguments...) when 'file' return Batman.DOM.binders.file(arguments...) when 'select' return Batman.DOM.binders.select(arguments...) # Fallback on the default nodeChange and dataChange observers in Binding context.bind(node, key, undefined, undefined, only) context: (node, key, context) -> context.addKeyToScopeForNode(node, key) mixin: (node, key, context) -> context.push(Batman.mixins) context.bind(node, key, (mixin) -> $mixin node, mixin , ->) context.pop() showif: (node, key, context, renderer, invert) -> originalDisplay = node.style.display || '' context.bind(node, key, (value) -> if !!value is !invert Batman.data(node, 'show')?.call(node) node.style.display = originalDisplay else if typeof (hide = Batman.data(node, 'hide')) == 'function' hide.call node else node.style.display = 'none' , -> ) hideif: (args...) -> Batman.DOM.readers.showif args..., yes route: (node, key, context) -> # you must specify the / in front to route directly to hash route if key.substr(0, 1) is '/' url = key else [key, action] = key.split '/' [dispatcher, app] = context.findKey 'dispatcher' [model, container] = context.findKey key dispatcher ||= Batman.currentApp.dispatcher if dispatcher and model instanceof Batman.Model action ||= 'show' name = helpers.underscore(helpers.pluralize($functionName(model.constructor))) url = dispatcher.findUrl({resource: name, id: model.get('id'), action: action}) else if model?.prototype # TODO write test for else case action ||= 'index' name = helpers.underscore(helpers.pluralize($functionName(model))) url = dispatcher.findUrl({resource: name, action: action}) return unless url if node.nodeName.toUpperCase() is 'A' node.href = Batman.HashHistory::urlFor url Batman.DOM.events.click node, (-> $redirect url) partial: (node, path, context, renderer) -> renderer.prevent('rendered') view = new Batman.View source: path + '.html' contentFor: node contexts: Array.prototype.slice.call(context.contexts) view.ready -> renderer.allow 'rendered' renderer.fire 'rendered' yield: (node, key) -> setTimeout (-> Batman.DOM.yield key, node), 0 contentfor: (node, key) -> setTimeout (-> Batman.DOM.contentFor key, node), 0 } # `Batman.DOM.attrReaders` contains all the DOM directives which take an argument in their name, in the # `data-dosomething-argument="keypath"` style. This means things like foreach, binding attributes like # disabled or anything arbitrary, descending into a context, binding specific classes, or binding to events. attrReaders: { _parseAttribute: (value) -> if value is 'false' then value = false if value is 'true' then value = true value source: (node, attr, key, context, renderer) -> Batman.DOM.attrReaders.bind node, attr, key, context, renderer, 'dataChange' bind: (node, attr, key, context, renderer, only) -> switch attr when 'checked', 'disabled', 'selected' dataChange = (value) -> node[attr] = !!value # Update the parent's binding if necessary Batman.data(node.parentNode, 'updateBinding')?() nodeChange = (node, subContext) -> subContext.set(key, Batman.DOM.attrReaders._parseAttribute(node[attr])) # Make the context and key available to the parent select Batman.data node, attr, context: context key: key when 'value', 'style', 'href', 'src', 'size' dataChange = (value) -> node[attr] = value nodeChange = (node, subContext) -> subContext.set(key, Batman.DOM.attrReaders._parseAttribute(node[attr])) when 'class' dataChange = (value) -> node.className = value nodeChange = (node, subContext) -> subContext.set key, node.className else dataChange = (value) -> node.setAttribute(attr, value) nodeChange = (node, subContext) -> subContext.set(key, Batman.DOM.attrReaders._parseAttribute(node.getAttribute(attr))) context.bind(node, key, dataChange, nodeChange, only) context: (node, contextName, key, context) -> context.addKeyToScopeForNode(node, key, contextName) event: (node, eventName, key, context) -> props = callback: null subContext: null context.bind node, key, (value, node, binding) -> props.callback = value if binding.get('key') ks = binding.get('key').split('.') ks.pop() if ks.length > 0 props.subContext = binding.get('keyContext').get(ks.join('.')) else props.subContext = binding.get('keyContext') , -> confirmText = node.getAttribute('data-confirm') Batman.DOM.events[eventName] node, -> if confirmText and not confirm(confirmText) return props.callback?.apply props.subContext, arguments addclass: (node, className, key, context, parentRenderer, invert) -> className = className.replace(/\|/g, ' ') #this will let you add or remove multiple class names in one binding context.bind node, key, (value) -> currentName = node.className includesClassName = currentName.indexOf(className) isnt -1 if !!value is !invert node.className = "#{currentName} #{className}" if !includesClassName else node.className = currentName.replace(className, '') if includesClassName , -> removeclass: (args...) -> Batman.DOM.attrReaders.addclass args..., yes foreach: (node, iteratorName, key, context, parentRenderer) -> prototype = node.cloneNode true prototype.removeAttribute "data-foreach-#{iteratorName}" parent = node.parentNode sibling = node.nextSibling # Remove the original node once the parent has moved past it. parentRenderer.parsed -> parent.removeChild node # Get a hash keyed by collection item with the nodes representing that item as values nodeMap = new Batman.SimpleHash fragment = document.createDocumentFragment() numPendingChildren = 0 observers = {} oldCollection = false context.bind(node, key, (collection) -> # Track the old collection so that if it changes, we can remove the observers we attached, # and only observe the new collection. if oldCollection return if collection == oldCollection nodeMap.forEach (item, node) -> node.parentNode?.removeChild node nodeMap.clear() if oldCollection.forget oldCollection.forget 'itemsWereAdded', observers.add oldCollection.forget 'itemsWereRemoved', observers.remove oldCollection.forget 'setWasSorted', observers.reorder oldCollection = collection observers.add = (items...) -> numPendingChildren += items.length for item in items parentRenderer.prevent 'rendered' newNode = prototype.cloneNode true nodeMap.set item, newNode localClone = context.clone() iteratorContext = new Batman.Object iteratorContext[iteratorName] = item localClone.push iteratorContext childRenderer = new Batman.Renderer newNode, do (newNode) -> -> if typeof (show = Batman.data(newNode, 'show')) == 'function' show.call newNode, before: sibling else fragment.appendChild newNode if --numPendingChildren == 0 parent.insertBefore fragment, sibling if collection.isSorted?() observers.reorder() fragment = document.createDocumentFragment() , localClone childRenderer.rendered => parentRenderer.allow 'rendered' parentRenderer.fire 'rendered' observers.remove = (items...) -> for item in items oldNode = nodeMap.get item nodeMap.unset item if oldNode? && typeof oldNode.hide is 'function' oldNode.hide yes else oldNode?.parentNode?.removeChild oldNode true observers.reorder = -> items = collection.toArray() for item in items thisNode = nodeMap.get(item) show = Batman.data thisNode, 'show' if typeof show is 'function' show.call thisNode, before: sibling else parent.insertBefore(thisNode, sibling) observers.arrayChange = (array) -> observers.remove(array...) observers.add(array...) # Observe the collection for events in the future if collection if collection.observe collection.observe 'itemsWereAdded', observers.add collection.observe 'itemsWereRemoved', observers.remove if collection.setWasSorted collection.observe 'setWasSorted', observers.reorder else collection.observe 'toArray', observers.arrayChange # Add all the already existing items. For hash-likes, add the key. if collection.forEach collection.forEach (item) -> observers.add(item) else if collection.get && array = collection.get('toArray') observers.add(array...) else for k, v of collection observers.add(k) else developer.warn "Warning! data-foreach-#{iteratorName} called with an undefined binding. Key was: #{key}." , -> ) false # Return false so the Renderer doesn't descend into this node's children. formfor: (node, localName, key, context) -> binding = context.addKeyToScopeForNode(node, key, localName) Batman.DOM.events.submit node, (node, e) -> $preventDefault e } # `Batman.DOM.binders` contains functions used to create element bindings # These are called via `Batman.DOM.readers` or `Batman.DOM.attrReaders` binders: { select: (node, key, context, renderer, only) -> [boundValue, container] = context.findKey key updateSelectBinding = => # Gather the selected options and update the binding selections = if node.multiple then (c.value for c in node.children when c.selected) else node.value selections = selections[0] if selections.length == 1 container.set key, selections updateOptionBindings = => # Go through the option nodes and update their bindings using the # context and key attached to the node via Batman.data for child in node.children if data = Batman.data(child, 'selected') if (subContext = data.context) and (subKey = data.key) [subBoundValue, subContainer] = subContext.findKey subKey unless child.selected == subBoundValue subContainer.set subKey, child.selected # wait for the select to render before binding to it renderer.rendered -> # Update the select box with the binding's new value. dataChange = (newValue) -> # For multi-select boxes, the `value` property only holds the first # selection, so we need to go through the child options and update # as necessary. if newValue instanceof Array # Use a hash to map values to their nodes to avoid O(n^2). valueToChild = {} for child in node.children # Clear all options. child.selected = false # Avoid collisions among options with same values. matches = valueToChild[child.value] if matches then matches.push child else matches = [child] valueToChild[child.value] = matches # Select options corresponding to the new values for value in newValue for match in valueToChild[value] match.selected = yes # For a regular select box, we just update the value. else node.value = newValue # Finally, we need to update the options' `selected` bindings updateOptionBindings() # Update the bindings with the node's new value nodeChange = -> updateSelectBinding() updateOptionBindings() # Expose the updateSelectBinding helper for the child options Batman.data node, 'updateBinding', updateSelectBinding # Create the binding context.bind node, key, dataChange, nodeChange, only radio: (node, key, context, renderer, only) -> dataChange = (value) -> # don't overwrite `checked` attributes in the HTML unless a bound # value is defined in the context. if no bound value is found, bind # to the key if the node is checked. [boundValue, container] = context.findKey key if boundValue node.checked = boundValue == node.value else if node.checked container.set key, node.value nodeChange = (newNode, subContext) -> subContext.set(key, Batman.DOM.attrReaders._parseAttribute(node.value)) context.bind node, key, dataChange, nodeChange, only file: (node, key, context, renderer, only) -> context.bind(node, key, -> developer.warn "Can't write to file inputs! Tried to on key #{key}." , (node, subContext) -> if subContext instanceof RenderContext.BindingProxy actualObject = subContext.binding.get('filteredValue') else actualObject = subContext if actualObject.hasStorage && actualObject.hasStorage() for adapter in actualObject._batman.get('storage') when adapter instanceof Batman.RestStorage adapter.defaultOptions.formData = true if node.hasAttribute('multiple') subContext.set key, Array::slice.call(node.files) else subContext.set key, node.files[0] , only) } # `Batman.DOM.events` contains the helpers used for binding to events. These aren't called by # DOM directives, but are used to handle specific events by the `data-event-#{name}` helper. events: { click: (node, callback, eventName = 'click') -> $addEventListener node, eventName, (args...) -> callback node, args... $preventDefault args[0] if node.nodeName.toUpperCase() is 'A' and not node.href node.href = '#' node doubleclick: (node, callback) -> Batman.DOM.events.click node, callback, 'dblclick' change: (node, callback) -> eventNames = switch node.nodeName.toUpperCase() when 'TEXTAREA' then ['keyup', 'change'] when 'INPUT' if node.type.toUpperCase() is 'TEXT' oldCallback = callback callback = (e) -> return if e.type == 'keyup' && 13 <= e.keyCode <= 14 oldCallback(arguments...) ['keyup', 'change'] else ['change'] else ['change'] for eventName in eventNames $addEventListener node, eventName, (args...) -> callback node, args... submit: (node, callback) -> if Batman.DOM.nodeIsEditable(node) $addEventListener node, 'keyup', (args...) -> if args[0].keyCode is 13 || args[0].which is 13 || args[0].keyIdentifier is 'Enter' || args[0].key is 'Enter' $preventDefault args[0] callback node, args... else $addEventListener node, 'submit', (args...) -> $preventDefault args[0] callback node, args... node } # `yield` and `contentFor` are used to declare partial views and then pull them in elsewhere. # This can be used for abstraction as well as repetition. yield: (name, node) -> yields = Batman.DOM._yields ||= {} yields[name] = node if (content = Batman.DOM._yieldContents?[name]) node.innerHTML = '' node.appendChild(content) if content contentFor: (name, node) -> contents = Batman.DOM._yieldContents ||= {} contents[name] = node if (yield = Batman.DOM._yields?[name]) content = if $isChildOf(yield, node) then node.cloneNode(true) else node yield.innerHTML = '' yield.appendChild(content) if content valueForNode: (node, value = '') -> isSetting = arguments.length > 1 switch node.nodeName.toUpperCase() when 'INPUT' if isSetting then (node.value = value) else node.value when 'TEXTAREA' if isSetting node.innerHTML = node.value = value else node.innerHTML when 'SELECT' node.value = value else if isSetting then (node.innerHTML = value) else node.innerHTML nodeIsEditable: (node) -> node.nodeName.toUpperCase() in ['INPUT', 'TEXTAREA', 'SELECT'] # `$addEventListener uses attachEvent when necessary addEventListener: $addEventListener = if window?.addEventListener ((node, eventName, callback) -> node.addEventListener eventName, callback, false) else ((node, eventName, callback) -> node.attachEvent "on#{eventName}", callback) # `$removeEventListener` uses detachEvent when necessary removeEventListener: $removeEventListener = if window?.removeEventListener ((elem, eventType, handler) -> elem.removeEventListener eventType, handler, false) else ((elem, eventType, handler) -> elem.detachEvent 'on'+eventType, handler) } # Filters # ------- # # `Batman.Filters` contains the simple, determininistic tranforms used in view bindings to # make life a little easier. buntUndefined = (f) -> (value) -> if typeof value is 'undefined' undefined else f.apply(@, arguments) filters = Batman.Filters = get: buntUndefined (value, key) -> if value.get? value.get(key) else value[key] equals: buntUndefined (lhs, rhs) -> lhs is rhs not: (value) -> ! !!value truncate: buntUndefined (value, length, end = "...") -> if value.length > length value = value.substr(0, length-end.length) + end value default: (value, string) -> value || string prepend: (value, string) -> string + value append: (value, string) -> value + string downcase: buntUndefined (value) -> value.toLowerCase() upcase: buntUndefined (value) -> value.toUpperCase() pluralize: buntUndefined (string, count) -> helpers.pluralize(count, string) join: buntUndefined (value, byWhat = '') -> value.join(byWhat) sort: buntUndefined (value) -> value.sort() map: buntUndefined (value, key) -> value.map((x) -> x[key]) first: buntUndefined (value) -> value[0] meta: buntUndefined (value, keypath) -> value.meta.get(keypath) for k in ['capitalize', 'singularize', 'underscore', 'camelize'] filters[k] = buntUndefined helpers[k] developer.addFilters() # Data # ---- $mixin Batman, cache: {} uuid: 0 expando: "batman" + Math.random().toString().replace(/\D/g, '') canDeleteExpando: true noData: # these throw exceptions if you attempt to add expandos to them "embed": true, # Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true hasData: (elem) -> elem = (if elem.nodeType then Batman.cache[elem[Batman.expando]] else elem[Batman.expando]) !!elem and !isEmptyDataObject(elem) data: (elem, name, data, pvt) -> # pvt is for internal use only return unless Batman.acceptData(elem) internalKey = Batman.expando getByName = typeof name == "string" # DOM nodes and JS objects have to be handled differently because IE6-7 can't # GC object references properly across the DOM-JS boundary isNode = elem.nodeType # Only DOM nodes need the global cache; JS object data is attached directly so GC # can occur automatically cache = if isNode then Batman.cache else elem # Only defining an ID for JS objects if its cache already exists allows # the code to shortcut on the same path as a DOM node with no cache id = if isNode then elem[Batman.expando] else elem[Batman.expando] && Batman.expando # Avoid doing any more work than we need to when trying to get data on an # object that has no data at all if (not id or (pvt and id and (cache[id] and not cache[id][internalKey]))) and getByName and data == undefined return unless id # Only DOM nodes need a new unique ID for each element since their data # ends up in the global cache if isNode elem[Batman.expando] = id = ++Batman.uuid else id = Batman.expando cache[id] = {} unless cache[id] # An object can be passed to Batman.data instead of a key/value pair; this gets # shallow copied over onto the existing cache if typeof name == "object" or typeof name == "function" if pvt cache[id][internalKey] = $mixin(cache[id][internalKey], name) else cache[id] = $mixin(cache[id], name) thisCache = cache[id] # Internal Batman data is stored in a separate object inside the object's data # cache in order to avoid key collisions between internal data and user-defined # data if pvt thisCache[internalKey] = {} unless thisCache[internalKey] thisCache = thisCache[internalKey] unless data is undefined thisCache[helpers.camelize(name, true)] = data # Check for both converted-to-camel and non-converted data property names # If a data property was specified if getByName # First try to find as-is property data ret = thisCache[name] # Test for null|undefined property data and try to find camel-cased property ret = thisCache[helpers.camelize(name, true)] unless ret? else ret = thisCache return ret removeData: (elem, name, pvt) -> # pvt is for internal use only return unless Batman.acceptData(elem) internalKey = Batman.expando isNode = elem.nodeType # non DOM-nodes have their data attached directly cache = if isNode then Batman.cache else elem id = if isNode then elem[Batman.expando] else Batman.expando # If there is already no cache entry for this object, there is no # purpose in continuing return unless cache[id] if name thisCache = if pvt then cache[id][internalKey] else cache[id] if thisCache # Support interoperable removal of hyphenated or camelcased keys name = helpers.camelize(name, true) unless thisCache[name] delete thisCache[name] # If there is no data left in the cache, we want to continue # and let the cache object itself get destroyed return unless isEmptyDataObject(thisCache) if pvt delete cache[id][internalKey] # Don't destroy the parent cache unless the internal data object # had been the only thing left in it return unless isEmptyDataObject(cache[id]) internalCache = cache[id][internalKey] # Browsers that fail expando deletion also refuse to delete expandos on # the window, but it will allow it on all other JS objects; other browsers # don't care # Ensure that `cache` is not a window object if Batman.canDeleteExpando or !cache.setInterval delete cache[id] else cache[id] = null # We destroyed the entire user cache at once because it's faster than # iterating through each key, but we need to continue to persist internal # data if it existed if internalCache cache[id] = {} cache[id][internalKey] = internalCache # Otherwise, we need to eliminate the expando on the node to avoid # false lookups in the cache for entries that no longer exist else if isNode if Batman.canDeleteExpando delete elem[Batman.expando] else if elem.removeAttribute elem.removeAttribute Batman.expando else elem[Batman.expando] = null # For internal use only _data: (elem, name, data) -> Batman.data elem, name, data, true # A method for determining if a DOM node can handle the data expando acceptData: (elem) -> if elem.nodeName match = Batman.noData[elem.nodeName.toLowerCase()] if match return !(match == true or elem.getAttribute("classid") != match) return true isEmptyDataObject = (obj) -> for name of obj return false return true # Test to see if it's possible to delete an expando from an element # Fails in Internet Explorer try div = document.createElement 'div' delete div.test catch e Batman.canDeleteExpando = false # Mixins # ------ mixins = Batman.mixins = new Batman.Object() # Encoders # ------ Batman.Encoders = railsDate: encode: (value) -> value decode: (value) -> a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value) if a return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])) else developer.error "Unrecognized rails date #{value}!" # Export a few globals, and grab a reference to an object accessible from all contexts for use elsewhere. # In node, the container is the `global` object, and in the browser, the container is the window object. container = if exports? module.exports = Batman global else window.Batman = Batman window $mixin container, Batman.Observable # Optionally export global sugar. Not sure what to do with this. Batman.exportHelpers = (onto) -> for k in ['mixin', 'unmixin', 'route', 'redirect', 'event', 'eventOneShot', 'typeOf', 'redirect'] onto["$#{k}"] = Batman[k] onto Batman.exportGlobals = () -> Batman.exportHelpers(container)
215952
# # batman.js # # Created by <NAME> # Copyright 2011, Shopify # # The global namespace, the `Batman` function will also create also create a new # instance of Batman.Object and mixin all arguments to it. Batman = (mixins...) -> new Batman.Object mixins... # Global Helpers # ------- # `$typeOf` returns a string that contains the built-in class of an object # like `String`, `Array`, or `Object`. Note that only `Object` will be returned for # the entire prototype chain. Batman.typeOf = $typeOf = (object) -> return "Undefined" if typeof object == 'undefined' _objectToString.call(object).slice(8, -1) # Cache this function to skip property lookups. _objectToString = Object.prototype.toString # `$mixin` applies every key from every argument after the first to the # first argument. If a mixin has an `initialize` method, it will be called in # the context of the `to` object, and it's key/values won't be applied. Batman.mixin = $mixin = (to, mixins...) -> hasSet = typeof to.set is 'function' for mixin in mixins continue if $typeOf(mixin) isnt 'Object' for own key, value of mixin continue if key in ['initialize', 'uninitialize', 'prototype'] if hasSet to.set(key, value) else if to.nodeName? Batman.data to, key, value else to[key] = value if typeof mixin.initialize is 'function' mixin.initialize.call to to # `$unmixin` removes every key/value from every argument after the first # from the first argument. If a mixin has a `deinitialize` method, it will be # called in the context of the `from` object and won't be removed. Batman.unmixin = $unmixin = (from, mixins...) -> for mixin in mixins for key of mixin continue if key in ['initialize', 'uninitialize'] delete from[key] if typeof mixin.uninitialize is 'function' mixin.uninitialize.call from from # `$block` takes in a function and returns a function which can either # A) take a callback as its last argument as it would normally, or # B) accept a callback as a second function application. # This is useful so that multiline functions can be passed as callbacks # without the need for wrapping brackets (which a CoffeeScript bug # requires them to have). `$block` also takes an optional function airity # argument as the first argument. If a `length` argument is given, and `length` # or more arguments are passed, `$block` will call the second argument # (the function) with the passed arguments, regardless of their type. # Example: # With a function that accepts a callback as its last argument # # f = (a, b, callback) -> callback(a + b) # ex = $block f # # We can use $block to make it accept the callback in both ways: # # ex(2, 3, (x) -> alert(x)) # alerts 5 # # or # # ex(2, 3) (x) -> alert(x) # Batman._block = $block = (lengthOrFunction, fn) -> if fn? argsLength = lengthOrFunction else fn = lengthOrFunction callbackEater = (args...) -> ctx = @ f = (callback) -> args.push callback fn.apply(ctx, args) # Call the function right now if we've been passed the callback already or if we've reached the argument count threshold if (typeof args[args.length-1] is 'function') || (argsLength && (args.length >= argsLength)) f(args.pop()) else f # `findName` allows an anonymous function to find out what key it resides # in within a context. Batman._findName = $findName = (f, context) -> unless f.displayName for key, value of context if value is f f.displayName = key break f.displayName # `$functionName` returns the name of a given function, if any # Used to deal with functions not having the `name` property in IE Batman._functionName = $functionName = (f) -> return f.__name__ if f.__name__ return f.name if f.name f.toString().match(/\W*function\s+([\w\$]+)\(/)?[1] # `$preventDefault` checks for preventDefault, since it's not # always available across all browsers Batman._preventDefault = $preventDefault = (e) -> if typeof e.preventDefault is "function" then e.preventDefault() else e.returnValue = false Batman._isChildOf = $isChildOf = (parentNode, childNode) -> node = childNode.parentNode while node return true if node == parentNode node = node.parentNode false # Developer Tooling # ----------------- developer = DevelopmentError: (-> DevelopmentError = (@message) -> @name = "DevelopmentError" DevelopmentError:: = Error:: DevelopmentError )() _ie_console: (f, args) -> console?[f] "...#{f} of #{args.length} items..." unless args.length == 1 console?[f] arg for arg in args log: -> return unless console?.log? if console.log.apply then console.log(arguments...) else developer._ie_console "log", arguments warn: -> return unless console?.warn? if console.warn.apply then console.warn(arguments...) else developer._ie_console "warn", arguments error: (message) -> throw new developer.DevelopmentError(message) assert: (result, message) -> developer.error(message) unless result addFilters: -> $mixin Batman.Filters, log: (value, key) -> console?.log? arguments value logStack: (value) -> console?.log? developer.currentFilterStack value logContext: (value) -> console?.log? developer.currentFilterContext value Batman.developer = developer # Helpers # ------- camelize_rx = /(?:^|_|\-)(.)/g capitalize_rx = /(^|\s)([a-z])/g underscore_rx1 = /([A-Z]+)([A-Z][a-z])/g underscore_rx2 = /([a-z\d])([A-Z])/g # Just a few random Rails-style string helpers. You can add more # to the Batman.helpers object. helpers = Batman.helpers = { camelize: (string, firstLetterLower) -> string = string.replace camelize_rx, (str, p1) -> p1.toUpperCase() if firstLetterLower then string.substr(0,1).toLowerCase() + string.substr(1) else string underscore: (string) -> string.replace(underscore_rx1, '$1_$2') .replace(underscore_rx2, '$1_$2') .replace('-', '_').toLowerCase() singularize: (string) -> len = string.length if string.substr(len - 3) is 'ies' string.substr(0, len - 3) + 'y' else if string.substr(len - 1) is 's' string.substr(0, len - 1) else string pluralize: (count, string) -> if string return string if count is 1 else string = count len = string.length lastLetter = string.substr(len - 1) if lastLetter is 'y' "#{string.substr(0, len - 1)}ies" else if lastLetter is 's' string else "#{string}s" capitalize: (string) -> string.replace capitalize_rx, (m,p1,p2) -> p1+p2.toUpperCase() trim: (string) -> if string then string.trim() else "" } # Properties # ---------- class Batman.Property @defaultAccessor: get: (key) -> @[key] set: (key, val) -> @[key] = val unset: (key) -> x = @[key]; delete @[key]; x @triggerTracker: null @forBaseAndKey: (base, key) -> propertyClass = base.propertyClass or Batman.Keypath if base._batman Batman.initializeObject base properties = base._batman.properties ||= new Batman.SimpleHash properties.get(key) or properties.set(key, new propertyClass(base, key)) else new propertyClass(base, key) constructor: (@base, @key) -> @observers = new Batman.SimpleSet @refreshTriggers() if @hasObserversToFire() @_preventCount = 0 isProperty: true isEqual: (other) -> @constructor is other.constructor and @base is other.base and @key is other.key accessor: -> accessors = @base._batman?.get('keyAccessors') if accessors && (val = accessors.get(@key)) return val else @base._batman?.getFirst('defaultAccessor') or Batman.Property.defaultAccessor registerAsTrigger: -> tracker.add @ if tracker = Batman.Property.triggerTracker getValue: -> @registerAsTrigger() @accessor()?.get.call @base, @key setValue: (val) -> @cacheDependentValues() result = @accessor()?.set.call @base, @key, val @fireDependents() result unsetValue: -> @cacheDependentValues() result = @accessor()?.unset.call @base, @key @fireDependents() result cacheDependentValues: -> if @dependents @dependents.forEach (prop) -> prop.cachedValue = prop.getValue() fireDependents: -> if @dependents @dependents.forEach (prop) -> prop.fire(prop.getValue(), prop.cachedValue) if prop.hasObserversToFire?() observe: (fireImmediately..., callback) -> fireImmediately = fireImmediately[0] is true currentValue = @getValue() @observers.add callback @refreshTriggers() callback.call(@base, currentValue, currentValue) if fireImmediately @ hasObserversToFire: -> return true if @observers.length > 0 if @base._batman @base._batman.ancestors().some((ancestor) => ancestor.property?(@key)?.observers?.length > 0) else false prevent: -> @_preventCount++ allow: -> @_preventCount-- if @_preventCount > 0 isAllowedToFire: -> @_preventCount <= 0 fire: (args...) -> return unless @isAllowedToFire() and @hasObserversToFire() key = @key base = @base observerSets = [@observers] @observers.forEach (callback) -> callback?.apply base, args if @base._batman @base._batman.ancestors (ancestor) -> ancestor.property?(key).observers.forEach (callback) -> callback?.apply base, args @refreshTriggers() forget: (observer) -> if observer @observers.remove(observer) else @observers = new Batman.SimpleSet @clearTriggers() unless @hasObserversToFire() refreshTriggers: -> Batman.Property.triggerTracker = new Batman.SimpleSet @getValue() if @triggers @triggers.forEach (property) => unless Batman.Property.triggerTracker.has(property) property.dependents?.remove @ @triggers = Batman.Property.triggerTracker @triggers.forEach (property) => property.dependents ||= new Batman.SimpleSet property.dependents.add @ delete Batman.Property.triggerTracker clearTriggers: -> if @triggers @triggers.forEach (property) => property.dependents.remove @ @triggers = new Batman.SimpleSet # Keypaths # -------- class Batman.Keypath extends Batman.Property constructor: (base, key) -> if $typeOf(key) is 'String' @segments = key.split('.') @depth = @segments.length else @segments = [key] @depth = 1 super slice: (begin, end = @depth) -> base = @base for segment in @segments.slice(0, begin) return unless base? and base = Batman.Property.forBaseAndKey(base, segment).getValue() Batman.Property.forBaseAndKey base, @segments.slice(begin, end).join('.') terminalProperty: -> @slice -1 getValue: -> @registerAsTrigger() if @depth is 1 then super else @terminalProperty()?.getValue() setValue: (val) -> if @depth is 1 then super else @terminalProperty()?.setValue(val) unsetValue: -> if @depth is 1 then super else @terminalProperty()?.unsetValue() # Observable # ---------- # Batman.Observable is a generic mixin that can be applied to any object to allow it to be bound to. # It is applied by default to every instance of `Batman.Object` and subclasses. Batman.Observable = isObservable: true property: (key) -> Batman.initializeObject @ Batman.Property.forBaseAndKey(@, key) get: (key) -> @property(key).getValue() set: (key, val) -> @property(key).setValue(val) unset: (key) -> @property(key).unsetValue() getOrSet: (key, valueFunction) -> currentValue = @get(key) unless currentValue currentValue = valueFunction() @set(key, currentValue) currentValue # `forget` removes an observer from an object. If the callback is passed in, # its removed. If no callback but a key is passed in, all the observers on # that key are removed. If no key is passed in, all observers are removed. forget: (key, observer) -> if key @property(key).forget(observer) else @_batman.properties.forEach (key, property) -> property.forget() @ # `allowed` returns a boolean describing whether or not the key is # currently allowed to fire its observers. allowed: (key) -> @property(key).isAllowedToFire() # `fire` tells any observers attached to a key to fire, manually. # `prevent` stops of a given binding from firing. `prevent` calls can be repeated such that # the same number of calls to allow are needed before observers can be fired. # `allow` unblocks a property for firing observers. Every call to prevent # must have a matching call to allow later if observers are to be fired. # `observe` takes a key and a callback. Whenever the value for that key changes, your # callback will be called in the context of the original object. for k in ['observe', 'prevent', 'allow', 'fire'] do (k) -> Batman.Observable[k] = (key, args...) -> @property(key)[k](args...) @ $get = Batman.get = (object, key) -> if object.get object.get(key) else Batman.Observable.get.call(object, key) # Events # ------ # `Batman.EventEmitter` is another generic mixin that simply allows an object to # emit events. Batman events use observers to manage the callbacks, so they require that # the object emitting the events be observable. If events need to be attached to an object # which isn't a `Batman.Object` or doesn't have the `Batman.Observable` and `Batman.EventEmitter` # mixins applied, the $event function can be used to create ephemeral event objects which # use those mixins internally. Batman.EventEmitter = # An event is a convenient observer wrapper. Any function can be wrapped in an event, and # when called, it will cause it's object to fire all the observers for that event. There is # also some syntactical sugar so observers can be registered simply by calling the event with a # function argument. Notice that the `$block` helper is used here so events can be declared in # class definitions using the second function application syntax and no wrapping brackets. event: $block (key, context, callback) -> if not callback and typeof context isnt 'undefined' callback = context context = null if not callback and $typeOf(key) isnt 'String' callback = key key = null # Return a function which either takes another observer # to register or a value to fire the event with. f = (observer) -> if not @observe developer.error "EventEmitter requires Observable" Batman.initializeObject @ key ||= $findName(f, @) fired = @_batman.oneShotFired?[key] # Pass a function to the event to register it as an observer. if typeof observer is 'function' @observe key, observer observer.apply(@, f._firedArgs) if f.isOneShot and fired # Otherwise, calling the event will cause it to fire. Any # arguments you pass will be passed to your wrapped function. else if @allowed key return false if f.isOneShot and fired value = callback?.apply @, arguments # Observers will only fire if the result of the event is not false. if value isnt false # Get and cache the arguments for the event listeners. Add the value if # its not undefined, and then concat any more arguments passed to this # event when fired. f._firedArgs = unless typeof value is 'undefined' [value].concat arguments... else if arguments.length == 0 [] else Array.prototype.slice.call arguments # Copy the array and add in the key for `fire` args = Array.prototype.slice.call f._firedArgs args.unshift key @fire(args...) if f.isOneShot firings = @_batman.oneShotFired ||= {} firings[key] = yes value else false # This could be its own mixin but is kept here for brevity. f = f.bind(context) if context @[key] = f if key? $mixin f, isEvent: yes action: callback # One shot events can be used for something that only fires once. Any observers # added after it has already fired will simply be executed immediately. This is useful # for things like `ready` events on requests or renders, because once ready they always # remain ready. If an AJAX request had a vanilla `ready` event, observers attached after # the ready event fired the first time would never fire, as they would be waiting for # the next time `ready` would fire as is standard with vanilla events. With a one shot # event, any observers attached after the first fire will fire immediately, meaning no logic eventOneShot: (callback) -> $mixin Batman.EventEmitter.event.apply(@, arguments), isOneShot: yes oneShotFired: @oneShotFired.bind @ oneShotFired: (key) -> Batman.initializeObject @ firings = @_batman.oneShotFired ||= {} !!firings[key] # `$event` lets you create an ephemeral event without needing an EventEmitter. # If you already have an EventEmitter object, you should call .event() on it. Batman.event = $event = (callback) -> context = new Batman.Object context.event('_event', context, callback) # `$eventOneShot` lets you create an ephemeral one-shot event without needing an EventEmitter. # If you already have an EventEmitter object, you should call .eventOneShot() on it. Batman.eventOneShot = $eventOneShot = (callback) -> context = new Batman.Object oneShot = context.eventOneShot('_event', context, callback) oneShot.oneShotFired = -> context.oneShotFired('_event') oneShot # Objects # ------- # `Batman.initializeObject` is called by all the methods in Batman.Object to ensure that the # object's `_batman` property is initialized and it's own. Classes extending Batman.Object inherit # methods like `get`, `set`, and `observe` by default on the class and prototype levels, such that # both instances and the class respond to them and can be bound to. However, CoffeeScript's static # class inheritance copies over all class level properties indiscriminately, so a parent class' # `_batman` object will get copied to its subclasses, transferring all the information stored there and # allowing subclasses to mutate parent state. This method prevents this undesirable behaviour by tracking # which object the `_batman_` object was initialized upon, and reinitializing if that has changed since # initialization. Batman.initializeObject = (object) -> if object._batman? object._batman.check(object) else object._batman = new _Batman(object) # _Batman provides a convienient, parent class and prototype aware place to store hidden # object state. Things like observers, accessors, and states belong in the `_batman` object # attached to every Batman.Object subclass and subclass instance. Batman._Batman = class _Batman constructor: (@object, mixins...) -> $mixin(@, mixins...) if mixins.length > 0 # Used by `Batman.initializeObject` to ensure that this `_batman` was created referencing # the object it is pointing to. check: (object) -> if object != @object object._batman = new _Batman(object) return false return true # `get` is a prototype and class aware property access method. `get` will traverse the prototype chain, asking # for the passed key at each step, and then attempting to merge the results into one object. # It can only do this if at each level an `Array`, `Hash`, or `Set` is found, so try to use # those if you need `_batman` inhertiance. get: (key) -> # Get all the keys from the ancestor chain results = @getAll(key) switch results.length when 0 undefined when 1 results[0] else # And then try to merge them if there is more than one. Use `concat` on arrays, and `merge` on # sets and hashes. if results[0].concat? results = results.reduceRight (a, b) -> a.concat(b) else if results[0].merge? results = results.reduceRight (a, b) -> a.merge(b) results # `getFirst` is a prototype and class aware property access method. `getFirst` traverses the prototype chain, # and returns the value of the first `_batman` object which defines the passed key. Useful for # times when the merged value doesn't make sense or the value is a primitive. getFirst: (key) -> results = @getAll(key) results[0] # `getAll` is a prototype and class chain iterator. When passed a key or function, it applies it to each # parent class or parent prototype, and returns the undefined values, closest ancestor first. getAll: (keyOrGetter) -> # Get a function which pulls out the key from the ancestor's `_batman` or use the passed function. if typeof keyOrGetter is 'function' getter = keyOrGetter else getter = (ancestor) -> ancestor._batman?[keyOrGetter] # Apply it to all the ancestors, and then this `_batman`'s object. results = @ancestors(getter) if val = getter(@object) results.unshift val results # `ancestors` traverses the prototype or class chain and returns the application of a function to each # object in the chain. `ancestors` does this _only_ to the `@object`'s ancestors, and not the `@object` # itsself. ancestors: (getter = (x) -> x) -> results = [] # Decide if the object is a class or not, and pull out the first ancestor isClass = !!@object.prototype parent = if isClass @object.__super__?.constructor else if (proto = Object.getPrototypeOf(@object)) == @object @object.constructor.__super__ else proto if parent? # Apply the function and store the result if it isn't undefined. val = getter(parent) results.push(val) if val? # Use a recursive call to `_batman.ancestors` on the ancestor, which will take the next step up the chain. results = results.concat(parent._batman.ancestors(getter)) if parent._batman? results set: (key, value) -> @[key] = value # `Batman.Object` is the base class for all other Batman objects. It is not abstract. class BatmanObject # Setting `isGlobal` to true will cause the class name to be defined on the # global object. For example, Batman.Model will be aliased to window.Model. # This should be used sparingly; it's mostly useful for debugging. @global: (isGlobal) -> return if isGlobal is false container[$functionName(@)] = @ # Apply mixins to this class. @classMixin: -> $mixin @, arguments... # Apply mixins to instances of this class. @mixin: -> @classMixin.apply @prototype, arguments mixin: @classMixin # Accessor implementation. Accessors are used to create properties on a class or prototype which can be fetched # with get, but are computed instead of just stored. This is a batman and old browser friendly version of # `defineProperty` without as much goodness. # # Accessors track which other properties they rely on for computation, and when those other properties change, # an accessor will recalculate its value and notifiy its observers. This way, when a source value is changed, # any dependent accessors will automatically update any bindings to them with a new value. Accessors accomplish # this feat by tracking `get` calls, do be sure to use `get` to retrieve properties inside accessors. # # `@accessor` or `@classAccessor` can be called with zero, one, or many keys to attach the accessor to. This # has the following effects: # # * zero: create a `defaultAccessor`, which will be called when no other properties or accessors on an object # match a keypath. This is similar to `method_missing` in Ruby or `#doesNotUnderstand` in Smalltalk. # * one: create a `keyAccessor` at the given key, which will only be called when that key is `get`ed. # * many: create `keyAccessors` for each given key, which will then be called whenever each key is `get`ed. # # Note: This function gets called in all sorts of different contexts by various # other pointers to it, but it acts the same way on `this` in all cases. getAccessorObject = (accessor) -> accessor = {get: accessor} if !accessor.get && !accessor.set && !accessor.unset accessor @classAccessor: (keys..., accessor) -> Batman.initializeObject @ # Create a default accessor if no keys have been given. if keys.length is 0 # The `accessor` argument is wrapped in `getAccessorObject` which allows functions to be passed in # as a shortcut to {get: function} @_batman.defaultAccessor = getAccessorObject(accessor) else # Otherwise, add key accessors for each key given. @_batman.keyAccessors ||= new Batman.SimpleHash @_batman.keyAccessors.set(key, getAccessorObject(accessor)) for key in keys # Support adding accessors to the prototype from within class defintions or after the class has been created # with `KlassExtendingBatmanObject.accessor(keys..., accessorObject)` @accessor: -> @classAccessor.apply @prototype, arguments # Support adding accessors to instances after creation accessor: @classAccessor constructor: (mixins...) -> @_batman = new _Batman(@) @mixin mixins... # Make every subclass and their instances observable. @classMixin Batman.Observable, Batman.EventEmitter @mixin Batman.Observable, Batman.EventEmitter # Observe this property on every instance of this class. @observeAll: -> @::observe.apply @prototype, arguments @singleton: (singletonMethodName="sharedInstance") -> @classAccessor singletonMethodName, get: -> @["_#{singletonMethodName}"] ||= new @ Batman.Object = BatmanObject class Batman.Accessible extends Batman.Object constructor: -> @accessor.apply(@, arguments) # Collections Batman.Enumerable = isEnumerable: true map: (f, ctx = container) -> r = []; @forEach(-> r.push f.apply(ctx, arguments)); r every: (f, ctx = container) -> r = true; @forEach(-> r = r && f.apply(ctx, arguments)); r some: (f, ctx = container) -> r = false; @forEach(-> r = r || f.apply(ctx, arguments)); r reduce: (f, r) -> count = 0 self = @ @forEach -> if r? then r = f(r, arguments..., count, self) else r = arguments[0] r filter: (f) -> r = new @constructor if r.add wrap = (r, e) -> r.add(e) if f(e); r else if r.set wrap = (r, k, v) -> r.set(k, v) if f(k, v); r else r = [] unless r.push wrap = (r, e) -> r.push(e) if f(e); r @reduce wrap, r # Provide this simple mixin ability so that during bootstrapping we don't have to use `$mixin`. `$mixin` # will correctly attempt to use `set` on the mixinee, which ends up requiring the definition of # `SimpleSet` to be complete during its definition. $extendsEnumerable = (onto) -> onto[k] = v for k,v of Batman.Enumerable class Batman.SimpleHash constructor: -> @_storage = {} @length = 0 $extendsEnumerable(@::) propertyClass: Batman.Property hasKey: (key) -> if pairs = @_storage[key] for pair in pairs return true if @equality(pair[0], key) return false get: (key) -> if pairs = @_storage[key] for pair in pairs return pair[1] if @equality(pair[0], key) set: (key, val) -> pairs = @_storage[key] ||= [] for pair in pairs if @equality(pair[0], key) return pair[1] = val @length++ pairs.push([key, val]) val unset: (key) -> if pairs = @_storage[key] for [obj,value], index in pairs if @equality(obj, key) pairs.splice(index,1) @length-- return getOrSet: Batman.Observable.getOrSet equality: (lhs, rhs) -> return true if lhs is rhs return true if lhs isnt lhs and rhs isnt rhs # when both are NaN return true if lhs?.isEqual?(rhs) and rhs?.isEqual?(lhs) return false forEach: (iterator) -> for key, values of @_storage iterator(obj, value) for [obj, value] in values keys: -> result = [] # Explicitly reference this foreach so that if it's overriden in subclasses the new implementation isn't used. Batman.SimpleHash::forEach.call @, (obj) -> result.push obj result clear: -> @_storage = {} @length = 0 isEmpty: -> @length is 0 merge: (others...) -> merged = new @constructor others.unshift(@) for hash in others hash.forEach (obj, value) -> merged.set obj, value merged class Batman.Hash extends Batman.Object constructor: -> Batman.SimpleHash.apply(@, arguments) # Add a meta object to all hashes which we can then use in the `meta` filter to allow binding # to hash meta-properties without reserving keys. @meta = new Batman.Object(length: 0) self = this @meta.accessor 'isEmpty', -> self.isEmpty() @meta.accessor 'keys', -> self.keys() super $extendsEnumerable(@::) propertyClass: Batman.Property @accessor get: Batman.SimpleHash::get set: -> results = Batman.SimpleHash::set.apply(@, arguments) @meta.set('length', @length) results unset: -> results = Batman.SimpleHash::unset.apply(@, arguments) @meta.set('length', @length) results for k in ['hasKey', 'equality', 'forEach', 'keys', 'isEmpty', 'merge'] @::[k] = Batman.SimpleHash::[k] clear: -> results = Batman.SimpleHash::clear.apply(@, arguments) @meta.set('length', @length) results class Batman.SimpleSet constructor: -> @_storage = new Batman.SimpleHash @_indexes = new Batman.SimpleHash @_sorts = new Batman.SimpleHash @length = 0 @add.apply @, arguments if arguments.length > 0 $extendsEnumerable(@::) has: (item) -> @_storage.hasKey item add: (items...) -> addedItems = [] for item in items unless @_storage.hasKey(item) @_storage.set item, true addedItems.push item @length++ @itemsWereAdded(addedItems...) unless addedItems.length is 0 addedItems remove: (items...) -> removedItems = [] for item in items if @_storage.hasKey(item) @_storage.unset item removedItems.push item @length-- @itemsWereRemoved(removedItems...) unless removedItems.length is 0 removedItems forEach: (iterator) -> @_storage.forEach (key, value) -> iterator(key) isEmpty: -> @length is 0 clear: -> items = @toArray() @_storage = new Batman.SimpleHash @length = 0 @itemsWereRemoved(items...) items toArray: -> @_storage.keys() merge: (others...) -> merged = new @constructor others.unshift(@) for set in others set.forEach (v) -> merged.add v merged indexedBy: (key) -> @_indexes.get(key) or @_indexes.set(key, new Batman.SetIndex(@, key)) sortedBy: (key) -> @_sorts.get(key) or @_sorts.set(key, new Batman.SetSort(@, key)) itemsWereAdded: -> itemsWereRemoved: -> class Batman.Set extends Batman.Object constructor: -> Batman.SimpleSet.apply @, arguments @set 'length', 0 $extendsEnumerable(@::) itemsWereAdded: @event -> itemsWereRemoved: @event -> for k in ['has', 'forEach', 'isEmpty', 'toArray', 'indexedBy', 'sortedBy'] @::[k] = Batman.SimpleSet::[k] for k in ['add', 'remove', 'clear', 'merge'] do (k) => @::[k] = -> oldLength = @length @prevent 'length' results = Batman.SimpleSet::[k].apply(@, arguments) [newLength, @length] = [@length, oldLength] @allow 'length' @set 'length', newLength if newLength != oldLength results @accessor 'indexedBy', -> new Batman.Accessible (key) => @indexedBy(key) @accessor 'sortedBy', -> new Batman.Accessible (key) => @sortedBy(key) @accessor 'isEmpty', -> @isEmpty() class Batman.SetObserver extends Batman.Object constructor: (@base) -> @_itemObservers = new Batman.Hash @_setObservers = new Batman.Hash @_setObservers.set("itemsWereAdded", @itemsWereAdded.bind(@)) @_setObservers.set("itemsWereRemoved", @itemsWereRemoved.bind(@)) @observe 'itemsWereAdded', @startObservingItems.bind(@) @observe 'itemsWereRemoved', @stopObservingItems.bind(@) itemsWereAdded: @event -> itemsWereRemoved: @event -> observedItemKeys: [] observerForItemAndKey: (item, key) -> _getOrSetObserverForItemAndKey: (item, key) -> @_itemObservers.getOrSet item, => observersByKey = new Batman.Hash observersByKey.getOrSet key, => @observerForItemAndKey(item, key) startObserving: -> @_manageItemObservers("observe") @_manageSetObservers("observe") stopObserving: -> @_manageItemObservers("forget") @_manageSetObservers("forget") startObservingItems: (items...) -> @_manageObserversForItem(item, "observe") for item in items stopObservingItems: (items...) -> @_manageObserversForItem(item, "forget") for item in items _manageObserversForItem: (item, method) -> return unless item.isObservable for key in @observedItemKeys item[method] key, @_getOrSetObserverForItemAndKey(item, key) @_itemObservers.unset(item) if method is "forget" _manageItemObservers: (method) -> @base.forEach (item) => @_manageObserversForItem(item, method) _manageSetObservers: (method) -> return unless @base.isObservable @_setObservers.forEach (key, observer) => @base[method](key, observer) class Batman.SetSort extends Batman.Object constructor: (@base, @key) -> if @base.isObservable @_setObserver = new Batman.SetObserver(@base) @_setObserver.observedItemKeys = [@key] boundReIndex = @_reIndex.bind(@) @_setObserver.observerForItemAndKey = -> boundReIndex @_setObserver.observe 'itemsWereAdded', boundReIndex @_setObserver.observe 'itemsWereRemoved', boundReIndex @startObserving() @_reIndex() startObserving: -> @_setObserver?.startObserving() stopObserving: -> @_setObserver?.stopObserving() toArray: -> @get('_storage') @accessor 'toArray', @::toArray forEach: (iterator) -> iterator(e,i) for e,i in @get('_storage') compare: (a,b) -> return 0 if a is b return 1 if a is undefined return -1 if b is undefined return 1 if a is null return -1 if b is null return 0 if a.isEqual?(b) and b.isEqual?(a) typeComparison = Batman.SetSort::compare($typeOf(a), $typeOf(b)) return typeComparison if typeComparison isnt 0 return 1 if a isnt a # means a is NaN return -1 if b isnt b # means b is NaN return 1 if a > b return -1 if a < b return 0 _reIndex: -> newOrder = @base.toArray().sort (a,b) => valueA = Batman.Observable.property.call(a, @key).getValue() valueA = valueA.valueOf() if valueA? valueB = Batman.Observable.property.call(b, @key).getValue() valueB = valueB.valueOf() if valueB? @compare.call(@, valueA, valueB) @_setObserver?.startObservingItems(newOrder...) @set('_storage', newOrder) class Batman.SetIndex extends Batman.Object constructor: (@base, @key) -> @_storage = new Batman.Hash if @base.isObservable @_setObserver = new Batman.SetObserver(@base) @_setObserver.observedItemKeys = [@key] @_setObserver.observerForItemAndKey = @observerForItemAndKey.bind(@) @_setObserver.observe 'itemsWereAdded', (items...) => @_addItem(item) for item in items @_setObserver.observe 'itemsWereRemoved', (items...) => @_removeItem(item) for item in items @base.forEach @_addItem.bind(@) @startObserving() @accessor (key) -> @_resultSetForKey(key) startObserving: ->@_setObserver?.startObserving() stopObserving: -> @_setObserver?.stopObserving() observerForItemAndKey: (item, key) -> (newValue, oldValue) => @_removeItemFromKey(item, oldValue) @_addItemToKey(item, newValue) _addItem: (item) -> @_addItemToKey(item, @_keyForItem(item)) _addItemToKey: (item, key) -> @_resultSetForKey(key).add item _removeItem: (item) -> @_removeItemFromKey(item, @_keyForItem(item)) _removeItemFromKey: (item, key) -> @_resultSetForKey(key).remove item _resultSetForKey: (key) -> @_storage.getOrSet(key, -> new Batman.Set) _keyForItem: (item) -> Batman.Keypath.forBaseAndKey(item, @key).getValue() class Batman.UniqueSetIndex extends Batman.SetIndex constructor: -> @_uniqueIndex = new Batman.Hash super @accessor (key) -> @_uniqueIndex.get(key) _addItemToKey: (item, key) -> @_resultSetForKey(key).add item unless @_uniqueIndex.hasKey(key) @_uniqueIndex.set(key, item) _removeItemFromKey: (item, key) -> resultSet = @_resultSetForKey(key) resultSet.remove item if resultSet.length is 0 @_uniqueIndex.unset(key) else @_uniqueIndex.set(key, resultSet.toArray()[0]) class Batman.SortableSet extends Batman.Set constructor: -> super @_sortIndexes = {} @observe 'activeIndex', => @setWasSorted(@) setWasSorted: @event -> return false if @length is 0 for k in ['add', 'remove', 'clear'] do (k) => @::[k] = -> results = Batman.Set::[k].apply(@, arguments) @_reIndex() results addIndex: (index) -> @_reIndex(index) removeIndex: (index) -> @_sortIndexes[index] = null delete @_sortIndexes[index] @unset('activeIndex') if @activeIndex is index index forEach: (iterator) -> iterator(el) for el in @toArray() sortBy: (index) -> @addIndex(index) unless @_sortIndexes[index] @set('activeIndex', index) unless @activeIndex is index @ isSorted: -> @_sortIndexes[@get('activeIndex')]? toArray: -> @_sortIndexes[@get('activeIndex')] || super _reIndex: (index) -> if index [keypath, ordering] = index.split ' ' ary = Batman.Set.prototype.toArray.call @ @_sortIndexes[index] = ary.sort (a,b) -> valueA = (Batman.Observable.property.call(a, keypath)).getValue()?.valueOf() valueB = (Batman.Observable.property.call(b, keypath)).getValue()?.valueOf() [valueA, valueB] = [valueB, valueA] if ordering?.toLowerCase() is 'desc' if valueA < valueB then -1 else if valueA > valueB then 1 else 0 @setWasSorted(@) if @activeIndex is index else @_reIndex(index) for index of @_sortIndexes @setWasSorted(@) @ # State Machines # -------------- Batman.StateMachine = { initialize: -> Batman.initializeObject @ if not @_batman.states @_batman.states = new Batman.SimpleHash state: (name, callback) -> Batman.StateMachine.initialize.call @ if not name return @_batman.getFirst 'state' developer.assert @event, "StateMachine requires EventEmitter" event = @[name] || @event name, -> _stateMachine_setState.call(@, name); false event.call(@, callback) if typeof callback is 'function' event transition: (from, to, callback) -> Batman.StateMachine.initialize.call @ @state from @state to name = "#{from}->#{to}" transitions = @_batman.states event = transitions.get(name) || transitions.set(name, $event ->) event(callback) if callback event } # A special method to alias state machine methods to class methods Batman.Object.actsAsStateMachine = (includeInstanceMethods=true) -> Batman.StateMachine.initialize.call @ Batman.StateMachine.initialize.call @prototype @classState = -> Batman.StateMachine.state.apply @, arguments @state = -> @classState.apply @prototype, arguments @::state = @classState if includeInstanceMethods @classTransition = -> Batman.StateMachine.transition.apply @, arguments @transition = -> @classTransition.apply @prototype, arguments @::transition = @classTransition if includeInstanceMethods # This is cached here so it doesn't need to be recompiled for every setter _stateMachine_setState = (newState) -> Batman.StateMachine.initialize.call @ if @_batman.isTransitioning (@_batman.nextState ||= []).push(newState) return false @_batman.isTransitioning = yes oldState = @state() @_batman.state = newState if newState and oldState name = "#{oldState}->#{newState}" for event in @_batman.getAll((ancestor) -> ancestor._batman?.get('states')?.get(name)) if event event newState, oldState if newState @fire newState, newState, oldState @_batman.isTransitioning = no @[@_batman.nextState.shift()]() if @_batman.nextState?.length newState # App, Requests, and Routing # -------------------------- # `Batman.Request` is a normalizer for XHR requests in the Batman world. class Batman.Request extends Batman.Object @objectToFormData: (data) -> pairForList = (key, object, first = false) -> list = switch Batman.typeOf(object) when 'Object' list = for k, v of object pairForList((if first then k else "#{key}[#{k}]"), v) list.reduce((acc, list) -> acc.concat list , []) when 'Array' object.reduce((acc, element) -> acc.concat pairForList("#{key}[]", element) , []) else [[key, object]] formData = new FormData() for [key, val] in pairForList("", data, true) formData.append(key, val) formData url: '' data: '' method: 'get' formData: false response: null status: null # Set the content type explicitly for PUT and POST requests. contentType: 'application/x-www-form-urlencoded' # After the URL gets set, we'll try to automatically send # your request after a short period. If this behavior is # not desired, use @cancel() after setting the URL. @observeAll 'url', -> @_autosendTimeout = setTimeout (=> @send()), 0 loading: @event -> loaded: @event -> success: @event -> error: @event -> # `send` is implmented in the platform layer files. One of those must be required for # `Batman.Request` to be useful. send: () -> developer.error "Please source a dependency file for a request implementation" cancel: -> clearTimeout(@_autosendTimeout) if @_autosendTimeout # `Batman.App` manages requiring files and acts as a namespace for all code subclassing # Batman objects. class Batman.App extends Batman.Object # Require path tells the require methods which base directory to look in. @requirePath: '' # The require class methods (`controller`, `model`, `view`) simply tells # your app where to look for coffeescript source files. This # implementation may change in the future. @require: (path, names...) -> base = @requirePath + path for name in names @prevent 'run' path = base + '/' + name + '.coffee' # FIXME: don't hardcode this new Batman.Request url: path type: 'html' success: (response) => CoffeeScript.eval response # FIXME: under no circumstances should we be compiling coffee in # the browser. This can be fixed via a real deployment solution # to compile coffeescripts, such as Sprockets. @allow 'run' @run() # FIXME: this should only happen if the client actually called run. @ @controller: (names...) -> names = names.map (n) -> n + '_controller' @require 'controllers', names... @model: -> @require 'models', arguments... @view: -> @require 'views', arguments... # Layout is the base view that other views can be yielded into. The # default behavior is that when `app.run()` is called, a new view will # be created for the layout using the `document` node as its content. # Use `MyApp.layout = null` to turn off the default behavior. @layout: undefined # Call `MyApp.run()` to start up an app. Batman level initializers will # be run to bootstrap the application. @run: @eventOneShot -> if Batman.currentApp return if Batman.currentApp is @ Batman.currentApp.stop() return false if @hasRun Batman.currentApp = @ if typeof @dispatcher is 'undefined' @dispatcher ||= new Batman.Dispatcher @ if typeof @layout is 'undefined' @set 'layout', new Batman.View contexts: [@] node: document @get('layout').ready => @ready() if typeof @historyManager is 'undefined' and @dispatcher.routeMap @historyManager = Batman.historyManager = new Batman.HashHistory @ @historyManager.start() @hasRun = yes @ # The `MyApp.ready` event will fire once the app's layout view has finished rendering. This includes # partials, loops, and all the other deferred renders, but excludes data fetching. @ready: @eventOneShot -> true @stop: @eventOneShot -> @historyManager?.stop() Batman.historyManager = null @hasRun = no @ # Dispatcher # ---------- class Batman.Route extends Batman.Object # Route regexes courtesy of Backbone namedParam = /:([\w\d]+)/g splatParam = /\*([\w\d]+)/g queryParam = '(?:\\?.+)?' namedOrSplat = /[:|\*]([\w\d]+)/g escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g constructor: -> super @pattern = @url.replace(escapeRegExp, '\\$&') @regexp = new RegExp('^' + @pattern.replace(namedParam, '([^\/]*)').replace(splatParam, '(.*?)') + queryParam + '$') @namedArguments = [] while (array = namedOrSplat.exec(@pattern))? @namedArguments.push(array[1]) if array[1] @accessor 'action', get: -> return @action if @action if @options result = $mixin {}, @options if signature = result.signature components = signature.split('#') result.controller = components[0] result.action = components[1] || 'index' result.target = @dispatcher.get result.controller @set 'action', result set: (key, action) -> @action = action parameterize: (url) -> [url, query] = url.split '?' array = @regexp.exec(url)?.slice(1) params = url: url action = @get 'action' if typeof action is 'function' params.action = action else $mixin params, action if array for param, index in array params[@namedArguments[index]] = param if query for s in query.split '&' [key, value] = s.split '=' params[key] = value params dispatch: (url) -> if $typeOf(url) is 'String' params = @parameterize url $redirect('/404') if not (action = params.action) and url isnt '/404' return action(params) if typeof action is 'function' return params.target.dispatch(action, params) if params.target?.dispatch return params.target?[action](params) class Batman.Dispatcher extends Batman.Object constructor: (@app) -> @app.route @ @app.controllers = new Batman.Object for key, controller of @app continue unless controller?.prototype instanceof Batman.Controller @prepareController controller prepareController: (controller) -> name = helpers.underscore($functionName(controller).replace('Controller', '')) return unless name getter = -> @[name] = controller.get 'sharedController' @accessor name, getter @app.controllers.accessor name, getter register: (url, options) -> url = "/#{url}" if url.indexOf('/') isnt 0 route = if $typeOf(options) is 'Function' new Batman.Route url: url, action: options, dispatcher: @ else new Batman.Route url: url, options: options, dispatcher: @ @routeMap ||= {} @routeMap[url] = route findRoute: (url) -> url = "/#{url}" if url.indexOf('/') isnt 0 return route if (route = @routeMap[url]) for routeUrl, route of @routeMap return route if route.regexp.test(url) findUrl: (params) -> for url, route of @routeMap matches = no options = route.options if params.resource matches = options.resource is params.resource and options.action is params.action else action = route.get 'action' continue if typeof action is 'function' {controller, action} = action if controller is params.controller and action is (params.action || 'index') matches = yes continue if not matches for key, value of params url = url.replace new RegExp('[:|\*]' + key), value return url dispatch: (url) -> route = @findRoute(url) if route route.dispatch(url) else if url isnt '/404' $redirect('/404') @app.set 'currentURL', url # History Manager # --------------- class Batman.HistoryManager constructor: (@app) -> dispatch: (url) -> url = "/#{url}" if url.indexOf('/') isnt 0 @app.dispatcher.dispatch url url redirect: (url) -> if $typeOf(url) isnt 'String' url = @app.dispatcher.findUrl(url) @dispatch url class Batman.HashHistory extends Batman.HistoryManager HASH_PREFIX: '#!' start: => return if typeof window is 'undefined' return if @started @started = yes if 'onhashchange' of window $addEventListener window, 'hashchange', @parseHash else @interval = setInterval @parseHash, 100 @first = true Batman.currentApp.prevent 'ready' setTimeout @parseHash, 0 stop: => if @interval @interval = clearInterval @interval else $removeEventListener window, 'hashchange', @parseHash @started = no urlFor: (url) -> @HASH_PREFIX + url parseHash: => hash = window.location.hash.replace @HASH_PREFIX, '' return if hash is @cachedHash result = @dispatch (@cachedHash = hash) if @first Batman.currentApp.allow 'ready' Batman.currentApp.fire 'ready' @first = false result redirect: (params) -> url = super @cachedHash = url window.location.hash = @HASH_PREFIX + url Batman.redirect = $redirect = (url) -> Batman.historyManager?.redirect url # Route Declarators # ----------------- Batman.App.classMixin route: (url, signature, options={}) -> return if not url if url instanceof Batman.Dispatcher dispatcher = url for key, value of @_dispatcherCache dispatcher.register key, value @_dispatcherCache = null return dispatcher if $typeOf(signature) is 'String' options.signature = signature else if $typeOf(signature) is 'Function' options = signature else if signature $mixin options, signature @_dispatcherCache ||= {} @_dispatcherCache[url] = options root: (signature, options) -> @route '/', signature, options resources: (resource, options={}, callback) -> (callback = options; options = {}) if typeof options is 'function' resource = helpers.pluralize(resource) controller = options.controller || resource @route(resource, "#{controller}#index", resource: controller, action: 'index') unless options.index is false @route("#{resource}/new", "#{controller}#new", resource: controller, action: 'new') unless options.new is false @route("#{resource}/:id", "#{controller}#show", resource: controller, action: 'show') unless options.show is false @route("#{resource}/:id/edit", "#{controller}#edit", resource: controller, action: 'edit') unless options.edit is false if callback app = @ ops = collection: (collectionCallback) -> collectionCallback?.call route: (url, methodName) -> app.route "#{resource}/#{url}", "#{controller}##{methodName || url}" member: (memberCallback) -> memberCallback?.call route: (url, methodName) -> app.route "#{resource}/:id/#{url}", "#{controller}##{methodName || url}" callback.call ops redirect: $redirect # Controllers # ----------- class Batman.Controller extends Batman.Object @singleton 'sharedController' @beforeFilter: (nameOrFunction) -> Batman.initializeObject @ filters = @_batman.beforeFilters ||= [] filters.push(nameOrFunction) if filters.indexOf(nameOrFunction) is -1 @accessor 'controllerName', get: -> @_controllerName ||= helpers.underscore($functionName(@constructor).replace('Controller', '')) @afterFilter: (nameOrFunction) -> Batman.initializeObject @ filters = @_batman.afterFilters ||= [] filters.push(nameOrFunction) if filters.indexOf(nameOrFunction) is -1 @accessor 'action', get: -> @_currentAction set: (key, value) -> @_currentAction = value # You shouldn't call this method directly. It will be called by the dispatcher when a route is called. # If you need to call a route manually, use `$redirect()`. dispatch: (action, params = {}) -> params.controller ||= @get 'controllerName' params.action ||= action params.target ||= @ oldRedirect = Batman.historyManager?.redirect Batman.historyManager?.redirect = @redirect @_actedDuringAction = no @set 'action', action if filters = @constructor._batman?.get('beforeFilters') for filter in filters if typeof filter is 'function' then filter.call(@, params) else @[filter](params) developer.assert @[action], "Error! Controller action #{@get 'controllerName'}.#{action} couldn't be found!" @[action](params) if not @_actedDuringAction @render() if filters = @constructor._batman?.get('afterFilters') for filter in filters if typeof filter is 'function' then filter.call(@, params) else @[filter](params) delete @_actedDuringAction @set 'action', null Batman.historyManager?.redirect = oldRedirect redirectTo = @_afterFilterRedirect delete @_afterFilterRedirect $redirect(redirectTo) if redirectTo redirect: (url) => throw 'DoubleRedirectError' if @_actedDuringAction if @get 'action' @_actedDuringAction = yes @_afterFilterRedirect = url else if $typeOf(url) is 'Object' url.controller = @ if not url.controller $redirect url render: (options = {}) -> throw 'DoubleRenderError' if @_actedDuringAction @_actedDuringAction = yes return if options is false if not options.view options.source ||= helpers.underscore($functionName(@constructor).replace('Controller', '')) + '/' + @_currentAction + '.html' options.view = new Batman.View(options) if view = options.view Batman.currentApp?.prevent 'ready' view.contexts.push @ view.ready -> Batman.DOM.contentFor('main', view.get('node')) Batman.currentApp?.allow 'ready' Batman.currentApp?.fire 'ready' view # Models # ------ class Batman.Model extends Batman.Object # ## Model API # Override this property if your model is indexed by a key other than `id` @primaryKey: 'id' # Override this property to define the key which storage adapters will use to store instances of this model under. # - For RestStorage, this ends up being part of the url built to store this model # - For LocalStorage, this ends up being the namespace in localStorage in which JSON is stored @storageKey: null # Pick one or many mechanisms with which this model should be persisted. The mechanisms # can be already instantiated or just the class defining them. @persist: (mechanisms...) -> Batman.initializeObject @prototype storage = @::_batman.storage ||= [] results = for mechanism in mechanisms mechanism = if mechanism.isStorageAdapter then mechanism else new mechanism(@) storage.push mechanism mechanism if results.length > 1 results else results[0] # Encoders are the tiny bits of logic which manage marshalling Batman models to and from their # storage representations. Encoders do things like stringifying dates and parsing them back out again, # pulling out nested model collections and instantiating them (and JSON.stringifying them back again), # and marshalling otherwise un-storable object. @encode: (keys..., encoderOrLastKey) -> Batman.initializeObject @prototype @::_batman.encoders ||= new Batman.SimpleHash @::_batman.decoders ||= new Batman.SimpleHash switch $typeOf(encoderOrLastKey) when 'String' keys.push encoderOrLastKey when 'Function' encoder = encoderOrLastKey else encoder = encoderOrLastKey.encode decoder = encoderOrLastKey.decode encoder = @defaultEncoder.encode if typeof encoder is 'undefined' decoder = @defaultEncoder.decode if typeof decoder is 'undefined' for key in keys @::_batman.encoders.set(key, encoder) if encoder @::_batman.decoders.set(key, decoder) if decoder # Set up the unit functions as the default for both @defaultEncoder: encode: (x) -> x decode: (x) -> x # Attach encoders and decoders for the primary key, and update them if the primary key changes. @observe 'primaryKey', yes, (newPrimaryKey) -> @encode newPrimaryKey, {encode: false, decode: @defaultEncoder.decode} # Validations allow a model to be marked as 'valid' or 'invalid' based on a set of programmatic rules. # By validating our data before it gets to the server we can provide immediate feedback to the user about # what they have entered and forgo waiting on a round trip to the server. # `validate` allows the attachment of validations to the model on particular keys, where the validation is # either a built in one (by use of options to pass to them) or a custom one (by use of a custom function as # the second argument). Custom validators should have the signature `(errors, record, key, callback)`. They # should add strings to the `errors` set based on the record (maybe depending on the `key` they were attached # to) and then always call the callback. Again: the callback must always be called. @validate: (keys..., optionsOrFunction) -> Batman.initializeObject @prototype validators = @::_batman.validators ||= [] if typeof optionsOrFunction is 'function' # Given a function, use that as the actual validator, expecting it to conform to the API # the built in validators do. validators.push keys: keys callback: optionsOrFunction else # Given options, find the validations which match the given options, and add them to the validators # array. options = optionsOrFunction for validator in Validators if (matches = validator.matches(options)) delete options[match] for match in matches validators.push keys: keys validator: new validator(matches) # ### Query methods @classAccessor 'all', get: -> @load() if @::hasStorage() and @classState() not in ['loaded', 'loading'] @get('loaded') set: (k, v) -> @set('loaded', v) @classAccessor 'loaded', get: -> unless @all @all = new Batman.SortableSet @all.sortBy "id asc" @all set: (k, v) -> @all = v @classAccessor 'first', -> @get('all').toArray()[0] @classAccessor 'last', -> x = @get('all').toArray(); x[x.length - 1] @find: (id, callback) -> developer.assert callback, "Must call find with a callback!" record = new @(id) newRecord = @_mapIdentity(record) newRecord.load callback return newRecord # `load` fetches records from all sources possible @load: (options, callback) -> if $typeOf(options) is 'Function' callback = options options = {} developer.assert @::_batman.getAll('storage').length, "Can't load model #{$functionName(@)} without any storage adapters!" do @loading @::_doStorageOperation 'readAll', options, (err, records) => if err? callback?(err, []) else mappedRecords = (@_mapIdentity(record) for record in records) do @loaded callback?(err, mappedRecords) # `create` takes an attributes hash, creates a record from it, and saves it given the callback. @create: (attrs, callback) -> if !callback [attrs, callback] = [{}, attrs] obj = new this(attrs) obj.save(callback) obj # `findOrCreate` takes an attributes hash, optionally containing a primary key, and returns to you a saved record # representing those attributes, either from the server or from the identity map. @findOrCreate: (attrs, callback) -> record = new this(attrs) if record.isNew() record.save(callback) else foundRecord = @_mapIdentity(record) foundRecord.updateAttributes(attrs) callback(undefined, foundRecord) @_mapIdentity: (record) -> if typeof (id = record.get('id')) == 'undefined' || id == '' return record else existing = @get("loaded.indexedBy.id").get(id)?.toArray()[0] if existing existing.updateAttributes(record._batman.attributes || {}) return existing else @get('loaded').add(record) return record # ### Record API # Add a universally accessible accessor for retrieving the primrary key, regardless of which key its stored under. @accessor 'id', get: -> pk = @constructor.get('primaryKey') if pk == 'id' @id else @get(pk) set: (k, v) -> pk = @constructor.get('primaryKey') if pk == 'id' @id = v else @set(pk, v) # Add normal accessors for the dirty keys and errors attributes of a record, so these accesses don't fall to the # default accessor. @accessor 'dirtyKeys', 'errors', Batman.Property.defaultAccessor # Add an accessor for the internal batman state under `batmanState`, so that the `state` key can be a valid # attribute. @accessor 'batmanState' get: -> @state() set: (k, v) -> @state(v) # Add a default accessor to make models store their attributes under a namespace by default. @accessor get: (k) -> (@_batman.attributes ||= {})[k] || @[k] set: (k, v) -> (@_batman.attributes ||= {})[k] = v unset: (k) -> x = (@_batman.attributes ||={})[k] delete @_batman.attributes[k] x # New records can be constructed by passing either an ID or a hash of attributes (potentially # containing an ID) to the Model constructor. By not passing an ID, the model is marked as new. constructor: (idOrAttributes = {}) -> developer.assert @ instanceof Batman.Object, "constructors must be called with new" # We have to do this ahead of super, because mixins will call set which calls things on dirtyKeys. @dirtyKeys = new Batman.Hash @errors = new Batman.ErrorsHash # Find the ID from either the first argument or the attributes. if $typeOf(idOrAttributes) is 'Object' super(idOrAttributes) else super() @set('id', idOrAttributes) @empty() if not @state() # Override the `Batman.Observable` implementation of `set` to implement dirty tracking. set: (key, value) -> # Optimize setting where the value is the same as what's already been set. oldValue = @get(key) return if oldValue is value # Actually set the value and note what the old value was in the tracking array. result = super @dirtyKeys.set(key, oldValue) # Mark the model as dirty if isn't already. @dirty() unless @state() in ['dirty', 'loading', 'creating'] result updateAttributes: (attrs) -> @mixin(attrs) @ toString: -> "#{$functionName(@constructor)}: #{@get('id')}" # `toJSON` uses the various encoders for each key to grab a storable representation of the record. toJSON: -> obj = {} # Encode each key into a new object encoders = @_batman.get('encoders') unless !encoders or encoders.isEmpty() encoders.forEach (key, encoder) => val = @get key if typeof val isnt 'undefined' encodedVal = encoder(@get key) if typeof encodedVal isnt 'undefined' obj[key] = encodedVal obj # `fromJSON` uses the various decoders for each key to generate a record instance from the JSON # stored in whichever storage mechanism. fromJSON: (data) -> obj = {} decoders = @_batman.get('decoders') # If no decoders were specified, do the best we can to interpret the given JSON by camelizing # each key and just setting the values. if !decoders or decoders.isEmpty() for key, value of data obj[key] = value else # If we do have decoders, use them to get the data. decoders.forEach (key, decoder) -> obj[key] = decoder(data[key]) if data[key] # Mixin the buffer object to use optimized and event-preventing sets used by `mixin`. @mixin obj # Each model instance (each record) can be in one of many states throughout its lifetime. Since various # operations on the model are asynchronous, these states are used to indicate exactly what point the # record is at in it's lifetime, which can often be during a save or load operation. @actsAsStateMachine yes # Add the various states to the model. for k in ['empty', 'dirty', 'loading', 'loaded', 'saving', 'saved', 'creating', 'created', 'validating', 'validated', 'destroying', 'destroyed'] @state k for k in ['loading', 'loaded'] @classState k _doStorageOperation: (operation, options, callback) -> developer.assert @hasStorage(), "Can't #{operation} model #{$functionName(@constructor)} without any storage adapters!" mechanisms = @_batman.get('storage') for mechanism in mechanisms mechanism[operation] @, options, callback true hasStorage: -> (@_batman.get('storage') || []).length > 0 # `load` fetches the record from all sources possible load: (callback) => if @state() in ['destroying', 'destroyed'] callback?(new Error("Can't load a destroyed record!")) return do @loading @_doStorageOperation 'read', {}, (err, record) => unless err do @loaded record = @constructor._mapIdentity(record) callback?(err, record) # `save` persists a record to all the storage mechanisms added using `@persist`. `save` will only save # a model if it is valid. save: (callback) => if @state() in ['destroying', 'destroyed'] callback?(new Error("Can't save a destroyed record!")) return @validate (isValid, errors) => if !isValid callback?(errors) return creating = @isNew() do @saving do @creating if creating @_doStorageOperation (if creating then 'create' else 'update'), {}, (err, record) => unless err if creating do @created do @saved @dirtyKeys.clear() record = @constructor._mapIdentity(record) callback?(err, record) # `destroy` destroys a record in all the stores. destroy: (callback) => do @destroying @_doStorageOperation 'destroy', {}, (err, record) => unless err @constructor.get('all').remove(@) do @destroyed callback?(err) # `validate` performs the record level validations determining the record's validity. These may be asynchronous, # in which case `validate` has no useful return value. Results from asynchronous validations can be received by # listening to the `afterValidation` lifecycle callback. validate: (callback) -> oldState = @state() @errors.clear() do @validating finish = () => do @validated @[oldState]() callback?(@errors.length == 0, @errors) validators = @_batman.get('validators') || [] unless validators.length > 0 finish() else count = validators.length validationCallback = => if --count == 0 finish() for validator in validators v = validator.validator # Run the validator `v` or the custom callback on each key it validates by instantiating a new promise # and passing it to the appropriate function along with the key and the value to be validated. for key in validator.keys if v v.validateEach @errors, @, key, validationCallback else validator.callback @errors, @, key, validationCallback return isNew: -> typeof @get('id') is 'undefined' # `ErrorHash` is a simple subclass of `Hash` which makes it a bit easier to # manage the errors on a model. class Batman.ErrorsHash extends Batman.Hash constructor: -> super @meta.observe 'length', (newLength) => @length = newLength @meta.set 'messages', new Batman.Set # Define a default accessor to instantiate a set for any requested key. @accessor get: (key) -> unless set = Batman.SimpleHash::get.call(@, key) set = new Batman.Set set.observe 'itemsWereAdded', (items...) => @meta.set('length', @meta.get('length') + items.length) @meta.get('messages').add(items...) set.observe 'itemsWereRemoved', (items...) => @meta.set('length', @meta.get('length') - arguments.length) @meta.get('messages').remove(items...) Batman.SimpleHash::set.call(@, key, set) set set: -> developer.error "Can't set on an errors hash, use add instead!" unset: -> developer.error "Can't unset on an errors hash, use clear instead!" # Define a shorthand method for adding errors to a key. add: (key, error) -> @get(key).add(error) # Ensure any observers placed on the sets stay around by clearing the sets instead of the whole hash clear: -> @forEach (key, set) -> set.clear() @ class Batman.Validator extends Batman.Object constructor: (@options, mixins...) -> super mixins... validate: (record) -> developer.error "You must override validate in Batman.Validator subclasses." @options: (options...) -> Batman.initializeObject @ if @_batman.options then @_batman.options.concat(options) else @_batman.options = options @matches: (options) -> results = {} shouldReturn = no for key, value of options if ~@_batman?.options?.indexOf(key) results[key] = value shouldReturn = yes return results if shouldReturn Validators = Batman.Validators = [ class Batman.LengthValidator extends Batman.Validator @options 'minLength', 'maxLength', 'length', 'lengthWithin', 'lengthIn' constructor: (options) -> if range = (options.lengthIn or options.lengthWithin) options.minLength = range[0] options.maxLength = range[1] || -1 delete options.lengthWithin delete options.lengthIn super validateEach: (errors, record, key, callback) -> options = @options value = record.get(key) if options.minLength and value.length < options.minLength errors.add key, "#{key} must be at least #{options.minLength} characters" if options.maxLength and value.length > options.maxLength errors.add key, "#{key} must be less than #{options.maxLength} characters" if options.length and value.length isnt options.length errors.add key, "#{key} must be #{options.length} characters" callback() class Batman.PresenceValidator extends Batman.Validator @options 'presence' validateEach: (errors, record, key, callback) -> value = record.get(key) if @options.presence and !value? errors.add key, "#{key} must be present" callback() ] class Batman.StorageAdapter extends Batman.Object constructor: (model) -> super(model: model, modelKey: model.get('storageKey') || helpers.pluralize(helpers.underscore($functionName(model)))) isStorageAdapter: true @::_batman.check(@::) for k in ['all', 'create', 'read', 'readAll', 'update', 'destroy'] for time in ['before', 'after'] do (k, time) => key = <KEY>helpers.<KEY> @::[key] = (filter) -> @_batman.check(@) (@_batman["#{key}Filters"] ||= []).push filter before: (keys..., callback) -> @["before#{helpers.capitalize(k)}"](callback) for k in keys after: (keys..., callback) -> @["after#{helpers.capitalize(k)}"](callback) for k in keys _filterData: (prefix, action, data...) -> # Filter the data first with the beforeRead and then the beforeAll filters (@_batman.get("#{prefix}#{helpers.capitalize(action)}Filters") || []) .concat(@_batman.get("#{prefix}AllFilters") || []) .reduce( (filteredData, filter) => filter.call(@, filteredData) , data) getRecordFromData: (data) -> record = new @model() record.fromJSON(data) record $passError = (f) -> return (filterables) -> if filterables[0] filterables else err = filterables.shift() filterables = f.call(@, filterables) filterables.unshift(err) filterables class Batman.LocalStorage extends Batman.StorageAdapter constructor: -> if typeof window.localStorage is 'undefined' return null super @storage = localStorage @key_re = new RegExp("^#{@modelKey}(\\d+)$") @nextId = 1 @_forAllRecords (k, v) -> if matches = @key_re.exec(k) @nextId = Math.max(@nextId, parseInt(matches[1], 10) + 1) return @::before 'create', 'update', $passError ([record, options]) -> [JSON.stringify(record), options] @::after 'read', $passError ([record, attributes, options]) -> [record.fromJSON(JSON.parse(attributes)), attributes, options] _forAllRecords: (f) -> for i in [0...@storage.length] k = @storage.key(i) f.call(@, k, @storage.getItem(k)) getRecordFromData: (data) -> record = super @nextId = Math.max(@nextId, parseInt(record.get('id'), 10) + 1) record update: (record, options, callback) -> [err, recordToSave] = @_filterData('before', 'update', undefined, record, options) if !err id = record.get('id') if id? @storage.setItem(@modelKey + id, recordToSave) else err = new Error("Couldn't get record primary key.") callback(@_filterData('after', 'update', err, record, options)...) create: (record, options, callback) -> [err, recordToSave] = @_filterData('before', 'create', undefined, record, options) if !err id = record.get('id') || record.set('id', @nextId++) if id? key = @modelKey + id if @storage.getItem(key) err = new Error("Can't create because the record already exists!") else @storage.setItem(key, recordToSave) else err = new Error("Couldn't set record primary key on create!") callback(@_filterData('after', 'create', err, record, options)...) read: (record, options, callback) -> [err, record] = @_filterData('before', 'read', undefined, record, options) id = record.get('id') if !err if id? attrs = @storage.getItem(@modelKey + id) if !attrs err = new Error("Couldn't find record!") else err = new Error("Couldn't get record primary key.") callback(@_filterData('after', 'read', err, record, attrs, options)...) readAll: (_, options, callback) -> records = [] [err, options] = @_filterData('before', 'readAll', undefined, options) if !err @_forAllRecords (storageKey, data) -> if keyMatches = @key_re.exec(storageKey) records.push {data, id: keyMatches[1]} callback(@_filterData('after', 'readAll', err, records, options)...) @::after 'readAll', $passError ([allAttributes, options]) -> allAttributes = for attributes in allAttributes data = JSON.parse(attributes.data) data[@model.primaryKey] ||= parseInt(attributes.id, 10) data [allAttributes, options] @::after 'readAll', $passError ([allAttributes, options]) -> matches = [] for data in allAttributes match = true for k, v of options if data[k] != v match = false break if match matches.push data [matches, options] @::after 'readAll', $passError ([filteredAttributes, options]) -> [@getRecordFromData(data) for data in filteredAttributes, filteredAttributes, options] destroy: (record, options, callback) -> [err, record] = @_filterData 'before', 'destroy', undefined, record, options if !err id = record.get('id') if id? key = @modelKey + id if @storage.getItem key @storage.removeItem key else err = new Error("Can't delete nonexistant record!") else err = new Error("Can't delete record without an primary key!") callback(@_filterData('after', 'destroy', err, record, options)...) class Batman.RestStorage extends Batman.StorageAdapter defaultOptions: type: 'json' recordJsonNamespace: false collectionJsonNamespace: false constructor: -> super @recordJsonNamespace = helpers.singularize(@modelKey) @collectionJsonNamespace = helpers.pluralize(@modelKey) @::before 'create', 'update', $passError ([record, options]) -> json = record.toJSON() record = if @recordJsonNamespace x = {} x[@recordJsonNamespace] = json x else json [record, options] @::after 'create', 'read', 'update', $passError ([record, data, options]) -> data = data[@recordJsonNamespace] if data[@recordJsonNamespace] [record, data, options] @::after 'create', 'read', 'update', $passError ([record, data, options]) -> record.fromJSON(data) [record, data, options] optionsForRecord: (record, idRequired, callback) -> if record.url url = if typeof record.url is 'function' then record.url() else record.url else url = "/#{@modelKey}" if idRequired || !record.isNew() id = record.get('id') if !id? callback.call(@, new Error("Couldn't get record primary key!")) return url = url + "/" + id unless url callback.call @, new Error("Couldn't get model url!") else callback.call @, undefined, $mixin({}, @defaultOptions, {url}) optionsForCollection: (recordsOptions, callback) -> url = @model.url?() || @model.url || "/#{@modelKey}" unless url callback.call @, new Error("Couldn't get collection url!") else callback.call @, undefined, $mixin {}, @defaultOptions, {url, data: $mixin({}, @defaultOptions.data, recordsOptions)} create: (record, recordOptions, callback) -> @optionsForRecord record, false, (err, options) -> [err, data] = @_filterData('before', 'create', err, record, recordOptions) if err callback(err) return new Batman.Request $mixin options, data: data method: 'POST' success: (data) => callback(@_filterData('after', 'create', undefined, record, data, recordOptions)...) error: (error) => callback(@_filterData('after', 'create', error, record, error.request.get('response'), recordOptions)...) update: (record, recordOptions, callback) -> @optionsForRecord record, true, (err, options) -> [err, data] = @_filterData('before', 'update', err, record, recordOptions) if err callback(err) return new Batman.Request $mixin options, data: data method: 'PUT' success: (data) => callback(@_filterData('after', 'update', undefined, record, data, recordOptions)...) error: (error) => callback(@_filterData('after', 'update', error, record, error.request.get('response'), recordOptions)...) read: (record, recordOptions, callback) -> @optionsForRecord record, true, (err, options) -> [err, record, recordOptions] = @_filterData('before', 'read', err, record, recordOptions) if err callback(err) return new Batman.Request $mixin options, data: recordOptions method: 'GET' success: (data) => callback(@_filterData('after', 'read', undefined, record, data, recordOptions)...) error: (error) => callback(@_filterData('after', 'read', error, record, error.request.get('response'), recordOptions)...) readAll: (_, recordsOptions, callback) -> @optionsForCollection recordsOptions, (err, options) -> [err, recordsOptions] = @_filterData('before', 'readAll', err, recordsOptions) if err callback(err) return if recordsOptions && recordsOptions.url options.url = recordsOptions.url delete recordsOptions.url new Batman.Request $mixin options, data: recordsOptions method: 'GET' success: (data) => callback(@_filterData('after', 'readAll', undefined, data, recordsOptions)...) error: (error) => callback(@_filterData('after', 'readAll', error, error.request.get('response'), recordsOptions)...) @::after 'readAll', $passError ([data, options]) -> recordData = if data[@collectionJsonNamespace] then data[@collectionJsonNamespace] else data [recordData, data, options] @::after 'readAll', $passError ([recordData, serverData, options]) -> [@getRecordFromData(attributes) for attributes in recordData, serverData, options] destroy: (record, recordOptions, callback) -> @optionsForRecord record, true, (err, options) -> [err, record, recordOptions] = @_filterData('before', 'destroy', err, record, recordOptions) if err callback(err) return new Batman.Request $mixin options, method: 'DELETE' success: (data) => callback(@_filterData('after', 'destroy', undefined, record, data, recordOptions)...) error: (error) => callback(@_filterData('after', 'destroy', error, record, error.request.get('response'), recordOptions)...) # Views # ----------- # A `Batman.View` can function two ways: a mechanism to load and/or parse html files # or a root of a subclass hierarchy to create rich UI classes, like in Cocoa. class Batman.View extends Batman.Object constructor: (options) -> @contexts = [] super(options) # Support both `options.context` and `options.contexts` if context = @get('context') @contexts.push context @unset('context') viewSources = {} # Set the source attribute to an html file to have that file loaded. source: '' # Set the html to a string of html to have that html parsed. html: '' # Set an existing DOM node to parse immediately. node: null contentFor: null # Fires once a node is parsed. ready: @eventOneShot -> # Where to look for views on the server prefix: 'views' # Whenever the source changes we load it up asynchronously @observeAll 'source', -> setTimeout (=> @reloadSource()), 0 reloadSource: -> source = @get 'source' return if not source if viewSources[source] @set('html', viewSources[source]) else new Batman.Request url: url = "#{@prefix}/#{@source}" type: 'html' success: (response) => viewSources[source] = response @set('html', response) error: (response) -> throw new Error("Could not load view from #{url}") @observeAll 'html', (html) -> node = @node || document.createElement 'div' node.innerHTML = html @set('node', node) if @node isnt node @observeAll 'node', (node) -> return unless node @ready.fired = false if @_renderer @_renderer.forgetAll() # We use a renderer with the continuation style rendering engine to not # block user interaction for too long during the render. if node @_renderer = new Batman.Renderer( node, => content = @contentFor if typeof content is 'string' @contentFor = Batman.DOM._yields?[content] if @contentFor and node @contentFor.innerHTML = '' @contentFor.appendChild(node) , @contexts) @_renderer.rendered => @ready node # DOM Helpers # ----------- # `Batman.Renderer` will take a node and parse all recognized data attributes out of it and its children. # It is a continuation style parser, designed not to block for longer than 50ms at a time if the document # fragment is particularly long. class Batman.Renderer extends Batman.Object constructor: (@node, callback, contexts = []) -> super() @parsed callback if callback? @context = if contexts instanceof RenderContext then contexts else new RenderContext(contexts...) setTimeout @start, 0 start: => @startTime = new Date @parseNode @node resume: => @startTime = new Date @parseNode @resumeNode finish: -> @startTime = null @fire 'parsed' @fire 'rendered' forgetAll: -> parsed: @eventOneShot -> rendered: @eventOneShot -> bindingRegexp = /data\-(.*)/ sortBindings = (a, b) -> if a[0] == 'foreach' -1 else if b[0] == 'foreach' 1 else if a[0] == 'formfor' -1 else if b[0] == 'formfor' 1 else if a[0] == 'bind' -1 else if b[0] == 'bind' 1 else 0 parseNode: (node) -> if new Date - @startTime > 50 @resumeNode = node setTimeout @resume, 0 return if node.getAttribute and node.attributes bindings = for attr in node.attributes name = attr.nodeName.match(bindingRegexp)?[1] continue if not name if ~(varIndex = name.indexOf('-')) [name.substr(0, varIndex), name.substr(varIndex + 1), attr.value] else [name, attr.value] for readerArgs in bindings.sort(sortBindings) key = readerArgs[1] result = if readerArgs.length == 2 Batman.DOM.readers[readerArgs[0]]?(node, key, @context, @) else Batman.DOM.attrReaders[readerArgs[0]]?(node, key, readerArgs[2], @context, @) if result is false skipChildren = true break if (nextNode = @nextNode(node, skipChildren)) then @parseNode(nextNode) else @finish() nextNode: (node, skipChildren) -> if not skipChildren children = node.childNodes return children[0] if children?.length Batman.data(node, 'onParseExit')?() return if @node == node sibling = node.nextSibling return sibling if sibling nextParent = node while nextParent = nextParent.parentNode nextParent.onParseExit?() return if @node == nextParent parentSibling = nextParent.nextSibling return parentSibling if parentSibling return # Bindings are shortlived objects which manage the observation of any keypaths a `data` attribute depends on. # Bindings parse any keypaths which are filtered and use an accessor to apply the filters, and thus enjoy # the automatic trigger and dependency system that Batman.Objects use. class Binding extends Batman.Object # A beastly regular expression for pulling keypaths out of the JSON arguments to a filter. # It makes the following matches: # # + `foo` and `baz.qux` in `foo, "bar", baz.qux` # + `foo.bar.baz` in `true, false, "true", "false", foo.bar.baz` # + `true.bar` in `2, true.bar` # + `truesay` in truesay # + no matches in `"bar", 2, {"x":"y", "Z": foo.bar.baz}, "baz"` keypath_rx = /// (^|,) # Match either the start of an arguments list or the start of a space inbetween commas. \s* # Be insensitive to whitespace between the comma and the actual arguments. (?! # Use a lookahead to ensure we aren't matching true or false: (?:true|false) # Match either true or false ... \s* # and make sure that there's nothing else that comes after the true or false ... (?:$|,) # before the end of this argument in the list. ) ([a-zA-Z][\w\.]*) # Now that true and false can't be matched, match a dot delimited list of keys. \s* # Be insensitive to whitespace before the next comma or end of the filter arguments list. ($|,) # Match either the next comma or the end of the filter arguments list. ///g # A less beastly pair of regular expressions for pulling out the [] syntax `get`s in a binding string, and # dotted names that follow them. get_dot_rx = /(?:\]\.)(.+?)(?=[\[\.]|\s*\||$)/ get_rx = /(?!^\s*)\[(.*?)\]/g # The `filteredValue` which calculates the final result by reducing the initial value through all the filters. @accessor 'filteredValue', -> unfilteredValue = @get('unfilteredValue') ctx = @get('keyContext') if @get('key') if @filterFunctions.length > 0 developer.currentFilterContext = ctx developer.currentFilterStack = @renderContext result = @filterFunctions.reduce((value, fn, i) => # Get any argument keypaths from the context stored at parse time. args = @filterArguments[i].map (argument) -> if argument._keypath argument.context.get(argument._keypath) else argument # Apply the filter. args.unshift value fn.apply(ctx, args) , unfilteredValue) developer.currentFilterContext = null developer.currentFilterStack = null result else unfilteredValue # The `unfilteredValue` is whats evaluated each time any dependents change. @accessor 'unfilteredValue', -> # If we're working with an `@key` and not an `@value`, find the context the key belongs to so we can # hold a reference to it for passing to the `dataChange` and `nodeChange` observers. if k = @get('key') @get("keyContext.#{k}") else @get('value') # The `keyContext` accessor is @accessor 'keyContext', -> unless @_keyContext [unfilteredValue, @_keyContext] = @renderContext.findKey @key @_keyContext constructor: -> super # Pull out the key and filter from the `@keyPath`. @parseFilter() # Define the default observers. @nodeChange ||= (node, context) => if @key && @filterFunctions.length == 0 @get('keyContext').set @key, @node.value @dataChange ||= (value, node) -> Batman.DOM.valueForNode @node, value shouldSet = yes # And attach them. if @only in [false, 'nodeChange'] and Batman.DOM.nodeIsEditable(@node) Batman.DOM.events.change @node, => shouldSet = no @nodeChange(@node, @_keyContext || @value, @) shouldSet = yes # Observe the value of this binding's `filteredValue` and fire it immediately to update the node. if @only in [false, 'dataChange'] @observe 'filteredValue', yes, (value) => if shouldSet @dataChange(value, @node, @) @ parseFilter: -> # Store the function which does the filtering and the arguments (all except the actual value to apply the # filter to) in these arrays. @filterFunctions = [] @filterArguments = [] # Rewrite [] style gets, replace quotes to be JSON friendly, and split the string by pipes to see if there are any filters. keyPath = @keyPath keyPath = keyPath.replace(get_dot_rx, "]['$1']") while get_dot_rx.test(keyPath) # Stupid lack of lookbehind assertions... filters = keyPath.replace(get_rx, " | get $1 ").replace(/'/g, '"').split(/(?!")\s+\|\s+(?!")/) # The key will is always the first token before the pipe. try key = @parseSegment(orig = filters.shift())[0] catch e developer.warn e developer.error "Error! Couldn't parse keypath in \"#{orig}\". Parsing error above." if key and key._keypath @key = key._keypath else @value = key if filters.length while filterString = filters.shift() # For each filter, get the name and the arguments by splitting on the first space. split = filterString.indexOf(' ') if ~split filterName = filterString.substr(0, split) args = filterString.substr(split) else filterName = filterString # If the filter exists, grab it. if filter = Batman.Filters[filterName] @filterFunctions.push filter # Get the arguments for the filter by parsing the args as JSON, or # just pushing an placeholder array if args try @filterArguments.push @parseSegment(args) catch e developer.error "Bad filter arguments \"#{args}\"!" else @filterArguments.push [] else developer.error "Unrecognized filter '#{filterName}' in key \"#{@keyPath}\"!" # Map over each array of arguments to grab the context for any keypaths. @filterArguments = @filterArguments.map (argumentList) => argumentList.map (argument) => if argument._keypath # Discard the value (for the time being) and store the context for the keypath in `context`. [_, argument.context] = @renderContext.findKey argument._keypath argument # Turn a piece of a `data` keypath into a usable javascript object. # + replacing keypaths using the above regular expression # + wrapping the `,` delimited list in square brackets # + and `JSON.parse`ing them as an array. parseSegment: (segment) -> JSON.parse( "[" + segment.replace(keypath_rx, "$1{\"_keypath\": \"$2\"}$3") + "]" ) # The RenderContext class manages the stack of contexts accessible to a view during rendering. # Every, and I really mean every method which uses filters has to be defined in terms of a new # binding, or by using the RenderContext.bind method. This is so that the proper order of objects # is traversed and any observers are properly attached. class RenderContext constructor: (contexts...) -> @contexts = contexts @storage = new Batman.Object @defaultContexts = [@storage] @defaultContexts.push Batman.currentApp if Batman.currentApp findKey: (key) -> base = key.split('.')[0].split('|')[0].trim() for contexts in [@contexts, @defaultContexts] i = contexts.length while i-- context = contexts[i] if context.get? val = context.get(base) else val = context[base] if typeof val isnt 'undefined' # we need to pass the check if the basekey exists, even if the intermediary keys do not. return [$get(context, key), context] return [container.get(key), container] set: (args...) -> @storage.set(args...) push: (x) -> @contexts.push(x) pop: -> @contexts.pop() clone: -> context = new @constructor(@contexts...) newStorage = $mixin {}, @storage context.setStorage(newStorage) context setStorage: (storage) -> @defaultContexts[0] = storage # `BindingProxy` is a simple class which assists in allowing bound contexts to be popped to the top of # the stack. This happens when a `data-context` is descended into, for each iteration in a `data-foreach`, # and in other specific HTML bindings like `data-formfor`. `BindingProxy`s use accessors so that if the # value of the binding they proxy changes, the changes will be propagated to any thing observing it. # This is good because it allows `data-context` to take filtered keys and even filters which take # keypath arguments, calculate the context to descend into when any of those keys change, and importantly # expose a friendly `Batman.Object` interface for the rest of the `Binding` code to work with. @BindingProxy = class BindingProxy extends Batman.Object isBindingProxy: true # Take the `binding` which needs to be proxied, and optionally rest it at the `localKey` scope. constructor: (@binding, @localKey) -> if @localKey @accessor @localKey, -> @binding.get('filteredValue') else @accessor (key) -> @binding.get("filteredValue.#{key}") # Below are the two primitives that all the `Batman.DOM` helpers are composed of. # `addKeyToScopeForNode` takes a `node`, `key`, and optionally a `localName`. It creates a `Binding` to # the key (such that the key can contain filters and many keypaths in arguments), and then pushes the # bound value onto the stack of contexts for the given `node`. If `localName` is given, the bound value # is available using that identifier in child bindings. Otherwise, the value itself is pushed onto the # context stack and member properties can be accessed directly in child bindings. addKeyToScopeForNode: (node, key, localName) -> @bind(node, key, (value, node, binding) => @push new BindingProxy(binding, localName) , -> true ) # Pop the `BindingProxy` off the stack once this node has been parsed. Batman.data node, 'onParseExit', => @pop() # `bind` takes a `node`, a `key`, and observers for when the `dataChange`s and the `nodeChange`s. It # creates a `Binding` to the key (supporting filters and the context stack), which fires the observers # when appropriate. Note that `Binding` has default observers for `dataChange` and `nodeChange` that # will set node/object values if these observers aren't passed in here. # The optional `only` parameter can be used to create data-to-node-only or node-to-data-only bindings. If left unset, # both data-to-node (source) and node-to-data (target) events are observed. bind: (node, key, dataChange, nodeChange, only = false) -> return new Binding renderContext: @ keyPath: key node: node dataChange: dataChange nodeChange: nodeChange only: only Batman.DOM = { # `Batman.DOM.readers` contains the functions used for binding a node's value or innerHTML, showing/hiding nodes, # and any other `data-#{name}=""` style DOM directives. readers: { target: (node, key, context, renderer) -> Batman.DOM.readers.bind(node, key, context, renderer, 'nodeChange') source: (node, key, context, renderer) -> Batman.DOM.readers.bind(node, key, context, renderer, 'dataChange') bind: (node, key, context, renderer, only) -> switch node.nodeName.toLowerCase() when 'input' switch node.getAttribute('type') when 'checkbox' return Batman.DOM.attrReaders.bind(node, 'checked', key, context, renderer, only) when 'radio' return Batman.DOM.binders.radio(arguments...) when 'file' return Batman.DOM.binders.file(arguments...) when 'select' return Batman.DOM.binders.select(arguments...) # Fallback on the default nodeChange and dataChange observers in Binding context.bind(node, key, undefined, undefined, only) context: (node, key, context) -> context.addKeyToScopeForNode(node, key) mixin: (node, key, context) -> context.push(Batman.mixins) context.bind(node, key, (mixin) -> $mixin node, mixin , ->) context.pop() showif: (node, key, context, renderer, invert) -> originalDisplay = node.style.display || '' context.bind(node, key, (value) -> if !!value is !invert Batman.data(node, 'show')?.call(node) node.style.display = originalDisplay else if typeof (hide = Batman.data(node, 'hide')) == 'function' hide.call node else node.style.display = 'none' , -> ) hideif: (args...) -> Batman.DOM.readers.showif args..., yes route: (node, key, context) -> # you must specify the / in front to route directly to hash route if key.substr(0, 1) is '/' url = key else [key, action] = key.split '/' [dispatcher, app] = context.findKey 'dispatcher' [model, container] = context.findKey key dispatcher ||= Batman.currentApp.dispatcher if dispatcher and model instanceof Batman.Model action ||= 'show' name = helpers.underscore(helpers.pluralize($functionName(model.constructor))) url = dispatcher.findUrl({resource: name, id: model.get('id'), action: action}) else if model?.prototype # TODO write test for else case action ||= 'index' name = helpers.underscore(helpers.pluralize($functionName(model))) url = dispatcher.findUrl({resource: name, action: action}) return unless url if node.nodeName.toUpperCase() is 'A' node.href = Batman.HashHistory::urlFor url Batman.DOM.events.click node, (-> $redirect url) partial: (node, path, context, renderer) -> renderer.prevent('rendered') view = new Batman.View source: path + '.html' contentFor: node contexts: Array.prototype.slice.call(context.contexts) view.ready -> renderer.allow 'rendered' renderer.fire 'rendered' yield: (node, key) -> setTimeout (-> Batman.DOM.yield key, node), 0 contentfor: (node, key) -> setTimeout (-> Batman.DOM.contentFor key, node), 0 } # `Batman.DOM.attrReaders` contains all the DOM directives which take an argument in their name, in the # `data-dosomething-argument="keypath"` style. This means things like foreach, binding attributes like # disabled or anything arbitrary, descending into a context, binding specific classes, or binding to events. attrReaders: { _parseAttribute: (value) -> if value is 'false' then value = false if value is 'true' then value = true value source: (node, attr, key, context, renderer) -> Batman.DOM.attrReaders.bind node, attr, key, context, renderer, 'dataChange' bind: (node, attr, key, context, renderer, only) -> switch attr when 'checked', 'disabled', 'selected' dataChange = (value) -> node[attr] = !!value # Update the parent's binding if necessary Batman.data(node.parentNode, 'updateBinding')?() nodeChange = (node, subContext) -> subContext.set(key, Batman.DOM.attrReaders._parseAttribute(node[attr])) # Make the context and key available to the parent select Batman.data node, attr, context: context key: key when 'value', 'style', 'href', 'src', 'size' dataChange = (value) -> node[attr] = value nodeChange = (node, subContext) -> subContext.set(key, Batman.DOM.attrReaders._parseAttribute(node[attr])) when 'class' dataChange = (value) -> node.className = value nodeChange = (node, subContext) -> subContext.set key, node.className else dataChange = (value) -> node.setAttribute(attr, value) nodeChange = (node, subContext) -> subContext.set(key, Batman.DOM.attrReaders._parseAttribute(node.getAttribute(attr))) context.bind(node, key, dataChange, nodeChange, only) context: (node, contextName, key, context) -> context.addKeyToScopeForNode(node, key, contextName) event: (node, eventName, key, context) -> props = callback: null subContext: null context.bind node, key, (value, node, binding) -> props.callback = value if binding.get('key') ks = binding.get('key').split('.') ks.pop() if ks.length > 0 props.subContext = binding.get('keyContext').get(ks.join('.')) else props.subContext = binding.get('keyContext') , -> confirmText = node.getAttribute('data-confirm') Batman.DOM.events[eventName] node, -> if confirmText and not confirm(confirmText) return props.callback?.apply props.subContext, arguments addclass: (node, className, key, context, parentRenderer, invert) -> className = className.replace(/\|/g, ' ') #this will let you add or remove multiple class names in one binding context.bind node, key, (value) -> currentName = node.className includesClassName = currentName.indexOf(className) isnt -1 if !!value is !invert node.className = "#{currentName} #{className}" if !includesClassName else node.className = currentName.replace(className, '') if includesClassName , -> removeclass: (args...) -> Batman.DOM.attrReaders.addclass args..., yes foreach: (node, iteratorName, key, context, parentRenderer) -> prototype = node.cloneNode true prototype.removeAttribute "data-foreach-#{iteratorName}" parent = node.parentNode sibling = node.nextSibling # Remove the original node once the parent has moved past it. parentRenderer.parsed -> parent.removeChild node # Get a hash keyed by collection item with the nodes representing that item as values nodeMap = new Batman.SimpleHash fragment = document.createDocumentFragment() numPendingChildren = 0 observers = {} oldCollection = false context.bind(node, key, (collection) -> # Track the old collection so that if it changes, we can remove the observers we attached, # and only observe the new collection. if oldCollection return if collection == oldCollection nodeMap.forEach (item, node) -> node.parentNode?.removeChild node nodeMap.clear() if oldCollection.forget oldCollection.forget 'itemsWereAdded', observers.add oldCollection.forget 'itemsWereRemoved', observers.remove oldCollection.forget 'setWasSorted', observers.reorder oldCollection = collection observers.add = (items...) -> numPendingChildren += items.length for item in items parentRenderer.prevent 'rendered' newNode = prototype.cloneNode true nodeMap.set item, newNode localClone = context.clone() iteratorContext = new Batman.Object iteratorContext[iteratorName] = item localClone.push iteratorContext childRenderer = new Batman.Renderer newNode, do (newNode) -> -> if typeof (show = Batman.data(newNode, 'show')) == 'function' show.call newNode, before: sibling else fragment.appendChild newNode if --numPendingChildren == 0 parent.insertBefore fragment, sibling if collection.isSorted?() observers.reorder() fragment = document.createDocumentFragment() , localClone childRenderer.rendered => parentRenderer.allow 'rendered' parentRenderer.fire 'rendered' observers.remove = (items...) -> for item in items oldNode = nodeMap.get item nodeMap.unset item if oldNode? && typeof oldNode.hide is 'function' oldNode.hide yes else oldNode?.parentNode?.removeChild oldNode true observers.reorder = -> items = collection.toArray() for item in items thisNode = nodeMap.get(item) show = Batman.data thisNode, 'show' if typeof show is 'function' show.call thisNode, before: sibling else parent.insertBefore(thisNode, sibling) observers.arrayChange = (array) -> observers.remove(array...) observers.add(array...) # Observe the collection for events in the future if collection if collection.observe collection.observe 'itemsWereAdded', observers.add collection.observe 'itemsWereRemoved', observers.remove if collection.setWasSorted collection.observe 'setWasSorted', observers.reorder else collection.observe 'toArray', observers.arrayChange # Add all the already existing items. For hash-likes, add the key. if collection.forEach collection.forEach (item) -> observers.add(item) else if collection.get && array = collection.get('toArray') observers.add(array...) else for k, v of collection observers.add(k) else developer.warn "Warning! data-foreach-#{iteratorName} called with an undefined binding. Key was: #{key}." , -> ) false # Return false so the Renderer doesn't descend into this node's children. formfor: (node, localName, key, context) -> binding = context.addKeyToScopeForNode(node, key, localName) Batman.DOM.events.submit node, (node, e) -> $preventDefault e } # `Batman.DOM.binders` contains functions used to create element bindings # These are called via `Batman.DOM.readers` or `Batman.DOM.attrReaders` binders: { select: (node, key, context, renderer, only) -> [boundValue, container] = context.findKey key updateSelectBinding = => # Gather the selected options and update the binding selections = if node.multiple then (c.value for c in node.children when c.selected) else node.value selections = selections[0] if selections.length == 1 container.set key, selections updateOptionBindings = => # Go through the option nodes and update their bindings using the # context and key attached to the node via Batman.data for child in node.children if data = Batman.data(child, 'selected') if (subContext = data.context) and (subKey = data.key) [subBoundValue, subContainer] = subContext.findKey subKey unless child.selected == subBoundValue subContainer.set subKey, child.selected # wait for the select to render before binding to it renderer.rendered -> # Update the select box with the binding's new value. dataChange = (newValue) -> # For multi-select boxes, the `value` property only holds the first # selection, so we need to go through the child options and update # as necessary. if newValue instanceof Array # Use a hash to map values to their nodes to avoid O(n^2). valueToChild = {} for child in node.children # Clear all options. child.selected = false # Avoid collisions among options with same values. matches = valueToChild[child.value] if matches then matches.push child else matches = [child] valueToChild[child.value] = matches # Select options corresponding to the new values for value in newValue for match in valueToChild[value] match.selected = yes # For a regular select box, we just update the value. else node.value = newValue # Finally, we need to update the options' `selected` bindings updateOptionBindings() # Update the bindings with the node's new value nodeChange = -> updateSelectBinding() updateOptionBindings() # Expose the updateSelectBinding helper for the child options Batman.data node, 'updateBinding', updateSelectBinding # Create the binding context.bind node, key, dataChange, nodeChange, only radio: (node, key, context, renderer, only) -> dataChange = (value) -> # don't overwrite `checked` attributes in the HTML unless a bound # value is defined in the context. if no bound value is found, bind # to the key if the node is checked. [boundValue, container] = context.findKey key if boundValue node.checked = boundValue == node.value else if node.checked container.set key, node.value nodeChange = (newNode, subContext) -> subContext.set(key, Batman.DOM.attrReaders._parseAttribute(node.value)) context.bind node, key, dataChange, nodeChange, only file: (node, key, context, renderer, only) -> context.bind(node, key, -> developer.warn "Can't write to file inputs! Tried to on key #{key}." , (node, subContext) -> if subContext instanceof RenderContext.BindingProxy actualObject = subContext.binding.get('filteredValue') else actualObject = subContext if actualObject.hasStorage && actualObject.hasStorage() for adapter in actualObject._batman.get('storage') when adapter instanceof Batman.RestStorage adapter.defaultOptions.formData = true if node.hasAttribute('multiple') subContext.set key, Array::slice.call(node.files) else subContext.set key, node.files[0] , only) } # `Batman.DOM.events` contains the helpers used for binding to events. These aren't called by # DOM directives, but are used to handle specific events by the `data-event-#{name}` helper. events: { click: (node, callback, eventName = 'click') -> $addEventListener node, eventName, (args...) -> callback node, args... $preventDefault args[0] if node.nodeName.toUpperCase() is 'A' and not node.href node.href = '#' node doubleclick: (node, callback) -> Batman.DOM.events.click node, callback, 'dblclick' change: (node, callback) -> eventNames = switch node.nodeName.toUpperCase() when 'TEXTAREA' then ['keyup', 'change'] when 'INPUT' if node.type.toUpperCase() is 'TEXT' oldCallback = callback callback = (e) -> return if e.type == 'keyup' && 13 <= e.keyCode <= 14 oldCallback(arguments...) ['keyup', 'change'] else ['change'] else ['change'] for eventName in eventNames $addEventListener node, eventName, (args...) -> callback node, args... submit: (node, callback) -> if Batman.DOM.nodeIsEditable(node) $addEventListener node, 'keyup', (args...) -> if args[0].keyCode is 13 || args[0].which is 13 || args[0].keyIdentifier is 'Enter' || args[0].key is 'Enter' $preventDefault args[0] callback node, args... else $addEventListener node, 'submit', (args...) -> $preventDefault args[0] callback node, args... node } # `yield` and `contentFor` are used to declare partial views and then pull them in elsewhere. # This can be used for abstraction as well as repetition. yield: (name, node) -> yields = Batman.DOM._yields ||= {} yields[name] = node if (content = Batman.DOM._yieldContents?[name]) node.innerHTML = '' node.appendChild(content) if content contentFor: (name, node) -> contents = Batman.DOM._yieldContents ||= {} contents[name] = node if (yield = Batman.DOM._yields?[name]) content = if $isChildOf(yield, node) then node.cloneNode(true) else node yield.innerHTML = '' yield.appendChild(content) if content valueForNode: (node, value = '') -> isSetting = arguments.length > 1 switch node.nodeName.toUpperCase() when 'INPUT' if isSetting then (node.value = value) else node.value when 'TEXTAREA' if isSetting node.innerHTML = node.value = value else node.innerHTML when 'SELECT' node.value = value else if isSetting then (node.innerHTML = value) else node.innerHTML nodeIsEditable: (node) -> node.nodeName.toUpperCase() in ['INPUT', 'TEXTAREA', 'SELECT'] # `$addEventListener uses attachEvent when necessary addEventListener: $addEventListener = if window?.addEventListener ((node, eventName, callback) -> node.addEventListener eventName, callback, false) else ((node, eventName, callback) -> node.attachEvent "on#{eventName}", callback) # `$removeEventListener` uses detachEvent when necessary removeEventListener: $removeEventListener = if window?.removeEventListener ((elem, eventType, handler) -> elem.removeEventListener eventType, handler, false) else ((elem, eventType, handler) -> elem.detachEvent 'on'+eventType, handler) } # Filters # ------- # # `Batman.Filters` contains the simple, determininistic tranforms used in view bindings to # make life a little easier. buntUndefined = (f) -> (value) -> if typeof value is 'undefined' undefined else f.apply(@, arguments) filters = Batman.Filters = get: buntUndefined (value, key) -> if value.get? value.get(key) else value[key] equals: buntUndefined (lhs, rhs) -> lhs is rhs not: (value) -> ! !!value truncate: buntUndefined (value, length, end = "...") -> if value.length > length value = value.substr(0, length-end.length) + end value default: (value, string) -> value || string prepend: (value, string) -> string + value append: (value, string) -> value + string downcase: buntUndefined (value) -> value.toLowerCase() upcase: buntUndefined (value) -> value.toUpperCase() pluralize: buntUndefined (string, count) -> helpers.pluralize(count, string) join: buntUndefined (value, byWhat = '') -> value.join(byWhat) sort: buntUndefined (value) -> value.sort() map: buntUndefined (value, key) -> value.map((x) -> x[key]) first: buntUndefined (value) -> value[0] meta: buntUndefined (value, keypath) -> value.meta.get(keypath) for k in ['capitalize', 'singularize', 'underscore', 'camelize'] filters[k] = buntUndefined helpers[k] developer.addFilters() # Data # ---- $mixin Batman, cache: {} uuid: 0 expando: "batman" + Math.random().toString().replace(/\D/g, '') canDeleteExpando: true noData: # these throw exceptions if you attempt to add expandos to them "embed": true, # Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true hasData: (elem) -> elem = (if elem.nodeType then Batman.cache[elem[Batman.expando]] else elem[Batman.expando]) !!elem and !isEmptyDataObject(elem) data: (elem, name, data, pvt) -> # pvt is for internal use only return unless Batman.acceptData(elem) internalKey = Batman.expando getByName = typeof name == "string" # DOM nodes and JS objects have to be handled differently because IE6-7 can't # GC object references properly across the DOM-JS boundary isNode = elem.nodeType # Only DOM nodes need the global cache; JS object data is attached directly so GC # can occur automatically cache = if isNode then Batman.cache else elem # Only defining an ID for JS objects if its cache already exists allows # the code to shortcut on the same path as a DOM node with no cache id = if isNode then elem[Batman.expando] else elem[Batman.expando] && Batman.expando # Avoid doing any more work than we need to when trying to get data on an # object that has no data at all if (not id or (pvt and id and (cache[id] and not cache[id][internalKey]))) and getByName and data == undefined return unless id # Only DOM nodes need a new unique ID for each element since their data # ends up in the global cache if isNode elem[Batman.expando] = id = ++Batman.uuid else id = Batman.expando cache[id] = {} unless cache[id] # An object can be passed to Batman.data instead of a key/value pair; this gets # shallow copied over onto the existing cache if typeof name == "object" or typeof name == "function" if pvt cache[id][internalKey] = $mixin(cache[id][internalKey], name) else cache[id] = $mixin(cache[id], name) thisCache = cache[id] # Internal Batman data is stored in a separate object inside the object's data # cache in order to avoid key collisions between internal data and user-defined # data if pvt thisCache[internalKey] = {} unless thisCache[internalKey] thisCache = thisCache[internalKey] unless data is undefined thisCache[helpers.camelize(name, true)] = data # Check for both converted-to-camel and non-converted data property names # If a data property was specified if getByName # First try to find as-is property data ret = thisCache[name] # Test for null|undefined property data and try to find camel-cased property ret = thisCache[helpers.camelize(name, true)] unless ret? else ret = thisCache return ret removeData: (elem, name, pvt) -> # pvt is for internal use only return unless Batman.acceptData(elem) internalKey = Batman.expando isNode = elem.nodeType # non DOM-nodes have their data attached directly cache = if isNode then Batman.cache else elem id = if isNode then elem[Batman.expando] else Batman.expando # If there is already no cache entry for this object, there is no # purpose in continuing return unless cache[id] if name thisCache = if pvt then cache[id][internalKey] else cache[id] if thisCache # Support interoperable removal of hyphenated or camelcased keys name = helpers.camelize(name, true) unless thisCache[name] delete thisCache[name] # If there is no data left in the cache, we want to continue # and let the cache object itself get destroyed return unless isEmptyDataObject(thisCache) if pvt delete cache[id][internalKey] # Don't destroy the parent cache unless the internal data object # had been the only thing left in it return unless isEmptyDataObject(cache[id]) internalCache = cache[id][internalKey] # Browsers that fail expando deletion also refuse to delete expandos on # the window, but it will allow it on all other JS objects; other browsers # don't care # Ensure that `cache` is not a window object if Batman.canDeleteExpando or !cache.setInterval delete cache[id] else cache[id] = null # We destroyed the entire user cache at once because it's faster than # iterating through each key, but we need to continue to persist internal # data if it existed if internalCache cache[id] = {} cache[id][internalKey] = internalCache # Otherwise, we need to eliminate the expando on the node to avoid # false lookups in the cache for entries that no longer exist else if isNode if Batman.canDeleteExpando delete elem[Batman.expando] else if elem.removeAttribute elem.removeAttribute Batman.expando else elem[Batman.expando] = null # For internal use only _data: (elem, name, data) -> Batman.data elem, name, data, true # A method for determining if a DOM node can handle the data expando acceptData: (elem) -> if elem.nodeName match = Batman.noData[elem.nodeName.toLowerCase()] if match return !(match == true or elem.getAttribute("classid") != match) return true isEmptyDataObject = (obj) -> for name of obj return false return true # Test to see if it's possible to delete an expando from an element # Fails in Internet Explorer try div = document.createElement 'div' delete div.test catch e Batman.canDeleteExpando = false # Mixins # ------ mixins = Batman.mixins = new Batman.Object() # Encoders # ------ Batman.Encoders = railsDate: encode: (value) -> value decode: (value) -> a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value) if a return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])) else developer.error "Unrecognized rails date #{value}!" # Export a few globals, and grab a reference to an object accessible from all contexts for use elsewhere. # In node, the container is the `global` object, and in the browser, the container is the window object. container = if exports? module.exports = Batman global else window.Batman = Batman window $mixin container, Batman.Observable # Optionally export global sugar. Not sure what to do with this. Batman.exportHelpers = (onto) -> for k in ['mixin', 'unmixin', 'route', 'redirect', 'event', 'eventOneShot', 'typeOf', 'redirect'] onto["$#{k}"] = Batman[k] onto Batman.exportGlobals = () -> Batman.exportHelpers(container)
true
# # batman.js # # Created by PI:NAME:<NAME>END_PI # Copyright 2011, Shopify # # The global namespace, the `Batman` function will also create also create a new # instance of Batman.Object and mixin all arguments to it. Batman = (mixins...) -> new Batman.Object mixins... # Global Helpers # ------- # `$typeOf` returns a string that contains the built-in class of an object # like `String`, `Array`, or `Object`. Note that only `Object` will be returned for # the entire prototype chain. Batman.typeOf = $typeOf = (object) -> return "Undefined" if typeof object == 'undefined' _objectToString.call(object).slice(8, -1) # Cache this function to skip property lookups. _objectToString = Object.prototype.toString # `$mixin` applies every key from every argument after the first to the # first argument. If a mixin has an `initialize` method, it will be called in # the context of the `to` object, and it's key/values won't be applied. Batman.mixin = $mixin = (to, mixins...) -> hasSet = typeof to.set is 'function' for mixin in mixins continue if $typeOf(mixin) isnt 'Object' for own key, value of mixin continue if key in ['initialize', 'uninitialize', 'prototype'] if hasSet to.set(key, value) else if to.nodeName? Batman.data to, key, value else to[key] = value if typeof mixin.initialize is 'function' mixin.initialize.call to to # `$unmixin` removes every key/value from every argument after the first # from the first argument. If a mixin has a `deinitialize` method, it will be # called in the context of the `from` object and won't be removed. Batman.unmixin = $unmixin = (from, mixins...) -> for mixin in mixins for key of mixin continue if key in ['initialize', 'uninitialize'] delete from[key] if typeof mixin.uninitialize is 'function' mixin.uninitialize.call from from # `$block` takes in a function and returns a function which can either # A) take a callback as its last argument as it would normally, or # B) accept a callback as a second function application. # This is useful so that multiline functions can be passed as callbacks # without the need for wrapping brackets (which a CoffeeScript bug # requires them to have). `$block` also takes an optional function airity # argument as the first argument. If a `length` argument is given, and `length` # or more arguments are passed, `$block` will call the second argument # (the function) with the passed arguments, regardless of their type. # Example: # With a function that accepts a callback as its last argument # # f = (a, b, callback) -> callback(a + b) # ex = $block f # # We can use $block to make it accept the callback in both ways: # # ex(2, 3, (x) -> alert(x)) # alerts 5 # # or # # ex(2, 3) (x) -> alert(x) # Batman._block = $block = (lengthOrFunction, fn) -> if fn? argsLength = lengthOrFunction else fn = lengthOrFunction callbackEater = (args...) -> ctx = @ f = (callback) -> args.push callback fn.apply(ctx, args) # Call the function right now if we've been passed the callback already or if we've reached the argument count threshold if (typeof args[args.length-1] is 'function') || (argsLength && (args.length >= argsLength)) f(args.pop()) else f # `findName` allows an anonymous function to find out what key it resides # in within a context. Batman._findName = $findName = (f, context) -> unless f.displayName for key, value of context if value is f f.displayName = key break f.displayName # `$functionName` returns the name of a given function, if any # Used to deal with functions not having the `name` property in IE Batman._functionName = $functionName = (f) -> return f.__name__ if f.__name__ return f.name if f.name f.toString().match(/\W*function\s+([\w\$]+)\(/)?[1] # `$preventDefault` checks for preventDefault, since it's not # always available across all browsers Batman._preventDefault = $preventDefault = (e) -> if typeof e.preventDefault is "function" then e.preventDefault() else e.returnValue = false Batman._isChildOf = $isChildOf = (parentNode, childNode) -> node = childNode.parentNode while node return true if node == parentNode node = node.parentNode false # Developer Tooling # ----------------- developer = DevelopmentError: (-> DevelopmentError = (@message) -> @name = "DevelopmentError" DevelopmentError:: = Error:: DevelopmentError )() _ie_console: (f, args) -> console?[f] "...#{f} of #{args.length} items..." unless args.length == 1 console?[f] arg for arg in args log: -> return unless console?.log? if console.log.apply then console.log(arguments...) else developer._ie_console "log", arguments warn: -> return unless console?.warn? if console.warn.apply then console.warn(arguments...) else developer._ie_console "warn", arguments error: (message) -> throw new developer.DevelopmentError(message) assert: (result, message) -> developer.error(message) unless result addFilters: -> $mixin Batman.Filters, log: (value, key) -> console?.log? arguments value logStack: (value) -> console?.log? developer.currentFilterStack value logContext: (value) -> console?.log? developer.currentFilterContext value Batman.developer = developer # Helpers # ------- camelize_rx = /(?:^|_|\-)(.)/g capitalize_rx = /(^|\s)([a-z])/g underscore_rx1 = /([A-Z]+)([A-Z][a-z])/g underscore_rx2 = /([a-z\d])([A-Z])/g # Just a few random Rails-style string helpers. You can add more # to the Batman.helpers object. helpers = Batman.helpers = { camelize: (string, firstLetterLower) -> string = string.replace camelize_rx, (str, p1) -> p1.toUpperCase() if firstLetterLower then string.substr(0,1).toLowerCase() + string.substr(1) else string underscore: (string) -> string.replace(underscore_rx1, '$1_$2') .replace(underscore_rx2, '$1_$2') .replace('-', '_').toLowerCase() singularize: (string) -> len = string.length if string.substr(len - 3) is 'ies' string.substr(0, len - 3) + 'y' else if string.substr(len - 1) is 's' string.substr(0, len - 1) else string pluralize: (count, string) -> if string return string if count is 1 else string = count len = string.length lastLetter = string.substr(len - 1) if lastLetter is 'y' "#{string.substr(0, len - 1)}ies" else if lastLetter is 's' string else "#{string}s" capitalize: (string) -> string.replace capitalize_rx, (m,p1,p2) -> p1+p2.toUpperCase() trim: (string) -> if string then string.trim() else "" } # Properties # ---------- class Batman.Property @defaultAccessor: get: (key) -> @[key] set: (key, val) -> @[key] = val unset: (key) -> x = @[key]; delete @[key]; x @triggerTracker: null @forBaseAndKey: (base, key) -> propertyClass = base.propertyClass or Batman.Keypath if base._batman Batman.initializeObject base properties = base._batman.properties ||= new Batman.SimpleHash properties.get(key) or properties.set(key, new propertyClass(base, key)) else new propertyClass(base, key) constructor: (@base, @key) -> @observers = new Batman.SimpleSet @refreshTriggers() if @hasObserversToFire() @_preventCount = 0 isProperty: true isEqual: (other) -> @constructor is other.constructor and @base is other.base and @key is other.key accessor: -> accessors = @base._batman?.get('keyAccessors') if accessors && (val = accessors.get(@key)) return val else @base._batman?.getFirst('defaultAccessor') or Batman.Property.defaultAccessor registerAsTrigger: -> tracker.add @ if tracker = Batman.Property.triggerTracker getValue: -> @registerAsTrigger() @accessor()?.get.call @base, @key setValue: (val) -> @cacheDependentValues() result = @accessor()?.set.call @base, @key, val @fireDependents() result unsetValue: -> @cacheDependentValues() result = @accessor()?.unset.call @base, @key @fireDependents() result cacheDependentValues: -> if @dependents @dependents.forEach (prop) -> prop.cachedValue = prop.getValue() fireDependents: -> if @dependents @dependents.forEach (prop) -> prop.fire(prop.getValue(), prop.cachedValue) if prop.hasObserversToFire?() observe: (fireImmediately..., callback) -> fireImmediately = fireImmediately[0] is true currentValue = @getValue() @observers.add callback @refreshTriggers() callback.call(@base, currentValue, currentValue) if fireImmediately @ hasObserversToFire: -> return true if @observers.length > 0 if @base._batman @base._batman.ancestors().some((ancestor) => ancestor.property?(@key)?.observers?.length > 0) else false prevent: -> @_preventCount++ allow: -> @_preventCount-- if @_preventCount > 0 isAllowedToFire: -> @_preventCount <= 0 fire: (args...) -> return unless @isAllowedToFire() and @hasObserversToFire() key = @key base = @base observerSets = [@observers] @observers.forEach (callback) -> callback?.apply base, args if @base._batman @base._batman.ancestors (ancestor) -> ancestor.property?(key).observers.forEach (callback) -> callback?.apply base, args @refreshTriggers() forget: (observer) -> if observer @observers.remove(observer) else @observers = new Batman.SimpleSet @clearTriggers() unless @hasObserversToFire() refreshTriggers: -> Batman.Property.triggerTracker = new Batman.SimpleSet @getValue() if @triggers @triggers.forEach (property) => unless Batman.Property.triggerTracker.has(property) property.dependents?.remove @ @triggers = Batman.Property.triggerTracker @triggers.forEach (property) => property.dependents ||= new Batman.SimpleSet property.dependents.add @ delete Batman.Property.triggerTracker clearTriggers: -> if @triggers @triggers.forEach (property) => property.dependents.remove @ @triggers = new Batman.SimpleSet # Keypaths # -------- class Batman.Keypath extends Batman.Property constructor: (base, key) -> if $typeOf(key) is 'String' @segments = key.split('.') @depth = @segments.length else @segments = [key] @depth = 1 super slice: (begin, end = @depth) -> base = @base for segment in @segments.slice(0, begin) return unless base? and base = Batman.Property.forBaseAndKey(base, segment).getValue() Batman.Property.forBaseAndKey base, @segments.slice(begin, end).join('.') terminalProperty: -> @slice -1 getValue: -> @registerAsTrigger() if @depth is 1 then super else @terminalProperty()?.getValue() setValue: (val) -> if @depth is 1 then super else @terminalProperty()?.setValue(val) unsetValue: -> if @depth is 1 then super else @terminalProperty()?.unsetValue() # Observable # ---------- # Batman.Observable is a generic mixin that can be applied to any object to allow it to be bound to. # It is applied by default to every instance of `Batman.Object` and subclasses. Batman.Observable = isObservable: true property: (key) -> Batman.initializeObject @ Batman.Property.forBaseAndKey(@, key) get: (key) -> @property(key).getValue() set: (key, val) -> @property(key).setValue(val) unset: (key) -> @property(key).unsetValue() getOrSet: (key, valueFunction) -> currentValue = @get(key) unless currentValue currentValue = valueFunction() @set(key, currentValue) currentValue # `forget` removes an observer from an object. If the callback is passed in, # its removed. If no callback but a key is passed in, all the observers on # that key are removed. If no key is passed in, all observers are removed. forget: (key, observer) -> if key @property(key).forget(observer) else @_batman.properties.forEach (key, property) -> property.forget() @ # `allowed` returns a boolean describing whether or not the key is # currently allowed to fire its observers. allowed: (key) -> @property(key).isAllowedToFire() # `fire` tells any observers attached to a key to fire, manually. # `prevent` stops of a given binding from firing. `prevent` calls can be repeated such that # the same number of calls to allow are needed before observers can be fired. # `allow` unblocks a property for firing observers. Every call to prevent # must have a matching call to allow later if observers are to be fired. # `observe` takes a key and a callback. Whenever the value for that key changes, your # callback will be called in the context of the original object. for k in ['observe', 'prevent', 'allow', 'fire'] do (k) -> Batman.Observable[k] = (key, args...) -> @property(key)[k](args...) @ $get = Batman.get = (object, key) -> if object.get object.get(key) else Batman.Observable.get.call(object, key) # Events # ------ # `Batman.EventEmitter` is another generic mixin that simply allows an object to # emit events. Batman events use observers to manage the callbacks, so they require that # the object emitting the events be observable. If events need to be attached to an object # which isn't a `Batman.Object` or doesn't have the `Batman.Observable` and `Batman.EventEmitter` # mixins applied, the $event function can be used to create ephemeral event objects which # use those mixins internally. Batman.EventEmitter = # An event is a convenient observer wrapper. Any function can be wrapped in an event, and # when called, it will cause it's object to fire all the observers for that event. There is # also some syntactical sugar so observers can be registered simply by calling the event with a # function argument. Notice that the `$block` helper is used here so events can be declared in # class definitions using the second function application syntax and no wrapping brackets. event: $block (key, context, callback) -> if not callback and typeof context isnt 'undefined' callback = context context = null if not callback and $typeOf(key) isnt 'String' callback = key key = null # Return a function which either takes another observer # to register or a value to fire the event with. f = (observer) -> if not @observe developer.error "EventEmitter requires Observable" Batman.initializeObject @ key ||= $findName(f, @) fired = @_batman.oneShotFired?[key] # Pass a function to the event to register it as an observer. if typeof observer is 'function' @observe key, observer observer.apply(@, f._firedArgs) if f.isOneShot and fired # Otherwise, calling the event will cause it to fire. Any # arguments you pass will be passed to your wrapped function. else if @allowed key return false if f.isOneShot and fired value = callback?.apply @, arguments # Observers will only fire if the result of the event is not false. if value isnt false # Get and cache the arguments for the event listeners. Add the value if # its not undefined, and then concat any more arguments passed to this # event when fired. f._firedArgs = unless typeof value is 'undefined' [value].concat arguments... else if arguments.length == 0 [] else Array.prototype.slice.call arguments # Copy the array and add in the key for `fire` args = Array.prototype.slice.call f._firedArgs args.unshift key @fire(args...) if f.isOneShot firings = @_batman.oneShotFired ||= {} firings[key] = yes value else false # This could be its own mixin but is kept here for brevity. f = f.bind(context) if context @[key] = f if key? $mixin f, isEvent: yes action: callback # One shot events can be used for something that only fires once. Any observers # added after it has already fired will simply be executed immediately. This is useful # for things like `ready` events on requests or renders, because once ready they always # remain ready. If an AJAX request had a vanilla `ready` event, observers attached after # the ready event fired the first time would never fire, as they would be waiting for # the next time `ready` would fire as is standard with vanilla events. With a one shot # event, any observers attached after the first fire will fire immediately, meaning no logic eventOneShot: (callback) -> $mixin Batman.EventEmitter.event.apply(@, arguments), isOneShot: yes oneShotFired: @oneShotFired.bind @ oneShotFired: (key) -> Batman.initializeObject @ firings = @_batman.oneShotFired ||= {} !!firings[key] # `$event` lets you create an ephemeral event without needing an EventEmitter. # If you already have an EventEmitter object, you should call .event() on it. Batman.event = $event = (callback) -> context = new Batman.Object context.event('_event', context, callback) # `$eventOneShot` lets you create an ephemeral one-shot event without needing an EventEmitter. # If you already have an EventEmitter object, you should call .eventOneShot() on it. Batman.eventOneShot = $eventOneShot = (callback) -> context = new Batman.Object oneShot = context.eventOneShot('_event', context, callback) oneShot.oneShotFired = -> context.oneShotFired('_event') oneShot # Objects # ------- # `Batman.initializeObject` is called by all the methods in Batman.Object to ensure that the # object's `_batman` property is initialized and it's own. Classes extending Batman.Object inherit # methods like `get`, `set`, and `observe` by default on the class and prototype levels, such that # both instances and the class respond to them and can be bound to. However, CoffeeScript's static # class inheritance copies over all class level properties indiscriminately, so a parent class' # `_batman` object will get copied to its subclasses, transferring all the information stored there and # allowing subclasses to mutate parent state. This method prevents this undesirable behaviour by tracking # which object the `_batman_` object was initialized upon, and reinitializing if that has changed since # initialization. Batman.initializeObject = (object) -> if object._batman? object._batman.check(object) else object._batman = new _Batman(object) # _Batman provides a convienient, parent class and prototype aware place to store hidden # object state. Things like observers, accessors, and states belong in the `_batman` object # attached to every Batman.Object subclass and subclass instance. Batman._Batman = class _Batman constructor: (@object, mixins...) -> $mixin(@, mixins...) if mixins.length > 0 # Used by `Batman.initializeObject` to ensure that this `_batman` was created referencing # the object it is pointing to. check: (object) -> if object != @object object._batman = new _Batman(object) return false return true # `get` is a prototype and class aware property access method. `get` will traverse the prototype chain, asking # for the passed key at each step, and then attempting to merge the results into one object. # It can only do this if at each level an `Array`, `Hash`, or `Set` is found, so try to use # those if you need `_batman` inhertiance. get: (key) -> # Get all the keys from the ancestor chain results = @getAll(key) switch results.length when 0 undefined when 1 results[0] else # And then try to merge them if there is more than one. Use `concat` on arrays, and `merge` on # sets and hashes. if results[0].concat? results = results.reduceRight (a, b) -> a.concat(b) else if results[0].merge? results = results.reduceRight (a, b) -> a.merge(b) results # `getFirst` is a prototype and class aware property access method. `getFirst` traverses the prototype chain, # and returns the value of the first `_batman` object which defines the passed key. Useful for # times when the merged value doesn't make sense or the value is a primitive. getFirst: (key) -> results = @getAll(key) results[0] # `getAll` is a prototype and class chain iterator. When passed a key or function, it applies it to each # parent class or parent prototype, and returns the undefined values, closest ancestor first. getAll: (keyOrGetter) -> # Get a function which pulls out the key from the ancestor's `_batman` or use the passed function. if typeof keyOrGetter is 'function' getter = keyOrGetter else getter = (ancestor) -> ancestor._batman?[keyOrGetter] # Apply it to all the ancestors, and then this `_batman`'s object. results = @ancestors(getter) if val = getter(@object) results.unshift val results # `ancestors` traverses the prototype or class chain and returns the application of a function to each # object in the chain. `ancestors` does this _only_ to the `@object`'s ancestors, and not the `@object` # itsself. ancestors: (getter = (x) -> x) -> results = [] # Decide if the object is a class or not, and pull out the first ancestor isClass = !!@object.prototype parent = if isClass @object.__super__?.constructor else if (proto = Object.getPrototypeOf(@object)) == @object @object.constructor.__super__ else proto if parent? # Apply the function and store the result if it isn't undefined. val = getter(parent) results.push(val) if val? # Use a recursive call to `_batman.ancestors` on the ancestor, which will take the next step up the chain. results = results.concat(parent._batman.ancestors(getter)) if parent._batman? results set: (key, value) -> @[key] = value # `Batman.Object` is the base class for all other Batman objects. It is not abstract. class BatmanObject # Setting `isGlobal` to true will cause the class name to be defined on the # global object. For example, Batman.Model will be aliased to window.Model. # This should be used sparingly; it's mostly useful for debugging. @global: (isGlobal) -> return if isGlobal is false container[$functionName(@)] = @ # Apply mixins to this class. @classMixin: -> $mixin @, arguments... # Apply mixins to instances of this class. @mixin: -> @classMixin.apply @prototype, arguments mixin: @classMixin # Accessor implementation. Accessors are used to create properties on a class or prototype which can be fetched # with get, but are computed instead of just stored. This is a batman and old browser friendly version of # `defineProperty` without as much goodness. # # Accessors track which other properties they rely on for computation, and when those other properties change, # an accessor will recalculate its value and notifiy its observers. This way, when a source value is changed, # any dependent accessors will automatically update any bindings to them with a new value. Accessors accomplish # this feat by tracking `get` calls, do be sure to use `get` to retrieve properties inside accessors. # # `@accessor` or `@classAccessor` can be called with zero, one, or many keys to attach the accessor to. This # has the following effects: # # * zero: create a `defaultAccessor`, which will be called when no other properties or accessors on an object # match a keypath. This is similar to `method_missing` in Ruby or `#doesNotUnderstand` in Smalltalk. # * one: create a `keyAccessor` at the given key, which will only be called when that key is `get`ed. # * many: create `keyAccessors` for each given key, which will then be called whenever each key is `get`ed. # # Note: This function gets called in all sorts of different contexts by various # other pointers to it, but it acts the same way on `this` in all cases. getAccessorObject = (accessor) -> accessor = {get: accessor} if !accessor.get && !accessor.set && !accessor.unset accessor @classAccessor: (keys..., accessor) -> Batman.initializeObject @ # Create a default accessor if no keys have been given. if keys.length is 0 # The `accessor` argument is wrapped in `getAccessorObject` which allows functions to be passed in # as a shortcut to {get: function} @_batman.defaultAccessor = getAccessorObject(accessor) else # Otherwise, add key accessors for each key given. @_batman.keyAccessors ||= new Batman.SimpleHash @_batman.keyAccessors.set(key, getAccessorObject(accessor)) for key in keys # Support adding accessors to the prototype from within class defintions or after the class has been created # with `KlassExtendingBatmanObject.accessor(keys..., accessorObject)` @accessor: -> @classAccessor.apply @prototype, arguments # Support adding accessors to instances after creation accessor: @classAccessor constructor: (mixins...) -> @_batman = new _Batman(@) @mixin mixins... # Make every subclass and their instances observable. @classMixin Batman.Observable, Batman.EventEmitter @mixin Batman.Observable, Batman.EventEmitter # Observe this property on every instance of this class. @observeAll: -> @::observe.apply @prototype, arguments @singleton: (singletonMethodName="sharedInstance") -> @classAccessor singletonMethodName, get: -> @["_#{singletonMethodName}"] ||= new @ Batman.Object = BatmanObject class Batman.Accessible extends Batman.Object constructor: -> @accessor.apply(@, arguments) # Collections Batman.Enumerable = isEnumerable: true map: (f, ctx = container) -> r = []; @forEach(-> r.push f.apply(ctx, arguments)); r every: (f, ctx = container) -> r = true; @forEach(-> r = r && f.apply(ctx, arguments)); r some: (f, ctx = container) -> r = false; @forEach(-> r = r || f.apply(ctx, arguments)); r reduce: (f, r) -> count = 0 self = @ @forEach -> if r? then r = f(r, arguments..., count, self) else r = arguments[0] r filter: (f) -> r = new @constructor if r.add wrap = (r, e) -> r.add(e) if f(e); r else if r.set wrap = (r, k, v) -> r.set(k, v) if f(k, v); r else r = [] unless r.push wrap = (r, e) -> r.push(e) if f(e); r @reduce wrap, r # Provide this simple mixin ability so that during bootstrapping we don't have to use `$mixin`. `$mixin` # will correctly attempt to use `set` on the mixinee, which ends up requiring the definition of # `SimpleSet` to be complete during its definition. $extendsEnumerable = (onto) -> onto[k] = v for k,v of Batman.Enumerable class Batman.SimpleHash constructor: -> @_storage = {} @length = 0 $extendsEnumerable(@::) propertyClass: Batman.Property hasKey: (key) -> if pairs = @_storage[key] for pair in pairs return true if @equality(pair[0], key) return false get: (key) -> if pairs = @_storage[key] for pair in pairs return pair[1] if @equality(pair[0], key) set: (key, val) -> pairs = @_storage[key] ||= [] for pair in pairs if @equality(pair[0], key) return pair[1] = val @length++ pairs.push([key, val]) val unset: (key) -> if pairs = @_storage[key] for [obj,value], index in pairs if @equality(obj, key) pairs.splice(index,1) @length-- return getOrSet: Batman.Observable.getOrSet equality: (lhs, rhs) -> return true if lhs is rhs return true if lhs isnt lhs and rhs isnt rhs # when both are NaN return true if lhs?.isEqual?(rhs) and rhs?.isEqual?(lhs) return false forEach: (iterator) -> for key, values of @_storage iterator(obj, value) for [obj, value] in values keys: -> result = [] # Explicitly reference this foreach so that if it's overriden in subclasses the new implementation isn't used. Batman.SimpleHash::forEach.call @, (obj) -> result.push obj result clear: -> @_storage = {} @length = 0 isEmpty: -> @length is 0 merge: (others...) -> merged = new @constructor others.unshift(@) for hash in others hash.forEach (obj, value) -> merged.set obj, value merged class Batman.Hash extends Batman.Object constructor: -> Batman.SimpleHash.apply(@, arguments) # Add a meta object to all hashes which we can then use in the `meta` filter to allow binding # to hash meta-properties without reserving keys. @meta = new Batman.Object(length: 0) self = this @meta.accessor 'isEmpty', -> self.isEmpty() @meta.accessor 'keys', -> self.keys() super $extendsEnumerable(@::) propertyClass: Batman.Property @accessor get: Batman.SimpleHash::get set: -> results = Batman.SimpleHash::set.apply(@, arguments) @meta.set('length', @length) results unset: -> results = Batman.SimpleHash::unset.apply(@, arguments) @meta.set('length', @length) results for k in ['hasKey', 'equality', 'forEach', 'keys', 'isEmpty', 'merge'] @::[k] = Batman.SimpleHash::[k] clear: -> results = Batman.SimpleHash::clear.apply(@, arguments) @meta.set('length', @length) results class Batman.SimpleSet constructor: -> @_storage = new Batman.SimpleHash @_indexes = new Batman.SimpleHash @_sorts = new Batman.SimpleHash @length = 0 @add.apply @, arguments if arguments.length > 0 $extendsEnumerable(@::) has: (item) -> @_storage.hasKey item add: (items...) -> addedItems = [] for item in items unless @_storage.hasKey(item) @_storage.set item, true addedItems.push item @length++ @itemsWereAdded(addedItems...) unless addedItems.length is 0 addedItems remove: (items...) -> removedItems = [] for item in items if @_storage.hasKey(item) @_storage.unset item removedItems.push item @length-- @itemsWereRemoved(removedItems...) unless removedItems.length is 0 removedItems forEach: (iterator) -> @_storage.forEach (key, value) -> iterator(key) isEmpty: -> @length is 0 clear: -> items = @toArray() @_storage = new Batman.SimpleHash @length = 0 @itemsWereRemoved(items...) items toArray: -> @_storage.keys() merge: (others...) -> merged = new @constructor others.unshift(@) for set in others set.forEach (v) -> merged.add v merged indexedBy: (key) -> @_indexes.get(key) or @_indexes.set(key, new Batman.SetIndex(@, key)) sortedBy: (key) -> @_sorts.get(key) or @_sorts.set(key, new Batman.SetSort(@, key)) itemsWereAdded: -> itemsWereRemoved: -> class Batman.Set extends Batman.Object constructor: -> Batman.SimpleSet.apply @, arguments @set 'length', 0 $extendsEnumerable(@::) itemsWereAdded: @event -> itemsWereRemoved: @event -> for k in ['has', 'forEach', 'isEmpty', 'toArray', 'indexedBy', 'sortedBy'] @::[k] = Batman.SimpleSet::[k] for k in ['add', 'remove', 'clear', 'merge'] do (k) => @::[k] = -> oldLength = @length @prevent 'length' results = Batman.SimpleSet::[k].apply(@, arguments) [newLength, @length] = [@length, oldLength] @allow 'length' @set 'length', newLength if newLength != oldLength results @accessor 'indexedBy', -> new Batman.Accessible (key) => @indexedBy(key) @accessor 'sortedBy', -> new Batman.Accessible (key) => @sortedBy(key) @accessor 'isEmpty', -> @isEmpty() class Batman.SetObserver extends Batman.Object constructor: (@base) -> @_itemObservers = new Batman.Hash @_setObservers = new Batman.Hash @_setObservers.set("itemsWereAdded", @itemsWereAdded.bind(@)) @_setObservers.set("itemsWereRemoved", @itemsWereRemoved.bind(@)) @observe 'itemsWereAdded', @startObservingItems.bind(@) @observe 'itemsWereRemoved', @stopObservingItems.bind(@) itemsWereAdded: @event -> itemsWereRemoved: @event -> observedItemKeys: [] observerForItemAndKey: (item, key) -> _getOrSetObserverForItemAndKey: (item, key) -> @_itemObservers.getOrSet item, => observersByKey = new Batman.Hash observersByKey.getOrSet key, => @observerForItemAndKey(item, key) startObserving: -> @_manageItemObservers("observe") @_manageSetObservers("observe") stopObserving: -> @_manageItemObservers("forget") @_manageSetObservers("forget") startObservingItems: (items...) -> @_manageObserversForItem(item, "observe") for item in items stopObservingItems: (items...) -> @_manageObserversForItem(item, "forget") for item in items _manageObserversForItem: (item, method) -> return unless item.isObservable for key in @observedItemKeys item[method] key, @_getOrSetObserverForItemAndKey(item, key) @_itemObservers.unset(item) if method is "forget" _manageItemObservers: (method) -> @base.forEach (item) => @_manageObserversForItem(item, method) _manageSetObservers: (method) -> return unless @base.isObservable @_setObservers.forEach (key, observer) => @base[method](key, observer) class Batman.SetSort extends Batman.Object constructor: (@base, @key) -> if @base.isObservable @_setObserver = new Batman.SetObserver(@base) @_setObserver.observedItemKeys = [@key] boundReIndex = @_reIndex.bind(@) @_setObserver.observerForItemAndKey = -> boundReIndex @_setObserver.observe 'itemsWereAdded', boundReIndex @_setObserver.observe 'itemsWereRemoved', boundReIndex @startObserving() @_reIndex() startObserving: -> @_setObserver?.startObserving() stopObserving: -> @_setObserver?.stopObserving() toArray: -> @get('_storage') @accessor 'toArray', @::toArray forEach: (iterator) -> iterator(e,i) for e,i in @get('_storage') compare: (a,b) -> return 0 if a is b return 1 if a is undefined return -1 if b is undefined return 1 if a is null return -1 if b is null return 0 if a.isEqual?(b) and b.isEqual?(a) typeComparison = Batman.SetSort::compare($typeOf(a), $typeOf(b)) return typeComparison if typeComparison isnt 0 return 1 if a isnt a # means a is NaN return -1 if b isnt b # means b is NaN return 1 if a > b return -1 if a < b return 0 _reIndex: -> newOrder = @base.toArray().sort (a,b) => valueA = Batman.Observable.property.call(a, @key).getValue() valueA = valueA.valueOf() if valueA? valueB = Batman.Observable.property.call(b, @key).getValue() valueB = valueB.valueOf() if valueB? @compare.call(@, valueA, valueB) @_setObserver?.startObservingItems(newOrder...) @set('_storage', newOrder) class Batman.SetIndex extends Batman.Object constructor: (@base, @key) -> @_storage = new Batman.Hash if @base.isObservable @_setObserver = new Batman.SetObserver(@base) @_setObserver.observedItemKeys = [@key] @_setObserver.observerForItemAndKey = @observerForItemAndKey.bind(@) @_setObserver.observe 'itemsWereAdded', (items...) => @_addItem(item) for item in items @_setObserver.observe 'itemsWereRemoved', (items...) => @_removeItem(item) for item in items @base.forEach @_addItem.bind(@) @startObserving() @accessor (key) -> @_resultSetForKey(key) startObserving: ->@_setObserver?.startObserving() stopObserving: -> @_setObserver?.stopObserving() observerForItemAndKey: (item, key) -> (newValue, oldValue) => @_removeItemFromKey(item, oldValue) @_addItemToKey(item, newValue) _addItem: (item) -> @_addItemToKey(item, @_keyForItem(item)) _addItemToKey: (item, key) -> @_resultSetForKey(key).add item _removeItem: (item) -> @_removeItemFromKey(item, @_keyForItem(item)) _removeItemFromKey: (item, key) -> @_resultSetForKey(key).remove item _resultSetForKey: (key) -> @_storage.getOrSet(key, -> new Batman.Set) _keyForItem: (item) -> Batman.Keypath.forBaseAndKey(item, @key).getValue() class Batman.UniqueSetIndex extends Batman.SetIndex constructor: -> @_uniqueIndex = new Batman.Hash super @accessor (key) -> @_uniqueIndex.get(key) _addItemToKey: (item, key) -> @_resultSetForKey(key).add item unless @_uniqueIndex.hasKey(key) @_uniqueIndex.set(key, item) _removeItemFromKey: (item, key) -> resultSet = @_resultSetForKey(key) resultSet.remove item if resultSet.length is 0 @_uniqueIndex.unset(key) else @_uniqueIndex.set(key, resultSet.toArray()[0]) class Batman.SortableSet extends Batman.Set constructor: -> super @_sortIndexes = {} @observe 'activeIndex', => @setWasSorted(@) setWasSorted: @event -> return false if @length is 0 for k in ['add', 'remove', 'clear'] do (k) => @::[k] = -> results = Batman.Set::[k].apply(@, arguments) @_reIndex() results addIndex: (index) -> @_reIndex(index) removeIndex: (index) -> @_sortIndexes[index] = null delete @_sortIndexes[index] @unset('activeIndex') if @activeIndex is index index forEach: (iterator) -> iterator(el) for el in @toArray() sortBy: (index) -> @addIndex(index) unless @_sortIndexes[index] @set('activeIndex', index) unless @activeIndex is index @ isSorted: -> @_sortIndexes[@get('activeIndex')]? toArray: -> @_sortIndexes[@get('activeIndex')] || super _reIndex: (index) -> if index [keypath, ordering] = index.split ' ' ary = Batman.Set.prototype.toArray.call @ @_sortIndexes[index] = ary.sort (a,b) -> valueA = (Batman.Observable.property.call(a, keypath)).getValue()?.valueOf() valueB = (Batman.Observable.property.call(b, keypath)).getValue()?.valueOf() [valueA, valueB] = [valueB, valueA] if ordering?.toLowerCase() is 'desc' if valueA < valueB then -1 else if valueA > valueB then 1 else 0 @setWasSorted(@) if @activeIndex is index else @_reIndex(index) for index of @_sortIndexes @setWasSorted(@) @ # State Machines # -------------- Batman.StateMachine = { initialize: -> Batman.initializeObject @ if not @_batman.states @_batman.states = new Batman.SimpleHash state: (name, callback) -> Batman.StateMachine.initialize.call @ if not name return @_batman.getFirst 'state' developer.assert @event, "StateMachine requires EventEmitter" event = @[name] || @event name, -> _stateMachine_setState.call(@, name); false event.call(@, callback) if typeof callback is 'function' event transition: (from, to, callback) -> Batman.StateMachine.initialize.call @ @state from @state to name = "#{from}->#{to}" transitions = @_batman.states event = transitions.get(name) || transitions.set(name, $event ->) event(callback) if callback event } # A special method to alias state machine methods to class methods Batman.Object.actsAsStateMachine = (includeInstanceMethods=true) -> Batman.StateMachine.initialize.call @ Batman.StateMachine.initialize.call @prototype @classState = -> Batman.StateMachine.state.apply @, arguments @state = -> @classState.apply @prototype, arguments @::state = @classState if includeInstanceMethods @classTransition = -> Batman.StateMachine.transition.apply @, arguments @transition = -> @classTransition.apply @prototype, arguments @::transition = @classTransition if includeInstanceMethods # This is cached here so it doesn't need to be recompiled for every setter _stateMachine_setState = (newState) -> Batman.StateMachine.initialize.call @ if @_batman.isTransitioning (@_batman.nextState ||= []).push(newState) return false @_batman.isTransitioning = yes oldState = @state() @_batman.state = newState if newState and oldState name = "#{oldState}->#{newState}" for event in @_batman.getAll((ancestor) -> ancestor._batman?.get('states')?.get(name)) if event event newState, oldState if newState @fire newState, newState, oldState @_batman.isTransitioning = no @[@_batman.nextState.shift()]() if @_batman.nextState?.length newState # App, Requests, and Routing # -------------------------- # `Batman.Request` is a normalizer for XHR requests in the Batman world. class Batman.Request extends Batman.Object @objectToFormData: (data) -> pairForList = (key, object, first = false) -> list = switch Batman.typeOf(object) when 'Object' list = for k, v of object pairForList((if first then k else "#{key}[#{k}]"), v) list.reduce((acc, list) -> acc.concat list , []) when 'Array' object.reduce((acc, element) -> acc.concat pairForList("#{key}[]", element) , []) else [[key, object]] formData = new FormData() for [key, val] in pairForList("", data, true) formData.append(key, val) formData url: '' data: '' method: 'get' formData: false response: null status: null # Set the content type explicitly for PUT and POST requests. contentType: 'application/x-www-form-urlencoded' # After the URL gets set, we'll try to automatically send # your request after a short period. If this behavior is # not desired, use @cancel() after setting the URL. @observeAll 'url', -> @_autosendTimeout = setTimeout (=> @send()), 0 loading: @event -> loaded: @event -> success: @event -> error: @event -> # `send` is implmented in the platform layer files. One of those must be required for # `Batman.Request` to be useful. send: () -> developer.error "Please source a dependency file for a request implementation" cancel: -> clearTimeout(@_autosendTimeout) if @_autosendTimeout # `Batman.App` manages requiring files and acts as a namespace for all code subclassing # Batman objects. class Batman.App extends Batman.Object # Require path tells the require methods which base directory to look in. @requirePath: '' # The require class methods (`controller`, `model`, `view`) simply tells # your app where to look for coffeescript source files. This # implementation may change in the future. @require: (path, names...) -> base = @requirePath + path for name in names @prevent 'run' path = base + '/' + name + '.coffee' # FIXME: don't hardcode this new Batman.Request url: path type: 'html' success: (response) => CoffeeScript.eval response # FIXME: under no circumstances should we be compiling coffee in # the browser. This can be fixed via a real deployment solution # to compile coffeescripts, such as Sprockets. @allow 'run' @run() # FIXME: this should only happen if the client actually called run. @ @controller: (names...) -> names = names.map (n) -> n + '_controller' @require 'controllers', names... @model: -> @require 'models', arguments... @view: -> @require 'views', arguments... # Layout is the base view that other views can be yielded into. The # default behavior is that when `app.run()` is called, a new view will # be created for the layout using the `document` node as its content. # Use `MyApp.layout = null` to turn off the default behavior. @layout: undefined # Call `MyApp.run()` to start up an app. Batman level initializers will # be run to bootstrap the application. @run: @eventOneShot -> if Batman.currentApp return if Batman.currentApp is @ Batman.currentApp.stop() return false if @hasRun Batman.currentApp = @ if typeof @dispatcher is 'undefined' @dispatcher ||= new Batman.Dispatcher @ if typeof @layout is 'undefined' @set 'layout', new Batman.View contexts: [@] node: document @get('layout').ready => @ready() if typeof @historyManager is 'undefined' and @dispatcher.routeMap @historyManager = Batman.historyManager = new Batman.HashHistory @ @historyManager.start() @hasRun = yes @ # The `MyApp.ready` event will fire once the app's layout view has finished rendering. This includes # partials, loops, and all the other deferred renders, but excludes data fetching. @ready: @eventOneShot -> true @stop: @eventOneShot -> @historyManager?.stop() Batman.historyManager = null @hasRun = no @ # Dispatcher # ---------- class Batman.Route extends Batman.Object # Route regexes courtesy of Backbone namedParam = /:([\w\d]+)/g splatParam = /\*([\w\d]+)/g queryParam = '(?:\\?.+)?' namedOrSplat = /[:|\*]([\w\d]+)/g escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g constructor: -> super @pattern = @url.replace(escapeRegExp, '\\$&') @regexp = new RegExp('^' + @pattern.replace(namedParam, '([^\/]*)').replace(splatParam, '(.*?)') + queryParam + '$') @namedArguments = [] while (array = namedOrSplat.exec(@pattern))? @namedArguments.push(array[1]) if array[1] @accessor 'action', get: -> return @action if @action if @options result = $mixin {}, @options if signature = result.signature components = signature.split('#') result.controller = components[0] result.action = components[1] || 'index' result.target = @dispatcher.get result.controller @set 'action', result set: (key, action) -> @action = action parameterize: (url) -> [url, query] = url.split '?' array = @regexp.exec(url)?.slice(1) params = url: url action = @get 'action' if typeof action is 'function' params.action = action else $mixin params, action if array for param, index in array params[@namedArguments[index]] = param if query for s in query.split '&' [key, value] = s.split '=' params[key] = value params dispatch: (url) -> if $typeOf(url) is 'String' params = @parameterize url $redirect('/404') if not (action = params.action) and url isnt '/404' return action(params) if typeof action is 'function' return params.target.dispatch(action, params) if params.target?.dispatch return params.target?[action](params) class Batman.Dispatcher extends Batman.Object constructor: (@app) -> @app.route @ @app.controllers = new Batman.Object for key, controller of @app continue unless controller?.prototype instanceof Batman.Controller @prepareController controller prepareController: (controller) -> name = helpers.underscore($functionName(controller).replace('Controller', '')) return unless name getter = -> @[name] = controller.get 'sharedController' @accessor name, getter @app.controllers.accessor name, getter register: (url, options) -> url = "/#{url}" if url.indexOf('/') isnt 0 route = if $typeOf(options) is 'Function' new Batman.Route url: url, action: options, dispatcher: @ else new Batman.Route url: url, options: options, dispatcher: @ @routeMap ||= {} @routeMap[url] = route findRoute: (url) -> url = "/#{url}" if url.indexOf('/') isnt 0 return route if (route = @routeMap[url]) for routeUrl, route of @routeMap return route if route.regexp.test(url) findUrl: (params) -> for url, route of @routeMap matches = no options = route.options if params.resource matches = options.resource is params.resource and options.action is params.action else action = route.get 'action' continue if typeof action is 'function' {controller, action} = action if controller is params.controller and action is (params.action || 'index') matches = yes continue if not matches for key, value of params url = url.replace new RegExp('[:|\*]' + key), value return url dispatch: (url) -> route = @findRoute(url) if route route.dispatch(url) else if url isnt '/404' $redirect('/404') @app.set 'currentURL', url # History Manager # --------------- class Batman.HistoryManager constructor: (@app) -> dispatch: (url) -> url = "/#{url}" if url.indexOf('/') isnt 0 @app.dispatcher.dispatch url url redirect: (url) -> if $typeOf(url) isnt 'String' url = @app.dispatcher.findUrl(url) @dispatch url class Batman.HashHistory extends Batman.HistoryManager HASH_PREFIX: '#!' start: => return if typeof window is 'undefined' return if @started @started = yes if 'onhashchange' of window $addEventListener window, 'hashchange', @parseHash else @interval = setInterval @parseHash, 100 @first = true Batman.currentApp.prevent 'ready' setTimeout @parseHash, 0 stop: => if @interval @interval = clearInterval @interval else $removeEventListener window, 'hashchange', @parseHash @started = no urlFor: (url) -> @HASH_PREFIX + url parseHash: => hash = window.location.hash.replace @HASH_PREFIX, '' return if hash is @cachedHash result = @dispatch (@cachedHash = hash) if @first Batman.currentApp.allow 'ready' Batman.currentApp.fire 'ready' @first = false result redirect: (params) -> url = super @cachedHash = url window.location.hash = @HASH_PREFIX + url Batman.redirect = $redirect = (url) -> Batman.historyManager?.redirect url # Route Declarators # ----------------- Batman.App.classMixin route: (url, signature, options={}) -> return if not url if url instanceof Batman.Dispatcher dispatcher = url for key, value of @_dispatcherCache dispatcher.register key, value @_dispatcherCache = null return dispatcher if $typeOf(signature) is 'String' options.signature = signature else if $typeOf(signature) is 'Function' options = signature else if signature $mixin options, signature @_dispatcherCache ||= {} @_dispatcherCache[url] = options root: (signature, options) -> @route '/', signature, options resources: (resource, options={}, callback) -> (callback = options; options = {}) if typeof options is 'function' resource = helpers.pluralize(resource) controller = options.controller || resource @route(resource, "#{controller}#index", resource: controller, action: 'index') unless options.index is false @route("#{resource}/new", "#{controller}#new", resource: controller, action: 'new') unless options.new is false @route("#{resource}/:id", "#{controller}#show", resource: controller, action: 'show') unless options.show is false @route("#{resource}/:id/edit", "#{controller}#edit", resource: controller, action: 'edit') unless options.edit is false if callback app = @ ops = collection: (collectionCallback) -> collectionCallback?.call route: (url, methodName) -> app.route "#{resource}/#{url}", "#{controller}##{methodName || url}" member: (memberCallback) -> memberCallback?.call route: (url, methodName) -> app.route "#{resource}/:id/#{url}", "#{controller}##{methodName || url}" callback.call ops redirect: $redirect # Controllers # ----------- class Batman.Controller extends Batman.Object @singleton 'sharedController' @beforeFilter: (nameOrFunction) -> Batman.initializeObject @ filters = @_batman.beforeFilters ||= [] filters.push(nameOrFunction) if filters.indexOf(nameOrFunction) is -1 @accessor 'controllerName', get: -> @_controllerName ||= helpers.underscore($functionName(@constructor).replace('Controller', '')) @afterFilter: (nameOrFunction) -> Batman.initializeObject @ filters = @_batman.afterFilters ||= [] filters.push(nameOrFunction) if filters.indexOf(nameOrFunction) is -1 @accessor 'action', get: -> @_currentAction set: (key, value) -> @_currentAction = value # You shouldn't call this method directly. It will be called by the dispatcher when a route is called. # If you need to call a route manually, use `$redirect()`. dispatch: (action, params = {}) -> params.controller ||= @get 'controllerName' params.action ||= action params.target ||= @ oldRedirect = Batman.historyManager?.redirect Batman.historyManager?.redirect = @redirect @_actedDuringAction = no @set 'action', action if filters = @constructor._batman?.get('beforeFilters') for filter in filters if typeof filter is 'function' then filter.call(@, params) else @[filter](params) developer.assert @[action], "Error! Controller action #{@get 'controllerName'}.#{action} couldn't be found!" @[action](params) if not @_actedDuringAction @render() if filters = @constructor._batman?.get('afterFilters') for filter in filters if typeof filter is 'function' then filter.call(@, params) else @[filter](params) delete @_actedDuringAction @set 'action', null Batman.historyManager?.redirect = oldRedirect redirectTo = @_afterFilterRedirect delete @_afterFilterRedirect $redirect(redirectTo) if redirectTo redirect: (url) => throw 'DoubleRedirectError' if @_actedDuringAction if @get 'action' @_actedDuringAction = yes @_afterFilterRedirect = url else if $typeOf(url) is 'Object' url.controller = @ if not url.controller $redirect url render: (options = {}) -> throw 'DoubleRenderError' if @_actedDuringAction @_actedDuringAction = yes return if options is false if not options.view options.source ||= helpers.underscore($functionName(@constructor).replace('Controller', '')) + '/' + @_currentAction + '.html' options.view = new Batman.View(options) if view = options.view Batman.currentApp?.prevent 'ready' view.contexts.push @ view.ready -> Batman.DOM.contentFor('main', view.get('node')) Batman.currentApp?.allow 'ready' Batman.currentApp?.fire 'ready' view # Models # ------ class Batman.Model extends Batman.Object # ## Model API # Override this property if your model is indexed by a key other than `id` @primaryKey: 'id' # Override this property to define the key which storage adapters will use to store instances of this model under. # - For RestStorage, this ends up being part of the url built to store this model # - For LocalStorage, this ends up being the namespace in localStorage in which JSON is stored @storageKey: null # Pick one or many mechanisms with which this model should be persisted. The mechanisms # can be already instantiated or just the class defining them. @persist: (mechanisms...) -> Batman.initializeObject @prototype storage = @::_batman.storage ||= [] results = for mechanism in mechanisms mechanism = if mechanism.isStorageAdapter then mechanism else new mechanism(@) storage.push mechanism mechanism if results.length > 1 results else results[0] # Encoders are the tiny bits of logic which manage marshalling Batman models to and from their # storage representations. Encoders do things like stringifying dates and parsing them back out again, # pulling out nested model collections and instantiating them (and JSON.stringifying them back again), # and marshalling otherwise un-storable object. @encode: (keys..., encoderOrLastKey) -> Batman.initializeObject @prototype @::_batman.encoders ||= new Batman.SimpleHash @::_batman.decoders ||= new Batman.SimpleHash switch $typeOf(encoderOrLastKey) when 'String' keys.push encoderOrLastKey when 'Function' encoder = encoderOrLastKey else encoder = encoderOrLastKey.encode decoder = encoderOrLastKey.decode encoder = @defaultEncoder.encode if typeof encoder is 'undefined' decoder = @defaultEncoder.decode if typeof decoder is 'undefined' for key in keys @::_batman.encoders.set(key, encoder) if encoder @::_batman.decoders.set(key, decoder) if decoder # Set up the unit functions as the default for both @defaultEncoder: encode: (x) -> x decode: (x) -> x # Attach encoders and decoders for the primary key, and update them if the primary key changes. @observe 'primaryKey', yes, (newPrimaryKey) -> @encode newPrimaryKey, {encode: false, decode: @defaultEncoder.decode} # Validations allow a model to be marked as 'valid' or 'invalid' based on a set of programmatic rules. # By validating our data before it gets to the server we can provide immediate feedback to the user about # what they have entered and forgo waiting on a round trip to the server. # `validate` allows the attachment of validations to the model on particular keys, where the validation is # either a built in one (by use of options to pass to them) or a custom one (by use of a custom function as # the second argument). Custom validators should have the signature `(errors, record, key, callback)`. They # should add strings to the `errors` set based on the record (maybe depending on the `key` they were attached # to) and then always call the callback. Again: the callback must always be called. @validate: (keys..., optionsOrFunction) -> Batman.initializeObject @prototype validators = @::_batman.validators ||= [] if typeof optionsOrFunction is 'function' # Given a function, use that as the actual validator, expecting it to conform to the API # the built in validators do. validators.push keys: keys callback: optionsOrFunction else # Given options, find the validations which match the given options, and add them to the validators # array. options = optionsOrFunction for validator in Validators if (matches = validator.matches(options)) delete options[match] for match in matches validators.push keys: keys validator: new validator(matches) # ### Query methods @classAccessor 'all', get: -> @load() if @::hasStorage() and @classState() not in ['loaded', 'loading'] @get('loaded') set: (k, v) -> @set('loaded', v) @classAccessor 'loaded', get: -> unless @all @all = new Batman.SortableSet @all.sortBy "id asc" @all set: (k, v) -> @all = v @classAccessor 'first', -> @get('all').toArray()[0] @classAccessor 'last', -> x = @get('all').toArray(); x[x.length - 1] @find: (id, callback) -> developer.assert callback, "Must call find with a callback!" record = new @(id) newRecord = @_mapIdentity(record) newRecord.load callback return newRecord # `load` fetches records from all sources possible @load: (options, callback) -> if $typeOf(options) is 'Function' callback = options options = {} developer.assert @::_batman.getAll('storage').length, "Can't load model #{$functionName(@)} without any storage adapters!" do @loading @::_doStorageOperation 'readAll', options, (err, records) => if err? callback?(err, []) else mappedRecords = (@_mapIdentity(record) for record in records) do @loaded callback?(err, mappedRecords) # `create` takes an attributes hash, creates a record from it, and saves it given the callback. @create: (attrs, callback) -> if !callback [attrs, callback] = [{}, attrs] obj = new this(attrs) obj.save(callback) obj # `findOrCreate` takes an attributes hash, optionally containing a primary key, and returns to you a saved record # representing those attributes, either from the server or from the identity map. @findOrCreate: (attrs, callback) -> record = new this(attrs) if record.isNew() record.save(callback) else foundRecord = @_mapIdentity(record) foundRecord.updateAttributes(attrs) callback(undefined, foundRecord) @_mapIdentity: (record) -> if typeof (id = record.get('id')) == 'undefined' || id == '' return record else existing = @get("loaded.indexedBy.id").get(id)?.toArray()[0] if existing existing.updateAttributes(record._batman.attributes || {}) return existing else @get('loaded').add(record) return record # ### Record API # Add a universally accessible accessor for retrieving the primrary key, regardless of which key its stored under. @accessor 'id', get: -> pk = @constructor.get('primaryKey') if pk == 'id' @id else @get(pk) set: (k, v) -> pk = @constructor.get('primaryKey') if pk == 'id' @id = v else @set(pk, v) # Add normal accessors for the dirty keys and errors attributes of a record, so these accesses don't fall to the # default accessor. @accessor 'dirtyKeys', 'errors', Batman.Property.defaultAccessor # Add an accessor for the internal batman state under `batmanState`, so that the `state` key can be a valid # attribute. @accessor 'batmanState' get: -> @state() set: (k, v) -> @state(v) # Add a default accessor to make models store their attributes under a namespace by default. @accessor get: (k) -> (@_batman.attributes ||= {})[k] || @[k] set: (k, v) -> (@_batman.attributes ||= {})[k] = v unset: (k) -> x = (@_batman.attributes ||={})[k] delete @_batman.attributes[k] x # New records can be constructed by passing either an ID or a hash of attributes (potentially # containing an ID) to the Model constructor. By not passing an ID, the model is marked as new. constructor: (idOrAttributes = {}) -> developer.assert @ instanceof Batman.Object, "constructors must be called with new" # We have to do this ahead of super, because mixins will call set which calls things on dirtyKeys. @dirtyKeys = new Batman.Hash @errors = new Batman.ErrorsHash # Find the ID from either the first argument or the attributes. if $typeOf(idOrAttributes) is 'Object' super(idOrAttributes) else super() @set('id', idOrAttributes) @empty() if not @state() # Override the `Batman.Observable` implementation of `set` to implement dirty tracking. set: (key, value) -> # Optimize setting where the value is the same as what's already been set. oldValue = @get(key) return if oldValue is value # Actually set the value and note what the old value was in the tracking array. result = super @dirtyKeys.set(key, oldValue) # Mark the model as dirty if isn't already. @dirty() unless @state() in ['dirty', 'loading', 'creating'] result updateAttributes: (attrs) -> @mixin(attrs) @ toString: -> "#{$functionName(@constructor)}: #{@get('id')}" # `toJSON` uses the various encoders for each key to grab a storable representation of the record. toJSON: -> obj = {} # Encode each key into a new object encoders = @_batman.get('encoders') unless !encoders or encoders.isEmpty() encoders.forEach (key, encoder) => val = @get key if typeof val isnt 'undefined' encodedVal = encoder(@get key) if typeof encodedVal isnt 'undefined' obj[key] = encodedVal obj # `fromJSON` uses the various decoders for each key to generate a record instance from the JSON # stored in whichever storage mechanism. fromJSON: (data) -> obj = {} decoders = @_batman.get('decoders') # If no decoders were specified, do the best we can to interpret the given JSON by camelizing # each key and just setting the values. if !decoders or decoders.isEmpty() for key, value of data obj[key] = value else # If we do have decoders, use them to get the data. decoders.forEach (key, decoder) -> obj[key] = decoder(data[key]) if data[key] # Mixin the buffer object to use optimized and event-preventing sets used by `mixin`. @mixin obj # Each model instance (each record) can be in one of many states throughout its lifetime. Since various # operations on the model are asynchronous, these states are used to indicate exactly what point the # record is at in it's lifetime, which can often be during a save or load operation. @actsAsStateMachine yes # Add the various states to the model. for k in ['empty', 'dirty', 'loading', 'loaded', 'saving', 'saved', 'creating', 'created', 'validating', 'validated', 'destroying', 'destroyed'] @state k for k in ['loading', 'loaded'] @classState k _doStorageOperation: (operation, options, callback) -> developer.assert @hasStorage(), "Can't #{operation} model #{$functionName(@constructor)} without any storage adapters!" mechanisms = @_batman.get('storage') for mechanism in mechanisms mechanism[operation] @, options, callback true hasStorage: -> (@_batman.get('storage') || []).length > 0 # `load` fetches the record from all sources possible load: (callback) => if @state() in ['destroying', 'destroyed'] callback?(new Error("Can't load a destroyed record!")) return do @loading @_doStorageOperation 'read', {}, (err, record) => unless err do @loaded record = @constructor._mapIdentity(record) callback?(err, record) # `save` persists a record to all the storage mechanisms added using `@persist`. `save` will only save # a model if it is valid. save: (callback) => if @state() in ['destroying', 'destroyed'] callback?(new Error("Can't save a destroyed record!")) return @validate (isValid, errors) => if !isValid callback?(errors) return creating = @isNew() do @saving do @creating if creating @_doStorageOperation (if creating then 'create' else 'update'), {}, (err, record) => unless err if creating do @created do @saved @dirtyKeys.clear() record = @constructor._mapIdentity(record) callback?(err, record) # `destroy` destroys a record in all the stores. destroy: (callback) => do @destroying @_doStorageOperation 'destroy', {}, (err, record) => unless err @constructor.get('all').remove(@) do @destroyed callback?(err) # `validate` performs the record level validations determining the record's validity. These may be asynchronous, # in which case `validate` has no useful return value. Results from asynchronous validations can be received by # listening to the `afterValidation` lifecycle callback. validate: (callback) -> oldState = @state() @errors.clear() do @validating finish = () => do @validated @[oldState]() callback?(@errors.length == 0, @errors) validators = @_batman.get('validators') || [] unless validators.length > 0 finish() else count = validators.length validationCallback = => if --count == 0 finish() for validator in validators v = validator.validator # Run the validator `v` or the custom callback on each key it validates by instantiating a new promise # and passing it to the appropriate function along with the key and the value to be validated. for key in validator.keys if v v.validateEach @errors, @, key, validationCallback else validator.callback @errors, @, key, validationCallback return isNew: -> typeof @get('id') is 'undefined' # `ErrorHash` is a simple subclass of `Hash` which makes it a bit easier to # manage the errors on a model. class Batman.ErrorsHash extends Batman.Hash constructor: -> super @meta.observe 'length', (newLength) => @length = newLength @meta.set 'messages', new Batman.Set # Define a default accessor to instantiate a set for any requested key. @accessor get: (key) -> unless set = Batman.SimpleHash::get.call(@, key) set = new Batman.Set set.observe 'itemsWereAdded', (items...) => @meta.set('length', @meta.get('length') + items.length) @meta.get('messages').add(items...) set.observe 'itemsWereRemoved', (items...) => @meta.set('length', @meta.get('length') - arguments.length) @meta.get('messages').remove(items...) Batman.SimpleHash::set.call(@, key, set) set set: -> developer.error "Can't set on an errors hash, use add instead!" unset: -> developer.error "Can't unset on an errors hash, use clear instead!" # Define a shorthand method for adding errors to a key. add: (key, error) -> @get(key).add(error) # Ensure any observers placed on the sets stay around by clearing the sets instead of the whole hash clear: -> @forEach (key, set) -> set.clear() @ class Batman.Validator extends Batman.Object constructor: (@options, mixins...) -> super mixins... validate: (record) -> developer.error "You must override validate in Batman.Validator subclasses." @options: (options...) -> Batman.initializeObject @ if @_batman.options then @_batman.options.concat(options) else @_batman.options = options @matches: (options) -> results = {} shouldReturn = no for key, value of options if ~@_batman?.options?.indexOf(key) results[key] = value shouldReturn = yes return results if shouldReturn Validators = Batman.Validators = [ class Batman.LengthValidator extends Batman.Validator @options 'minLength', 'maxLength', 'length', 'lengthWithin', 'lengthIn' constructor: (options) -> if range = (options.lengthIn or options.lengthWithin) options.minLength = range[0] options.maxLength = range[1] || -1 delete options.lengthWithin delete options.lengthIn super validateEach: (errors, record, key, callback) -> options = @options value = record.get(key) if options.minLength and value.length < options.minLength errors.add key, "#{key} must be at least #{options.minLength} characters" if options.maxLength and value.length > options.maxLength errors.add key, "#{key} must be less than #{options.maxLength} characters" if options.length and value.length isnt options.length errors.add key, "#{key} must be #{options.length} characters" callback() class Batman.PresenceValidator extends Batman.Validator @options 'presence' validateEach: (errors, record, key, callback) -> value = record.get(key) if @options.presence and !value? errors.add key, "#{key} must be present" callback() ] class Batman.StorageAdapter extends Batman.Object constructor: (model) -> super(model: model, modelKey: model.get('storageKey') || helpers.pluralize(helpers.underscore($functionName(model)))) isStorageAdapter: true @::_batman.check(@::) for k in ['all', 'create', 'read', 'readAll', 'update', 'destroy'] for time in ['before', 'after'] do (k, time) => key = PI:KEY:<KEY>END_PIhelpers.PI:KEY:<KEY>END_PI @::[key] = (filter) -> @_batman.check(@) (@_batman["#{key}Filters"] ||= []).push filter before: (keys..., callback) -> @["before#{helpers.capitalize(k)}"](callback) for k in keys after: (keys..., callback) -> @["after#{helpers.capitalize(k)}"](callback) for k in keys _filterData: (prefix, action, data...) -> # Filter the data first with the beforeRead and then the beforeAll filters (@_batman.get("#{prefix}#{helpers.capitalize(action)}Filters") || []) .concat(@_batman.get("#{prefix}AllFilters") || []) .reduce( (filteredData, filter) => filter.call(@, filteredData) , data) getRecordFromData: (data) -> record = new @model() record.fromJSON(data) record $passError = (f) -> return (filterables) -> if filterables[0] filterables else err = filterables.shift() filterables = f.call(@, filterables) filterables.unshift(err) filterables class Batman.LocalStorage extends Batman.StorageAdapter constructor: -> if typeof window.localStorage is 'undefined' return null super @storage = localStorage @key_re = new RegExp("^#{@modelKey}(\\d+)$") @nextId = 1 @_forAllRecords (k, v) -> if matches = @key_re.exec(k) @nextId = Math.max(@nextId, parseInt(matches[1], 10) + 1) return @::before 'create', 'update', $passError ([record, options]) -> [JSON.stringify(record), options] @::after 'read', $passError ([record, attributes, options]) -> [record.fromJSON(JSON.parse(attributes)), attributes, options] _forAllRecords: (f) -> for i in [0...@storage.length] k = @storage.key(i) f.call(@, k, @storage.getItem(k)) getRecordFromData: (data) -> record = super @nextId = Math.max(@nextId, parseInt(record.get('id'), 10) + 1) record update: (record, options, callback) -> [err, recordToSave] = @_filterData('before', 'update', undefined, record, options) if !err id = record.get('id') if id? @storage.setItem(@modelKey + id, recordToSave) else err = new Error("Couldn't get record primary key.") callback(@_filterData('after', 'update', err, record, options)...) create: (record, options, callback) -> [err, recordToSave] = @_filterData('before', 'create', undefined, record, options) if !err id = record.get('id') || record.set('id', @nextId++) if id? key = @modelKey + id if @storage.getItem(key) err = new Error("Can't create because the record already exists!") else @storage.setItem(key, recordToSave) else err = new Error("Couldn't set record primary key on create!") callback(@_filterData('after', 'create', err, record, options)...) read: (record, options, callback) -> [err, record] = @_filterData('before', 'read', undefined, record, options) id = record.get('id') if !err if id? attrs = @storage.getItem(@modelKey + id) if !attrs err = new Error("Couldn't find record!") else err = new Error("Couldn't get record primary key.") callback(@_filterData('after', 'read', err, record, attrs, options)...) readAll: (_, options, callback) -> records = [] [err, options] = @_filterData('before', 'readAll', undefined, options) if !err @_forAllRecords (storageKey, data) -> if keyMatches = @key_re.exec(storageKey) records.push {data, id: keyMatches[1]} callback(@_filterData('after', 'readAll', err, records, options)...) @::after 'readAll', $passError ([allAttributes, options]) -> allAttributes = for attributes in allAttributes data = JSON.parse(attributes.data) data[@model.primaryKey] ||= parseInt(attributes.id, 10) data [allAttributes, options] @::after 'readAll', $passError ([allAttributes, options]) -> matches = [] for data in allAttributes match = true for k, v of options if data[k] != v match = false break if match matches.push data [matches, options] @::after 'readAll', $passError ([filteredAttributes, options]) -> [@getRecordFromData(data) for data in filteredAttributes, filteredAttributes, options] destroy: (record, options, callback) -> [err, record] = @_filterData 'before', 'destroy', undefined, record, options if !err id = record.get('id') if id? key = @modelKey + id if @storage.getItem key @storage.removeItem key else err = new Error("Can't delete nonexistant record!") else err = new Error("Can't delete record without an primary key!") callback(@_filterData('after', 'destroy', err, record, options)...) class Batman.RestStorage extends Batman.StorageAdapter defaultOptions: type: 'json' recordJsonNamespace: false collectionJsonNamespace: false constructor: -> super @recordJsonNamespace = helpers.singularize(@modelKey) @collectionJsonNamespace = helpers.pluralize(@modelKey) @::before 'create', 'update', $passError ([record, options]) -> json = record.toJSON() record = if @recordJsonNamespace x = {} x[@recordJsonNamespace] = json x else json [record, options] @::after 'create', 'read', 'update', $passError ([record, data, options]) -> data = data[@recordJsonNamespace] if data[@recordJsonNamespace] [record, data, options] @::after 'create', 'read', 'update', $passError ([record, data, options]) -> record.fromJSON(data) [record, data, options] optionsForRecord: (record, idRequired, callback) -> if record.url url = if typeof record.url is 'function' then record.url() else record.url else url = "/#{@modelKey}" if idRequired || !record.isNew() id = record.get('id') if !id? callback.call(@, new Error("Couldn't get record primary key!")) return url = url + "/" + id unless url callback.call @, new Error("Couldn't get model url!") else callback.call @, undefined, $mixin({}, @defaultOptions, {url}) optionsForCollection: (recordsOptions, callback) -> url = @model.url?() || @model.url || "/#{@modelKey}" unless url callback.call @, new Error("Couldn't get collection url!") else callback.call @, undefined, $mixin {}, @defaultOptions, {url, data: $mixin({}, @defaultOptions.data, recordsOptions)} create: (record, recordOptions, callback) -> @optionsForRecord record, false, (err, options) -> [err, data] = @_filterData('before', 'create', err, record, recordOptions) if err callback(err) return new Batman.Request $mixin options, data: data method: 'POST' success: (data) => callback(@_filterData('after', 'create', undefined, record, data, recordOptions)...) error: (error) => callback(@_filterData('after', 'create', error, record, error.request.get('response'), recordOptions)...) update: (record, recordOptions, callback) -> @optionsForRecord record, true, (err, options) -> [err, data] = @_filterData('before', 'update', err, record, recordOptions) if err callback(err) return new Batman.Request $mixin options, data: data method: 'PUT' success: (data) => callback(@_filterData('after', 'update', undefined, record, data, recordOptions)...) error: (error) => callback(@_filterData('after', 'update', error, record, error.request.get('response'), recordOptions)...) read: (record, recordOptions, callback) -> @optionsForRecord record, true, (err, options) -> [err, record, recordOptions] = @_filterData('before', 'read', err, record, recordOptions) if err callback(err) return new Batman.Request $mixin options, data: recordOptions method: 'GET' success: (data) => callback(@_filterData('after', 'read', undefined, record, data, recordOptions)...) error: (error) => callback(@_filterData('after', 'read', error, record, error.request.get('response'), recordOptions)...) readAll: (_, recordsOptions, callback) -> @optionsForCollection recordsOptions, (err, options) -> [err, recordsOptions] = @_filterData('before', 'readAll', err, recordsOptions) if err callback(err) return if recordsOptions && recordsOptions.url options.url = recordsOptions.url delete recordsOptions.url new Batman.Request $mixin options, data: recordsOptions method: 'GET' success: (data) => callback(@_filterData('after', 'readAll', undefined, data, recordsOptions)...) error: (error) => callback(@_filterData('after', 'readAll', error, error.request.get('response'), recordsOptions)...) @::after 'readAll', $passError ([data, options]) -> recordData = if data[@collectionJsonNamespace] then data[@collectionJsonNamespace] else data [recordData, data, options] @::after 'readAll', $passError ([recordData, serverData, options]) -> [@getRecordFromData(attributes) for attributes in recordData, serverData, options] destroy: (record, recordOptions, callback) -> @optionsForRecord record, true, (err, options) -> [err, record, recordOptions] = @_filterData('before', 'destroy', err, record, recordOptions) if err callback(err) return new Batman.Request $mixin options, method: 'DELETE' success: (data) => callback(@_filterData('after', 'destroy', undefined, record, data, recordOptions)...) error: (error) => callback(@_filterData('after', 'destroy', error, record, error.request.get('response'), recordOptions)...) # Views # ----------- # A `Batman.View` can function two ways: a mechanism to load and/or parse html files # or a root of a subclass hierarchy to create rich UI classes, like in Cocoa. class Batman.View extends Batman.Object constructor: (options) -> @contexts = [] super(options) # Support both `options.context` and `options.contexts` if context = @get('context') @contexts.push context @unset('context') viewSources = {} # Set the source attribute to an html file to have that file loaded. source: '' # Set the html to a string of html to have that html parsed. html: '' # Set an existing DOM node to parse immediately. node: null contentFor: null # Fires once a node is parsed. ready: @eventOneShot -> # Where to look for views on the server prefix: 'views' # Whenever the source changes we load it up asynchronously @observeAll 'source', -> setTimeout (=> @reloadSource()), 0 reloadSource: -> source = @get 'source' return if not source if viewSources[source] @set('html', viewSources[source]) else new Batman.Request url: url = "#{@prefix}/#{@source}" type: 'html' success: (response) => viewSources[source] = response @set('html', response) error: (response) -> throw new Error("Could not load view from #{url}") @observeAll 'html', (html) -> node = @node || document.createElement 'div' node.innerHTML = html @set('node', node) if @node isnt node @observeAll 'node', (node) -> return unless node @ready.fired = false if @_renderer @_renderer.forgetAll() # We use a renderer with the continuation style rendering engine to not # block user interaction for too long during the render. if node @_renderer = new Batman.Renderer( node, => content = @contentFor if typeof content is 'string' @contentFor = Batman.DOM._yields?[content] if @contentFor and node @contentFor.innerHTML = '' @contentFor.appendChild(node) , @contexts) @_renderer.rendered => @ready node # DOM Helpers # ----------- # `Batman.Renderer` will take a node and parse all recognized data attributes out of it and its children. # It is a continuation style parser, designed not to block for longer than 50ms at a time if the document # fragment is particularly long. class Batman.Renderer extends Batman.Object constructor: (@node, callback, contexts = []) -> super() @parsed callback if callback? @context = if contexts instanceof RenderContext then contexts else new RenderContext(contexts...) setTimeout @start, 0 start: => @startTime = new Date @parseNode @node resume: => @startTime = new Date @parseNode @resumeNode finish: -> @startTime = null @fire 'parsed' @fire 'rendered' forgetAll: -> parsed: @eventOneShot -> rendered: @eventOneShot -> bindingRegexp = /data\-(.*)/ sortBindings = (a, b) -> if a[0] == 'foreach' -1 else if b[0] == 'foreach' 1 else if a[0] == 'formfor' -1 else if b[0] == 'formfor' 1 else if a[0] == 'bind' -1 else if b[0] == 'bind' 1 else 0 parseNode: (node) -> if new Date - @startTime > 50 @resumeNode = node setTimeout @resume, 0 return if node.getAttribute and node.attributes bindings = for attr in node.attributes name = attr.nodeName.match(bindingRegexp)?[1] continue if not name if ~(varIndex = name.indexOf('-')) [name.substr(0, varIndex), name.substr(varIndex + 1), attr.value] else [name, attr.value] for readerArgs in bindings.sort(sortBindings) key = readerArgs[1] result = if readerArgs.length == 2 Batman.DOM.readers[readerArgs[0]]?(node, key, @context, @) else Batman.DOM.attrReaders[readerArgs[0]]?(node, key, readerArgs[2], @context, @) if result is false skipChildren = true break if (nextNode = @nextNode(node, skipChildren)) then @parseNode(nextNode) else @finish() nextNode: (node, skipChildren) -> if not skipChildren children = node.childNodes return children[0] if children?.length Batman.data(node, 'onParseExit')?() return if @node == node sibling = node.nextSibling return sibling if sibling nextParent = node while nextParent = nextParent.parentNode nextParent.onParseExit?() return if @node == nextParent parentSibling = nextParent.nextSibling return parentSibling if parentSibling return # Bindings are shortlived objects which manage the observation of any keypaths a `data` attribute depends on. # Bindings parse any keypaths which are filtered and use an accessor to apply the filters, and thus enjoy # the automatic trigger and dependency system that Batman.Objects use. class Binding extends Batman.Object # A beastly regular expression for pulling keypaths out of the JSON arguments to a filter. # It makes the following matches: # # + `foo` and `baz.qux` in `foo, "bar", baz.qux` # + `foo.bar.baz` in `true, false, "true", "false", foo.bar.baz` # + `true.bar` in `2, true.bar` # + `truesay` in truesay # + no matches in `"bar", 2, {"x":"y", "Z": foo.bar.baz}, "baz"` keypath_rx = /// (^|,) # Match either the start of an arguments list or the start of a space inbetween commas. \s* # Be insensitive to whitespace between the comma and the actual arguments. (?! # Use a lookahead to ensure we aren't matching true or false: (?:true|false) # Match either true or false ... \s* # and make sure that there's nothing else that comes after the true or false ... (?:$|,) # before the end of this argument in the list. ) ([a-zA-Z][\w\.]*) # Now that true and false can't be matched, match a dot delimited list of keys. \s* # Be insensitive to whitespace before the next comma or end of the filter arguments list. ($|,) # Match either the next comma or the end of the filter arguments list. ///g # A less beastly pair of regular expressions for pulling out the [] syntax `get`s in a binding string, and # dotted names that follow them. get_dot_rx = /(?:\]\.)(.+?)(?=[\[\.]|\s*\||$)/ get_rx = /(?!^\s*)\[(.*?)\]/g # The `filteredValue` which calculates the final result by reducing the initial value through all the filters. @accessor 'filteredValue', -> unfilteredValue = @get('unfilteredValue') ctx = @get('keyContext') if @get('key') if @filterFunctions.length > 0 developer.currentFilterContext = ctx developer.currentFilterStack = @renderContext result = @filterFunctions.reduce((value, fn, i) => # Get any argument keypaths from the context stored at parse time. args = @filterArguments[i].map (argument) -> if argument._keypath argument.context.get(argument._keypath) else argument # Apply the filter. args.unshift value fn.apply(ctx, args) , unfilteredValue) developer.currentFilterContext = null developer.currentFilterStack = null result else unfilteredValue # The `unfilteredValue` is whats evaluated each time any dependents change. @accessor 'unfilteredValue', -> # If we're working with an `@key` and not an `@value`, find the context the key belongs to so we can # hold a reference to it for passing to the `dataChange` and `nodeChange` observers. if k = @get('key') @get("keyContext.#{k}") else @get('value') # The `keyContext` accessor is @accessor 'keyContext', -> unless @_keyContext [unfilteredValue, @_keyContext] = @renderContext.findKey @key @_keyContext constructor: -> super # Pull out the key and filter from the `@keyPath`. @parseFilter() # Define the default observers. @nodeChange ||= (node, context) => if @key && @filterFunctions.length == 0 @get('keyContext').set @key, @node.value @dataChange ||= (value, node) -> Batman.DOM.valueForNode @node, value shouldSet = yes # And attach them. if @only in [false, 'nodeChange'] and Batman.DOM.nodeIsEditable(@node) Batman.DOM.events.change @node, => shouldSet = no @nodeChange(@node, @_keyContext || @value, @) shouldSet = yes # Observe the value of this binding's `filteredValue` and fire it immediately to update the node. if @only in [false, 'dataChange'] @observe 'filteredValue', yes, (value) => if shouldSet @dataChange(value, @node, @) @ parseFilter: -> # Store the function which does the filtering and the arguments (all except the actual value to apply the # filter to) in these arrays. @filterFunctions = [] @filterArguments = [] # Rewrite [] style gets, replace quotes to be JSON friendly, and split the string by pipes to see if there are any filters. keyPath = @keyPath keyPath = keyPath.replace(get_dot_rx, "]['$1']") while get_dot_rx.test(keyPath) # Stupid lack of lookbehind assertions... filters = keyPath.replace(get_rx, " | get $1 ").replace(/'/g, '"').split(/(?!")\s+\|\s+(?!")/) # The key will is always the first token before the pipe. try key = @parseSegment(orig = filters.shift())[0] catch e developer.warn e developer.error "Error! Couldn't parse keypath in \"#{orig}\". Parsing error above." if key and key._keypath @key = key._keypath else @value = key if filters.length while filterString = filters.shift() # For each filter, get the name and the arguments by splitting on the first space. split = filterString.indexOf(' ') if ~split filterName = filterString.substr(0, split) args = filterString.substr(split) else filterName = filterString # If the filter exists, grab it. if filter = Batman.Filters[filterName] @filterFunctions.push filter # Get the arguments for the filter by parsing the args as JSON, or # just pushing an placeholder array if args try @filterArguments.push @parseSegment(args) catch e developer.error "Bad filter arguments \"#{args}\"!" else @filterArguments.push [] else developer.error "Unrecognized filter '#{filterName}' in key \"#{@keyPath}\"!" # Map over each array of arguments to grab the context for any keypaths. @filterArguments = @filterArguments.map (argumentList) => argumentList.map (argument) => if argument._keypath # Discard the value (for the time being) and store the context for the keypath in `context`. [_, argument.context] = @renderContext.findKey argument._keypath argument # Turn a piece of a `data` keypath into a usable javascript object. # + replacing keypaths using the above regular expression # + wrapping the `,` delimited list in square brackets # + and `JSON.parse`ing them as an array. parseSegment: (segment) -> JSON.parse( "[" + segment.replace(keypath_rx, "$1{\"_keypath\": \"$2\"}$3") + "]" ) # The RenderContext class manages the stack of contexts accessible to a view during rendering. # Every, and I really mean every method which uses filters has to be defined in terms of a new # binding, or by using the RenderContext.bind method. This is so that the proper order of objects # is traversed and any observers are properly attached. class RenderContext constructor: (contexts...) -> @contexts = contexts @storage = new Batman.Object @defaultContexts = [@storage] @defaultContexts.push Batman.currentApp if Batman.currentApp findKey: (key) -> base = key.split('.')[0].split('|')[0].trim() for contexts in [@contexts, @defaultContexts] i = contexts.length while i-- context = contexts[i] if context.get? val = context.get(base) else val = context[base] if typeof val isnt 'undefined' # we need to pass the check if the basekey exists, even if the intermediary keys do not. return [$get(context, key), context] return [container.get(key), container] set: (args...) -> @storage.set(args...) push: (x) -> @contexts.push(x) pop: -> @contexts.pop() clone: -> context = new @constructor(@contexts...) newStorage = $mixin {}, @storage context.setStorage(newStorage) context setStorage: (storage) -> @defaultContexts[0] = storage # `BindingProxy` is a simple class which assists in allowing bound contexts to be popped to the top of # the stack. This happens when a `data-context` is descended into, for each iteration in a `data-foreach`, # and in other specific HTML bindings like `data-formfor`. `BindingProxy`s use accessors so that if the # value of the binding they proxy changes, the changes will be propagated to any thing observing it. # This is good because it allows `data-context` to take filtered keys and even filters which take # keypath arguments, calculate the context to descend into when any of those keys change, and importantly # expose a friendly `Batman.Object` interface for the rest of the `Binding` code to work with. @BindingProxy = class BindingProxy extends Batman.Object isBindingProxy: true # Take the `binding` which needs to be proxied, and optionally rest it at the `localKey` scope. constructor: (@binding, @localKey) -> if @localKey @accessor @localKey, -> @binding.get('filteredValue') else @accessor (key) -> @binding.get("filteredValue.#{key}") # Below are the two primitives that all the `Batman.DOM` helpers are composed of. # `addKeyToScopeForNode` takes a `node`, `key`, and optionally a `localName`. It creates a `Binding` to # the key (such that the key can contain filters and many keypaths in arguments), and then pushes the # bound value onto the stack of contexts for the given `node`. If `localName` is given, the bound value # is available using that identifier in child bindings. Otherwise, the value itself is pushed onto the # context stack and member properties can be accessed directly in child bindings. addKeyToScopeForNode: (node, key, localName) -> @bind(node, key, (value, node, binding) => @push new BindingProxy(binding, localName) , -> true ) # Pop the `BindingProxy` off the stack once this node has been parsed. Batman.data node, 'onParseExit', => @pop() # `bind` takes a `node`, a `key`, and observers for when the `dataChange`s and the `nodeChange`s. It # creates a `Binding` to the key (supporting filters and the context stack), which fires the observers # when appropriate. Note that `Binding` has default observers for `dataChange` and `nodeChange` that # will set node/object values if these observers aren't passed in here. # The optional `only` parameter can be used to create data-to-node-only or node-to-data-only bindings. If left unset, # both data-to-node (source) and node-to-data (target) events are observed. bind: (node, key, dataChange, nodeChange, only = false) -> return new Binding renderContext: @ keyPath: key node: node dataChange: dataChange nodeChange: nodeChange only: only Batman.DOM = { # `Batman.DOM.readers` contains the functions used for binding a node's value or innerHTML, showing/hiding nodes, # and any other `data-#{name}=""` style DOM directives. readers: { target: (node, key, context, renderer) -> Batman.DOM.readers.bind(node, key, context, renderer, 'nodeChange') source: (node, key, context, renderer) -> Batman.DOM.readers.bind(node, key, context, renderer, 'dataChange') bind: (node, key, context, renderer, only) -> switch node.nodeName.toLowerCase() when 'input' switch node.getAttribute('type') when 'checkbox' return Batman.DOM.attrReaders.bind(node, 'checked', key, context, renderer, only) when 'radio' return Batman.DOM.binders.radio(arguments...) when 'file' return Batman.DOM.binders.file(arguments...) when 'select' return Batman.DOM.binders.select(arguments...) # Fallback on the default nodeChange and dataChange observers in Binding context.bind(node, key, undefined, undefined, only) context: (node, key, context) -> context.addKeyToScopeForNode(node, key) mixin: (node, key, context) -> context.push(Batman.mixins) context.bind(node, key, (mixin) -> $mixin node, mixin , ->) context.pop() showif: (node, key, context, renderer, invert) -> originalDisplay = node.style.display || '' context.bind(node, key, (value) -> if !!value is !invert Batman.data(node, 'show')?.call(node) node.style.display = originalDisplay else if typeof (hide = Batman.data(node, 'hide')) == 'function' hide.call node else node.style.display = 'none' , -> ) hideif: (args...) -> Batman.DOM.readers.showif args..., yes route: (node, key, context) -> # you must specify the / in front to route directly to hash route if key.substr(0, 1) is '/' url = key else [key, action] = key.split '/' [dispatcher, app] = context.findKey 'dispatcher' [model, container] = context.findKey key dispatcher ||= Batman.currentApp.dispatcher if dispatcher and model instanceof Batman.Model action ||= 'show' name = helpers.underscore(helpers.pluralize($functionName(model.constructor))) url = dispatcher.findUrl({resource: name, id: model.get('id'), action: action}) else if model?.prototype # TODO write test for else case action ||= 'index' name = helpers.underscore(helpers.pluralize($functionName(model))) url = dispatcher.findUrl({resource: name, action: action}) return unless url if node.nodeName.toUpperCase() is 'A' node.href = Batman.HashHistory::urlFor url Batman.DOM.events.click node, (-> $redirect url) partial: (node, path, context, renderer) -> renderer.prevent('rendered') view = new Batman.View source: path + '.html' contentFor: node contexts: Array.prototype.slice.call(context.contexts) view.ready -> renderer.allow 'rendered' renderer.fire 'rendered' yield: (node, key) -> setTimeout (-> Batman.DOM.yield key, node), 0 contentfor: (node, key) -> setTimeout (-> Batman.DOM.contentFor key, node), 0 } # `Batman.DOM.attrReaders` contains all the DOM directives which take an argument in their name, in the # `data-dosomething-argument="keypath"` style. This means things like foreach, binding attributes like # disabled or anything arbitrary, descending into a context, binding specific classes, or binding to events. attrReaders: { _parseAttribute: (value) -> if value is 'false' then value = false if value is 'true' then value = true value source: (node, attr, key, context, renderer) -> Batman.DOM.attrReaders.bind node, attr, key, context, renderer, 'dataChange' bind: (node, attr, key, context, renderer, only) -> switch attr when 'checked', 'disabled', 'selected' dataChange = (value) -> node[attr] = !!value # Update the parent's binding if necessary Batman.data(node.parentNode, 'updateBinding')?() nodeChange = (node, subContext) -> subContext.set(key, Batman.DOM.attrReaders._parseAttribute(node[attr])) # Make the context and key available to the parent select Batman.data node, attr, context: context key: key when 'value', 'style', 'href', 'src', 'size' dataChange = (value) -> node[attr] = value nodeChange = (node, subContext) -> subContext.set(key, Batman.DOM.attrReaders._parseAttribute(node[attr])) when 'class' dataChange = (value) -> node.className = value nodeChange = (node, subContext) -> subContext.set key, node.className else dataChange = (value) -> node.setAttribute(attr, value) nodeChange = (node, subContext) -> subContext.set(key, Batman.DOM.attrReaders._parseAttribute(node.getAttribute(attr))) context.bind(node, key, dataChange, nodeChange, only) context: (node, contextName, key, context) -> context.addKeyToScopeForNode(node, key, contextName) event: (node, eventName, key, context) -> props = callback: null subContext: null context.bind node, key, (value, node, binding) -> props.callback = value if binding.get('key') ks = binding.get('key').split('.') ks.pop() if ks.length > 0 props.subContext = binding.get('keyContext').get(ks.join('.')) else props.subContext = binding.get('keyContext') , -> confirmText = node.getAttribute('data-confirm') Batman.DOM.events[eventName] node, -> if confirmText and not confirm(confirmText) return props.callback?.apply props.subContext, arguments addclass: (node, className, key, context, parentRenderer, invert) -> className = className.replace(/\|/g, ' ') #this will let you add or remove multiple class names in one binding context.bind node, key, (value) -> currentName = node.className includesClassName = currentName.indexOf(className) isnt -1 if !!value is !invert node.className = "#{currentName} #{className}" if !includesClassName else node.className = currentName.replace(className, '') if includesClassName , -> removeclass: (args...) -> Batman.DOM.attrReaders.addclass args..., yes foreach: (node, iteratorName, key, context, parentRenderer) -> prototype = node.cloneNode true prototype.removeAttribute "data-foreach-#{iteratorName}" parent = node.parentNode sibling = node.nextSibling # Remove the original node once the parent has moved past it. parentRenderer.parsed -> parent.removeChild node # Get a hash keyed by collection item with the nodes representing that item as values nodeMap = new Batman.SimpleHash fragment = document.createDocumentFragment() numPendingChildren = 0 observers = {} oldCollection = false context.bind(node, key, (collection) -> # Track the old collection so that if it changes, we can remove the observers we attached, # and only observe the new collection. if oldCollection return if collection == oldCollection nodeMap.forEach (item, node) -> node.parentNode?.removeChild node nodeMap.clear() if oldCollection.forget oldCollection.forget 'itemsWereAdded', observers.add oldCollection.forget 'itemsWereRemoved', observers.remove oldCollection.forget 'setWasSorted', observers.reorder oldCollection = collection observers.add = (items...) -> numPendingChildren += items.length for item in items parentRenderer.prevent 'rendered' newNode = prototype.cloneNode true nodeMap.set item, newNode localClone = context.clone() iteratorContext = new Batman.Object iteratorContext[iteratorName] = item localClone.push iteratorContext childRenderer = new Batman.Renderer newNode, do (newNode) -> -> if typeof (show = Batman.data(newNode, 'show')) == 'function' show.call newNode, before: sibling else fragment.appendChild newNode if --numPendingChildren == 0 parent.insertBefore fragment, sibling if collection.isSorted?() observers.reorder() fragment = document.createDocumentFragment() , localClone childRenderer.rendered => parentRenderer.allow 'rendered' parentRenderer.fire 'rendered' observers.remove = (items...) -> for item in items oldNode = nodeMap.get item nodeMap.unset item if oldNode? && typeof oldNode.hide is 'function' oldNode.hide yes else oldNode?.parentNode?.removeChild oldNode true observers.reorder = -> items = collection.toArray() for item in items thisNode = nodeMap.get(item) show = Batman.data thisNode, 'show' if typeof show is 'function' show.call thisNode, before: sibling else parent.insertBefore(thisNode, sibling) observers.arrayChange = (array) -> observers.remove(array...) observers.add(array...) # Observe the collection for events in the future if collection if collection.observe collection.observe 'itemsWereAdded', observers.add collection.observe 'itemsWereRemoved', observers.remove if collection.setWasSorted collection.observe 'setWasSorted', observers.reorder else collection.observe 'toArray', observers.arrayChange # Add all the already existing items. For hash-likes, add the key. if collection.forEach collection.forEach (item) -> observers.add(item) else if collection.get && array = collection.get('toArray') observers.add(array...) else for k, v of collection observers.add(k) else developer.warn "Warning! data-foreach-#{iteratorName} called with an undefined binding. Key was: #{key}." , -> ) false # Return false so the Renderer doesn't descend into this node's children. formfor: (node, localName, key, context) -> binding = context.addKeyToScopeForNode(node, key, localName) Batman.DOM.events.submit node, (node, e) -> $preventDefault e } # `Batman.DOM.binders` contains functions used to create element bindings # These are called via `Batman.DOM.readers` or `Batman.DOM.attrReaders` binders: { select: (node, key, context, renderer, only) -> [boundValue, container] = context.findKey key updateSelectBinding = => # Gather the selected options and update the binding selections = if node.multiple then (c.value for c in node.children when c.selected) else node.value selections = selections[0] if selections.length == 1 container.set key, selections updateOptionBindings = => # Go through the option nodes and update their bindings using the # context and key attached to the node via Batman.data for child in node.children if data = Batman.data(child, 'selected') if (subContext = data.context) and (subKey = data.key) [subBoundValue, subContainer] = subContext.findKey subKey unless child.selected == subBoundValue subContainer.set subKey, child.selected # wait for the select to render before binding to it renderer.rendered -> # Update the select box with the binding's new value. dataChange = (newValue) -> # For multi-select boxes, the `value` property only holds the first # selection, so we need to go through the child options and update # as necessary. if newValue instanceof Array # Use a hash to map values to their nodes to avoid O(n^2). valueToChild = {} for child in node.children # Clear all options. child.selected = false # Avoid collisions among options with same values. matches = valueToChild[child.value] if matches then matches.push child else matches = [child] valueToChild[child.value] = matches # Select options corresponding to the new values for value in newValue for match in valueToChild[value] match.selected = yes # For a regular select box, we just update the value. else node.value = newValue # Finally, we need to update the options' `selected` bindings updateOptionBindings() # Update the bindings with the node's new value nodeChange = -> updateSelectBinding() updateOptionBindings() # Expose the updateSelectBinding helper for the child options Batman.data node, 'updateBinding', updateSelectBinding # Create the binding context.bind node, key, dataChange, nodeChange, only radio: (node, key, context, renderer, only) -> dataChange = (value) -> # don't overwrite `checked` attributes in the HTML unless a bound # value is defined in the context. if no bound value is found, bind # to the key if the node is checked. [boundValue, container] = context.findKey key if boundValue node.checked = boundValue == node.value else if node.checked container.set key, node.value nodeChange = (newNode, subContext) -> subContext.set(key, Batman.DOM.attrReaders._parseAttribute(node.value)) context.bind node, key, dataChange, nodeChange, only file: (node, key, context, renderer, only) -> context.bind(node, key, -> developer.warn "Can't write to file inputs! Tried to on key #{key}." , (node, subContext) -> if subContext instanceof RenderContext.BindingProxy actualObject = subContext.binding.get('filteredValue') else actualObject = subContext if actualObject.hasStorage && actualObject.hasStorage() for adapter in actualObject._batman.get('storage') when adapter instanceof Batman.RestStorage adapter.defaultOptions.formData = true if node.hasAttribute('multiple') subContext.set key, Array::slice.call(node.files) else subContext.set key, node.files[0] , only) } # `Batman.DOM.events` contains the helpers used for binding to events. These aren't called by # DOM directives, but are used to handle specific events by the `data-event-#{name}` helper. events: { click: (node, callback, eventName = 'click') -> $addEventListener node, eventName, (args...) -> callback node, args... $preventDefault args[0] if node.nodeName.toUpperCase() is 'A' and not node.href node.href = '#' node doubleclick: (node, callback) -> Batman.DOM.events.click node, callback, 'dblclick' change: (node, callback) -> eventNames = switch node.nodeName.toUpperCase() when 'TEXTAREA' then ['keyup', 'change'] when 'INPUT' if node.type.toUpperCase() is 'TEXT' oldCallback = callback callback = (e) -> return if e.type == 'keyup' && 13 <= e.keyCode <= 14 oldCallback(arguments...) ['keyup', 'change'] else ['change'] else ['change'] for eventName in eventNames $addEventListener node, eventName, (args...) -> callback node, args... submit: (node, callback) -> if Batman.DOM.nodeIsEditable(node) $addEventListener node, 'keyup', (args...) -> if args[0].keyCode is 13 || args[0].which is 13 || args[0].keyIdentifier is 'Enter' || args[0].key is 'Enter' $preventDefault args[0] callback node, args... else $addEventListener node, 'submit', (args...) -> $preventDefault args[0] callback node, args... node } # `yield` and `contentFor` are used to declare partial views and then pull them in elsewhere. # This can be used for abstraction as well as repetition. yield: (name, node) -> yields = Batman.DOM._yields ||= {} yields[name] = node if (content = Batman.DOM._yieldContents?[name]) node.innerHTML = '' node.appendChild(content) if content contentFor: (name, node) -> contents = Batman.DOM._yieldContents ||= {} contents[name] = node if (yield = Batman.DOM._yields?[name]) content = if $isChildOf(yield, node) then node.cloneNode(true) else node yield.innerHTML = '' yield.appendChild(content) if content valueForNode: (node, value = '') -> isSetting = arguments.length > 1 switch node.nodeName.toUpperCase() when 'INPUT' if isSetting then (node.value = value) else node.value when 'TEXTAREA' if isSetting node.innerHTML = node.value = value else node.innerHTML when 'SELECT' node.value = value else if isSetting then (node.innerHTML = value) else node.innerHTML nodeIsEditable: (node) -> node.nodeName.toUpperCase() in ['INPUT', 'TEXTAREA', 'SELECT'] # `$addEventListener uses attachEvent when necessary addEventListener: $addEventListener = if window?.addEventListener ((node, eventName, callback) -> node.addEventListener eventName, callback, false) else ((node, eventName, callback) -> node.attachEvent "on#{eventName}", callback) # `$removeEventListener` uses detachEvent when necessary removeEventListener: $removeEventListener = if window?.removeEventListener ((elem, eventType, handler) -> elem.removeEventListener eventType, handler, false) else ((elem, eventType, handler) -> elem.detachEvent 'on'+eventType, handler) } # Filters # ------- # # `Batman.Filters` contains the simple, determininistic tranforms used in view bindings to # make life a little easier. buntUndefined = (f) -> (value) -> if typeof value is 'undefined' undefined else f.apply(@, arguments) filters = Batman.Filters = get: buntUndefined (value, key) -> if value.get? value.get(key) else value[key] equals: buntUndefined (lhs, rhs) -> lhs is rhs not: (value) -> ! !!value truncate: buntUndefined (value, length, end = "...") -> if value.length > length value = value.substr(0, length-end.length) + end value default: (value, string) -> value || string prepend: (value, string) -> string + value append: (value, string) -> value + string downcase: buntUndefined (value) -> value.toLowerCase() upcase: buntUndefined (value) -> value.toUpperCase() pluralize: buntUndefined (string, count) -> helpers.pluralize(count, string) join: buntUndefined (value, byWhat = '') -> value.join(byWhat) sort: buntUndefined (value) -> value.sort() map: buntUndefined (value, key) -> value.map((x) -> x[key]) first: buntUndefined (value) -> value[0] meta: buntUndefined (value, keypath) -> value.meta.get(keypath) for k in ['capitalize', 'singularize', 'underscore', 'camelize'] filters[k] = buntUndefined helpers[k] developer.addFilters() # Data # ---- $mixin Batman, cache: {} uuid: 0 expando: "batman" + Math.random().toString().replace(/\D/g, '') canDeleteExpando: true noData: # these throw exceptions if you attempt to add expandos to them "embed": true, # Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true hasData: (elem) -> elem = (if elem.nodeType then Batman.cache[elem[Batman.expando]] else elem[Batman.expando]) !!elem and !isEmptyDataObject(elem) data: (elem, name, data, pvt) -> # pvt is for internal use only return unless Batman.acceptData(elem) internalKey = Batman.expando getByName = typeof name == "string" # DOM nodes and JS objects have to be handled differently because IE6-7 can't # GC object references properly across the DOM-JS boundary isNode = elem.nodeType # Only DOM nodes need the global cache; JS object data is attached directly so GC # can occur automatically cache = if isNode then Batman.cache else elem # Only defining an ID for JS objects if its cache already exists allows # the code to shortcut on the same path as a DOM node with no cache id = if isNode then elem[Batman.expando] else elem[Batman.expando] && Batman.expando # Avoid doing any more work than we need to when trying to get data on an # object that has no data at all if (not id or (pvt and id and (cache[id] and not cache[id][internalKey]))) and getByName and data == undefined return unless id # Only DOM nodes need a new unique ID for each element since their data # ends up in the global cache if isNode elem[Batman.expando] = id = ++Batman.uuid else id = Batman.expando cache[id] = {} unless cache[id] # An object can be passed to Batman.data instead of a key/value pair; this gets # shallow copied over onto the existing cache if typeof name == "object" or typeof name == "function" if pvt cache[id][internalKey] = $mixin(cache[id][internalKey], name) else cache[id] = $mixin(cache[id], name) thisCache = cache[id] # Internal Batman data is stored in a separate object inside the object's data # cache in order to avoid key collisions between internal data and user-defined # data if pvt thisCache[internalKey] = {} unless thisCache[internalKey] thisCache = thisCache[internalKey] unless data is undefined thisCache[helpers.camelize(name, true)] = data # Check for both converted-to-camel and non-converted data property names # If a data property was specified if getByName # First try to find as-is property data ret = thisCache[name] # Test for null|undefined property data and try to find camel-cased property ret = thisCache[helpers.camelize(name, true)] unless ret? else ret = thisCache return ret removeData: (elem, name, pvt) -> # pvt is for internal use only return unless Batman.acceptData(elem) internalKey = Batman.expando isNode = elem.nodeType # non DOM-nodes have their data attached directly cache = if isNode then Batman.cache else elem id = if isNode then elem[Batman.expando] else Batman.expando # If there is already no cache entry for this object, there is no # purpose in continuing return unless cache[id] if name thisCache = if pvt then cache[id][internalKey] else cache[id] if thisCache # Support interoperable removal of hyphenated or camelcased keys name = helpers.camelize(name, true) unless thisCache[name] delete thisCache[name] # If there is no data left in the cache, we want to continue # and let the cache object itself get destroyed return unless isEmptyDataObject(thisCache) if pvt delete cache[id][internalKey] # Don't destroy the parent cache unless the internal data object # had been the only thing left in it return unless isEmptyDataObject(cache[id]) internalCache = cache[id][internalKey] # Browsers that fail expando deletion also refuse to delete expandos on # the window, but it will allow it on all other JS objects; other browsers # don't care # Ensure that `cache` is not a window object if Batman.canDeleteExpando or !cache.setInterval delete cache[id] else cache[id] = null # We destroyed the entire user cache at once because it's faster than # iterating through each key, but we need to continue to persist internal # data if it existed if internalCache cache[id] = {} cache[id][internalKey] = internalCache # Otherwise, we need to eliminate the expando on the node to avoid # false lookups in the cache for entries that no longer exist else if isNode if Batman.canDeleteExpando delete elem[Batman.expando] else if elem.removeAttribute elem.removeAttribute Batman.expando else elem[Batman.expando] = null # For internal use only _data: (elem, name, data) -> Batman.data elem, name, data, true # A method for determining if a DOM node can handle the data expando acceptData: (elem) -> if elem.nodeName match = Batman.noData[elem.nodeName.toLowerCase()] if match return !(match == true or elem.getAttribute("classid") != match) return true isEmptyDataObject = (obj) -> for name of obj return false return true # Test to see if it's possible to delete an expando from an element # Fails in Internet Explorer try div = document.createElement 'div' delete div.test catch e Batman.canDeleteExpando = false # Mixins # ------ mixins = Batman.mixins = new Batman.Object() # Encoders # ------ Batman.Encoders = railsDate: encode: (value) -> value decode: (value) -> a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value) if a return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])) else developer.error "Unrecognized rails date #{value}!" # Export a few globals, and grab a reference to an object accessible from all contexts for use elsewhere. # In node, the container is the `global` object, and in the browser, the container is the window object. container = if exports? module.exports = Batman global else window.Batman = Batman window $mixin container, Batman.Observable # Optionally export global sugar. Not sure what to do with this. Batman.exportHelpers = (onto) -> for k in ['mixin', 'unmixin', 'route', 'redirect', 'event', 'eventOneShot', 'typeOf', 'redirect'] onto["$#{k}"] = Batman[k] onto Batman.exportGlobals = () -> Batman.exportHelpers(container)
[ { "context": "sages' }\n { fn:fetchPrivateMessages, key: 'privateMessages' }\n { fn:fetchBotChannel, key: 'bot' }\n", "end": 2743, "score": 0.5900523662567139, "start": 2728, "tag": "KEY", "value": "privateMessages" } ]
workers/social/lib/social/cache/socialapi.coffee
ezgikaysi/koding
1
async = require 'async' SocialChannel = require '../models/socialapi/channel' SocialMessage = require '../models/socialapi/message' JAccount = require '../models/account' KodingError = require '../error' module.exports = (options = {}, callback) -> { client, entryPoint, params, session } = options { clientId: sessionToken } = session if session defaultOptions = limit: 5 fetchPopularPosts = (cb) -> opt = channelName : params?.section or 'Public' limit : 10 SocialChannel.fetchPopularPosts client, opt, cb fetchPopularTopics = (cb) -> opt = type : 'weekly' channelName : 'koding' limit : 5 SocialChannel.fetchPopularTopics opt, cb fetchFollowedChannels = (cb) -> options = limit : 8 SocialChannel.fetchFollowedChannels client, options, cb fetchPinnedMessages = (cb) -> SocialChannel.fetchPinnedMessages client, defaultOptions, cb fetchPrivateMessages = (cb) -> options = limit : 10 SocialMessage.fetchPrivateMessages client, options, cb fetchBotChannel = (cb) -> SocialChannel.fetchBotChannel client, cb fetchGroupActivities = (cb) -> SocialChannel.fetchGroupActivities client, { sessionToken }, cb fetchChannelActivities = (channelName, cb) -> # fetch channel first SocialChannel.byName client, { name: channelName }, (err, data) -> return cb err if err return cb new KodingError 'channel is not set' unless data?.channel # then fetch activity with channel id SocialChannel.fetchActivities client, { id: data.channel.id, sessionToken }, cb fetchProfileFeed = (client, params, cb) -> JAccount.one { 'profile.nickname': entryPoint.slug }, (err, account) -> return cb err if err return cb new KodingError 'account not found' unless account SocialChannel.fetchProfileFeed client, { targetId: account.socialApiId }, cb fetchActivitiesForNavigatedURL = (params, cb) -> return cb null, null unless params switch params.section when 'Topic' then fetchChannelActivities params.slug, cb when 'Message' then SocialChannel.fetchActivities client, { id: params.slug, sessionToken }, cb when 'Post' then SocialMessage.bySlug client, { slug: params.slug }, cb when 'Announcement' then cb new KodingError 'announcement not implemented' else fetchGroupActivities cb reqs = [ { fn:fetchPopularPosts, key: 'popularPosts' } { fn:fetchFollowedChannels, key: 'followedChannels' } # pinned message channel is no-longer used # { fn:fetchPinnedMessages, key: 'pinnedMessages' } { fn:fetchPrivateMessages, key: 'privateMessages' } { fn:fetchBotChannel, key: 'bot' } ] handleQueue fetchActivitiesForNavigatedURL, reqs, params, callback handleQueue = (fetchActivitiesForNavigatedURL, reqs, params, callback) -> queue = reqs.map (req) -> (fin) -> req.fn (err, data) -> queue.localPrefetchedFeeds or= {} queue.localPrefetchedFeeds[req.key] = data fin() queue.push (fin) -> fetchActivitiesForNavigatedURL params, (err, data) -> queue.localPrefetchedFeeds or= {} res = name: params?.name or 'Activity' section: params?.section or 'Public' slug: params?.slug or '/' data: data queue.localPrefetchedFeeds.navigated = res unless err? fin() async.parallel queue, -> callback null, queue.localPrefetchedFeeds
86612
async = require 'async' SocialChannel = require '../models/socialapi/channel' SocialMessage = require '../models/socialapi/message' JAccount = require '../models/account' KodingError = require '../error' module.exports = (options = {}, callback) -> { client, entryPoint, params, session } = options { clientId: sessionToken } = session if session defaultOptions = limit: 5 fetchPopularPosts = (cb) -> opt = channelName : params?.section or 'Public' limit : 10 SocialChannel.fetchPopularPosts client, opt, cb fetchPopularTopics = (cb) -> opt = type : 'weekly' channelName : 'koding' limit : 5 SocialChannel.fetchPopularTopics opt, cb fetchFollowedChannels = (cb) -> options = limit : 8 SocialChannel.fetchFollowedChannels client, options, cb fetchPinnedMessages = (cb) -> SocialChannel.fetchPinnedMessages client, defaultOptions, cb fetchPrivateMessages = (cb) -> options = limit : 10 SocialMessage.fetchPrivateMessages client, options, cb fetchBotChannel = (cb) -> SocialChannel.fetchBotChannel client, cb fetchGroupActivities = (cb) -> SocialChannel.fetchGroupActivities client, { sessionToken }, cb fetchChannelActivities = (channelName, cb) -> # fetch channel first SocialChannel.byName client, { name: channelName }, (err, data) -> return cb err if err return cb new KodingError 'channel is not set' unless data?.channel # then fetch activity with channel id SocialChannel.fetchActivities client, { id: data.channel.id, sessionToken }, cb fetchProfileFeed = (client, params, cb) -> JAccount.one { 'profile.nickname': entryPoint.slug }, (err, account) -> return cb err if err return cb new KodingError 'account not found' unless account SocialChannel.fetchProfileFeed client, { targetId: account.socialApiId }, cb fetchActivitiesForNavigatedURL = (params, cb) -> return cb null, null unless params switch params.section when 'Topic' then fetchChannelActivities params.slug, cb when 'Message' then SocialChannel.fetchActivities client, { id: params.slug, sessionToken }, cb when 'Post' then SocialMessage.bySlug client, { slug: params.slug }, cb when 'Announcement' then cb new KodingError 'announcement not implemented' else fetchGroupActivities cb reqs = [ { fn:fetchPopularPosts, key: 'popularPosts' } { fn:fetchFollowedChannels, key: 'followedChannels' } # pinned message channel is no-longer used # { fn:fetchPinnedMessages, key: 'pinnedMessages' } { fn:fetchPrivateMessages, key: '<KEY>' } { fn:fetchBotChannel, key: 'bot' } ] handleQueue fetchActivitiesForNavigatedURL, reqs, params, callback handleQueue = (fetchActivitiesForNavigatedURL, reqs, params, callback) -> queue = reqs.map (req) -> (fin) -> req.fn (err, data) -> queue.localPrefetchedFeeds or= {} queue.localPrefetchedFeeds[req.key] = data fin() queue.push (fin) -> fetchActivitiesForNavigatedURL params, (err, data) -> queue.localPrefetchedFeeds or= {} res = name: params?.name or 'Activity' section: params?.section or 'Public' slug: params?.slug or '/' data: data queue.localPrefetchedFeeds.navigated = res unless err? fin() async.parallel queue, -> callback null, queue.localPrefetchedFeeds
true
async = require 'async' SocialChannel = require '../models/socialapi/channel' SocialMessage = require '../models/socialapi/message' JAccount = require '../models/account' KodingError = require '../error' module.exports = (options = {}, callback) -> { client, entryPoint, params, session } = options { clientId: sessionToken } = session if session defaultOptions = limit: 5 fetchPopularPosts = (cb) -> opt = channelName : params?.section or 'Public' limit : 10 SocialChannel.fetchPopularPosts client, opt, cb fetchPopularTopics = (cb) -> opt = type : 'weekly' channelName : 'koding' limit : 5 SocialChannel.fetchPopularTopics opt, cb fetchFollowedChannels = (cb) -> options = limit : 8 SocialChannel.fetchFollowedChannels client, options, cb fetchPinnedMessages = (cb) -> SocialChannel.fetchPinnedMessages client, defaultOptions, cb fetchPrivateMessages = (cb) -> options = limit : 10 SocialMessage.fetchPrivateMessages client, options, cb fetchBotChannel = (cb) -> SocialChannel.fetchBotChannel client, cb fetchGroupActivities = (cb) -> SocialChannel.fetchGroupActivities client, { sessionToken }, cb fetchChannelActivities = (channelName, cb) -> # fetch channel first SocialChannel.byName client, { name: channelName }, (err, data) -> return cb err if err return cb new KodingError 'channel is not set' unless data?.channel # then fetch activity with channel id SocialChannel.fetchActivities client, { id: data.channel.id, sessionToken }, cb fetchProfileFeed = (client, params, cb) -> JAccount.one { 'profile.nickname': entryPoint.slug }, (err, account) -> return cb err if err return cb new KodingError 'account not found' unless account SocialChannel.fetchProfileFeed client, { targetId: account.socialApiId }, cb fetchActivitiesForNavigatedURL = (params, cb) -> return cb null, null unless params switch params.section when 'Topic' then fetchChannelActivities params.slug, cb when 'Message' then SocialChannel.fetchActivities client, { id: params.slug, sessionToken }, cb when 'Post' then SocialMessage.bySlug client, { slug: params.slug }, cb when 'Announcement' then cb new KodingError 'announcement not implemented' else fetchGroupActivities cb reqs = [ { fn:fetchPopularPosts, key: 'popularPosts' } { fn:fetchFollowedChannels, key: 'followedChannels' } # pinned message channel is no-longer used # { fn:fetchPinnedMessages, key: 'pinnedMessages' } { fn:fetchPrivateMessages, key: 'PI:KEY:<KEY>END_PI' } { fn:fetchBotChannel, key: 'bot' } ] handleQueue fetchActivitiesForNavigatedURL, reqs, params, callback handleQueue = (fetchActivitiesForNavigatedURL, reqs, params, callback) -> queue = reqs.map (req) -> (fin) -> req.fn (err, data) -> queue.localPrefetchedFeeds or= {} queue.localPrefetchedFeeds[req.key] = data fin() queue.push (fin) -> fetchActivitiesForNavigatedURL params, (err, data) -> queue.localPrefetchedFeeds or= {} res = name: params?.name or 'Activity' section: params?.section or 'Public' slug: params?.slug or '/' data: data queue.localPrefetchedFeeds.navigated = res unless err? fin() async.parallel queue, -> callback null, queue.localPrefetchedFeeds
[ { "context": "#\n#* $Id$\n#*\n#* Copyright 2014 Valentyn Kolesnikov\n#*\n#* Licensed under the Apache License, Version ", "end": 50, "score": 0.999854564666748, "start": 31, "tag": "NAME", "value": "Valentyn Kolesnikov" }, { "context": ".\n#\n\n###*\nUkrainianToLatin utility class.\n\n@author Valentyn Kolesnikov\n@version $Revision$ $Date$\n###\nStringBuilder = (-", "end": 677, "score": 0.9998804926872253, "start": 658, "tag": "NAME", "value": "Valentyn Kolesnikov" } ]
src/main/resources/com/github/ukrainiantolatin/ukrainiantolatin.coffee
HappyFacade/ukrainiantolatin
4
# #* $Id$ #* #* Copyright 2014 Valentyn Kolesnikov #* #* Licensed under the Apache License, Version 2.0 (the "License"); #* you may not use this file except in compliance with the License. #* You may obtain a copy of the License at #* #* http://www.apache.org/licenses/LICENSE-2.0 #* #* Unless required by applicable law or agreed to in writing, software #* distributed under the License is distributed on an "AS IS" BASIS, #* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #* See the License for the specific language governing permissions and #* limitations under the License. # ###* UkrainianToLatin utility class. @author Valentyn Kolesnikov @version $Revision$ $Date$ ### StringBuilder = (-> StringBuilder = -> @_buffer = [] return StringBuilder::append = (text) -> @_buffer[@_buffer.length] = text this StringBuilder::insert = (index, text) -> @_buffer.splice index, 0, text this StringBuilder::toString = -> @_buffer.join "" StringBuilder )() ConvertCase = (-> ConvertCase = (convert, lowcase) -> @convert = convert @lowcase = lowcase return ConvertCase )() UkrainianToLatin = (-> UkrainianToLatin = -> ###* Generates latinic from cyrilic. @param name the name @return the result ### UkrainianToLatin.generateLat = (name) -> @initialize() result = new StringBuilder() prevConvertCase = null for index in [0...name.length] curChar = name.substring(index, index + UkrainianToLatin.INDEX_1) nextChar = (if index is name.length - 1 then null else name.substring(index + UkrainianToLatin.INDEX_1, index + UkrainianToLatin.INDEX_2)) continue if curChar.match("[-'’,]") unless @cyrToLat[curChar]? if " " is curChar prevConvertCase = null result.append " " continue convertCase = @cyrToLat[curChar] unless prevConvertCase? @checkFirstChar result, convertCase, (if not @cyrToLat[nextChar]? then convertCase else @cyrToLat[nextChar]) else @checkMiddleChar result, convertCase, (if not @cyrToLat[nextChar]? then convertCase else @cyrToLat[nextChar]) prevConvertCase = convertCase index += 1 result.toString() UkrainianToLatin.checkFirstChar = (result, convertCase, nextConvertCase) -> latName = convertCase.convert switch latName.length when UkrainianToLatin.LENGTH_2 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_1).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_1) else latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_1).toUpperCase())) result.append (if nextConvertCase.lowcase then "g" else "G") if convertCase.convert is "ZZ" and nextConvertCase.convert is "HH" when UkrainianToLatin.LENGTH_3, UkrainianToLatin.LENGTH_4 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_2).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_2) else latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_2).toUpperCase())) when UkrainianToLatin.LENGTH_8 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_4).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_4) else latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_4).toUpperCase())) ###* @param result the output string @param convertCase the current char @param nextConvertCase the next char ### UkrainianToLatin.checkMiddleChar = (result, convertCase, nextConvertCase) -> latName = convertCase.convert switch latName.length when UkrainianToLatin.LENGTH_2 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_1, UkrainianToLatin.INDEX_2).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_1, UkrainianToLatin.INDEX_2) else latName.substring(UkrainianToLatin.INDEX_1, UkrainianToLatin.INDEX_2).toUpperCase())) result.append (if nextConvertCase.lowcase then "g" else "G") if convertCase.convert is "ZZ" and nextConvertCase.convert is "HH" when UkrainianToLatin.LENGTH_3 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_3).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_3) else latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_3).toUpperCase())) when UkrainianToLatin.LENGTH_4 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_4).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_4) else latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_4).toUpperCase())) when UkrainianToLatin.LENGTH_8 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_4, UkrainianToLatin.INDEX_8).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_4, UkrainianToLatin.INDEX_8) else latName.substring(UkrainianToLatin.INDEX_4, UkrainianToLatin.INDEX_8).toUpperCase())) UkrainianToLatin.initialize = -> @cyrToLat = {} for convert of UkrainianToLatin.Convert @cyrToLat[UkrainianToLatin.Convert[convert].substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_1)] = new ConvertCase(convert, false) @cyrToLat[UkrainianToLatin.Convert[convert].substring(UkrainianToLatin.INDEX_1, UkrainianToLatin.INDEX_2)] = new ConvertCase(convert, true) if convert is UkrainianToLatin.Convert.EE @cyrToLat["Ё"] = new ConvertCase(convert, false) @cyrToLat["ё"] = new ConvertCase(convert, true) return UkrainianToLatin.INDEX_0 = 0 UkrainianToLatin.INDEX_1 = 1 UkrainianToLatin.INDEX_2 = 2 UkrainianToLatin.INDEX_3 = 3 UkrainianToLatin.INDEX_4 = 4 UkrainianToLatin.INDEX_8 = 8 UkrainianToLatin.LENGTH_2 = 2 UkrainianToLatin.LENGTH_3 = 3 UkrainianToLatin.LENGTH_4 = 4 UkrainianToLatin.LENGTH_8 = 8 UkrainianToLatin.cyrToLat = {} UkrainianToLatin.Convert = AA: "Аа" BB: "Бб" VV: "Вв" HH: "Гг" GG: "Ґґ" DD: "Дд" EE: "Ее" YeIe: "Єє" ZhZh: "Жж" ZZ: "Зз" YY: "Ии" II: "Іі" YiI: "Її" YI: "Йй" KK: "Кк" LL: "Лл" MM: "Мм" NN: "Нн" OO: "Оо" PP: "Пп" RR: "Рр" SS: "Сс" TT: "Тт" UU: "Уу" FF: "Фф" KhKh: "Хх" TsTs: "Цц" ChCh: "Чч" ShSh: "Шш" ShchShch: "Щщ" YuIu: "Юю" YaIa: "Яя" UkrainianToLatin )() module.exports = UkrainianToLatin: UkrainianToLatin
196846
# #* $Id$ #* #* Copyright 2014 <NAME> #* #* Licensed under the Apache License, Version 2.0 (the "License"); #* you may not use this file except in compliance with the License. #* You may obtain a copy of the License at #* #* http://www.apache.org/licenses/LICENSE-2.0 #* #* Unless required by applicable law or agreed to in writing, software #* distributed under the License is distributed on an "AS IS" BASIS, #* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #* See the License for the specific language governing permissions and #* limitations under the License. # ###* UkrainianToLatin utility class. @author <NAME> @version $Revision$ $Date$ ### StringBuilder = (-> StringBuilder = -> @_buffer = [] return StringBuilder::append = (text) -> @_buffer[@_buffer.length] = text this StringBuilder::insert = (index, text) -> @_buffer.splice index, 0, text this StringBuilder::toString = -> @_buffer.join "" StringBuilder )() ConvertCase = (-> ConvertCase = (convert, lowcase) -> @convert = convert @lowcase = lowcase return ConvertCase )() UkrainianToLatin = (-> UkrainianToLatin = -> ###* Generates latinic from cyrilic. @param name the name @return the result ### UkrainianToLatin.generateLat = (name) -> @initialize() result = new StringBuilder() prevConvertCase = null for index in [0...name.length] curChar = name.substring(index, index + UkrainianToLatin.INDEX_1) nextChar = (if index is name.length - 1 then null else name.substring(index + UkrainianToLatin.INDEX_1, index + UkrainianToLatin.INDEX_2)) continue if curChar.match("[-'’,]") unless @cyrToLat[curChar]? if " " is curChar prevConvertCase = null result.append " " continue convertCase = @cyrToLat[curChar] unless prevConvertCase? @checkFirstChar result, convertCase, (if not @cyrToLat[nextChar]? then convertCase else @cyrToLat[nextChar]) else @checkMiddleChar result, convertCase, (if not @cyrToLat[nextChar]? then convertCase else @cyrToLat[nextChar]) prevConvertCase = convertCase index += 1 result.toString() UkrainianToLatin.checkFirstChar = (result, convertCase, nextConvertCase) -> latName = convertCase.convert switch latName.length when UkrainianToLatin.LENGTH_2 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_1).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_1) else latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_1).toUpperCase())) result.append (if nextConvertCase.lowcase then "g" else "G") if convertCase.convert is "ZZ" and nextConvertCase.convert is "HH" when UkrainianToLatin.LENGTH_3, UkrainianToLatin.LENGTH_4 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_2).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_2) else latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_2).toUpperCase())) when UkrainianToLatin.LENGTH_8 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_4).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_4) else latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_4).toUpperCase())) ###* @param result the output string @param convertCase the current char @param nextConvertCase the next char ### UkrainianToLatin.checkMiddleChar = (result, convertCase, nextConvertCase) -> latName = convertCase.convert switch latName.length when UkrainianToLatin.LENGTH_2 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_1, UkrainianToLatin.INDEX_2).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_1, UkrainianToLatin.INDEX_2) else latName.substring(UkrainianToLatin.INDEX_1, UkrainianToLatin.INDEX_2).toUpperCase())) result.append (if nextConvertCase.lowcase then "g" else "G") if convertCase.convert is "ZZ" and nextConvertCase.convert is "HH" when UkrainianToLatin.LENGTH_3 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_3).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_3) else latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_3).toUpperCase())) when UkrainianToLatin.LENGTH_4 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_4).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_4) else latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_4).toUpperCase())) when UkrainianToLatin.LENGTH_8 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_4, UkrainianToLatin.INDEX_8).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_4, UkrainianToLatin.INDEX_8) else latName.substring(UkrainianToLatin.INDEX_4, UkrainianToLatin.INDEX_8).toUpperCase())) UkrainianToLatin.initialize = -> @cyrToLat = {} for convert of UkrainianToLatin.Convert @cyrToLat[UkrainianToLatin.Convert[convert].substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_1)] = new ConvertCase(convert, false) @cyrToLat[UkrainianToLatin.Convert[convert].substring(UkrainianToLatin.INDEX_1, UkrainianToLatin.INDEX_2)] = new ConvertCase(convert, true) if convert is UkrainianToLatin.Convert.EE @cyrToLat["Ё"] = new ConvertCase(convert, false) @cyrToLat["ё"] = new ConvertCase(convert, true) return UkrainianToLatin.INDEX_0 = 0 UkrainianToLatin.INDEX_1 = 1 UkrainianToLatin.INDEX_2 = 2 UkrainianToLatin.INDEX_3 = 3 UkrainianToLatin.INDEX_4 = 4 UkrainianToLatin.INDEX_8 = 8 UkrainianToLatin.LENGTH_2 = 2 UkrainianToLatin.LENGTH_3 = 3 UkrainianToLatin.LENGTH_4 = 4 UkrainianToLatin.LENGTH_8 = 8 UkrainianToLatin.cyrToLat = {} UkrainianToLatin.Convert = AA: "Аа" BB: "Бб" VV: "Вв" HH: "Гг" GG: "Ґґ" DD: "Дд" EE: "Ее" YeIe: "Єє" ZhZh: "Жж" ZZ: "Зз" YY: "Ии" II: "Іі" YiI: "Її" YI: "Йй" KK: "Кк" LL: "Лл" MM: "Мм" NN: "Нн" OO: "Оо" PP: "Пп" RR: "Рр" SS: "Сс" TT: "Тт" UU: "Уу" FF: "Фф" KhKh: "Хх" TsTs: "Цц" ChCh: "Чч" ShSh: "Шш" ShchShch: "Щщ" YuIu: "Юю" YaIa: "Яя" UkrainianToLatin )() module.exports = UkrainianToLatin: UkrainianToLatin
true
# #* $Id$ #* #* Copyright 2014 PI:NAME:<NAME>END_PI #* #* Licensed under the Apache License, Version 2.0 (the "License"); #* you may not use this file except in compliance with the License. #* You may obtain a copy of the License at #* #* http://www.apache.org/licenses/LICENSE-2.0 #* #* Unless required by applicable law or agreed to in writing, software #* distributed under the License is distributed on an "AS IS" BASIS, #* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #* See the License for the specific language governing permissions and #* limitations under the License. # ###* UkrainianToLatin utility class. @author PI:NAME:<NAME>END_PI @version $Revision$ $Date$ ### StringBuilder = (-> StringBuilder = -> @_buffer = [] return StringBuilder::append = (text) -> @_buffer[@_buffer.length] = text this StringBuilder::insert = (index, text) -> @_buffer.splice index, 0, text this StringBuilder::toString = -> @_buffer.join "" StringBuilder )() ConvertCase = (-> ConvertCase = (convert, lowcase) -> @convert = convert @lowcase = lowcase return ConvertCase )() UkrainianToLatin = (-> UkrainianToLatin = -> ###* Generates latinic from cyrilic. @param name the name @return the result ### UkrainianToLatin.generateLat = (name) -> @initialize() result = new StringBuilder() prevConvertCase = null for index in [0...name.length] curChar = name.substring(index, index + UkrainianToLatin.INDEX_1) nextChar = (if index is name.length - 1 then null else name.substring(index + UkrainianToLatin.INDEX_1, index + UkrainianToLatin.INDEX_2)) continue if curChar.match("[-'’,]") unless @cyrToLat[curChar]? if " " is curChar prevConvertCase = null result.append " " continue convertCase = @cyrToLat[curChar] unless prevConvertCase? @checkFirstChar result, convertCase, (if not @cyrToLat[nextChar]? then convertCase else @cyrToLat[nextChar]) else @checkMiddleChar result, convertCase, (if not @cyrToLat[nextChar]? then convertCase else @cyrToLat[nextChar]) prevConvertCase = convertCase index += 1 result.toString() UkrainianToLatin.checkFirstChar = (result, convertCase, nextConvertCase) -> latName = convertCase.convert switch latName.length when UkrainianToLatin.LENGTH_2 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_1).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_1) else latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_1).toUpperCase())) result.append (if nextConvertCase.lowcase then "g" else "G") if convertCase.convert is "ZZ" and nextConvertCase.convert is "HH" when UkrainianToLatin.LENGTH_3, UkrainianToLatin.LENGTH_4 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_2).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_2) else latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_2).toUpperCase())) when UkrainianToLatin.LENGTH_8 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_4).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_4) else latName.substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_4).toUpperCase())) ###* @param result the output string @param convertCase the current char @param nextConvertCase the next char ### UkrainianToLatin.checkMiddleChar = (result, convertCase, nextConvertCase) -> latName = convertCase.convert switch latName.length when UkrainianToLatin.LENGTH_2 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_1, UkrainianToLatin.INDEX_2).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_1, UkrainianToLatin.INDEX_2) else latName.substring(UkrainianToLatin.INDEX_1, UkrainianToLatin.INDEX_2).toUpperCase())) result.append (if nextConvertCase.lowcase then "g" else "G") if convertCase.convert is "ZZ" and nextConvertCase.convert is "HH" when UkrainianToLatin.LENGTH_3 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_3).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_3) else latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_3).toUpperCase())) when UkrainianToLatin.LENGTH_4 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_4).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_4) else latName.substring(UkrainianToLatin.INDEX_2, UkrainianToLatin.INDEX_4).toUpperCase())) when UkrainianToLatin.LENGTH_8 result.append (if convertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_4, UkrainianToLatin.INDEX_8).toLowerCase() else (if nextConvertCase.lowcase then latName.substring(UkrainianToLatin.INDEX_4, UkrainianToLatin.INDEX_8) else latName.substring(UkrainianToLatin.INDEX_4, UkrainianToLatin.INDEX_8).toUpperCase())) UkrainianToLatin.initialize = -> @cyrToLat = {} for convert of UkrainianToLatin.Convert @cyrToLat[UkrainianToLatin.Convert[convert].substring(UkrainianToLatin.INDEX_0, UkrainianToLatin.INDEX_1)] = new ConvertCase(convert, false) @cyrToLat[UkrainianToLatin.Convert[convert].substring(UkrainianToLatin.INDEX_1, UkrainianToLatin.INDEX_2)] = new ConvertCase(convert, true) if convert is UkrainianToLatin.Convert.EE @cyrToLat["Ё"] = new ConvertCase(convert, false) @cyrToLat["ё"] = new ConvertCase(convert, true) return UkrainianToLatin.INDEX_0 = 0 UkrainianToLatin.INDEX_1 = 1 UkrainianToLatin.INDEX_2 = 2 UkrainianToLatin.INDEX_3 = 3 UkrainianToLatin.INDEX_4 = 4 UkrainianToLatin.INDEX_8 = 8 UkrainianToLatin.LENGTH_2 = 2 UkrainianToLatin.LENGTH_3 = 3 UkrainianToLatin.LENGTH_4 = 4 UkrainianToLatin.LENGTH_8 = 8 UkrainianToLatin.cyrToLat = {} UkrainianToLatin.Convert = AA: "Аа" BB: "Бб" VV: "Вв" HH: "Гг" GG: "Ґґ" DD: "Дд" EE: "Ее" YeIe: "Єє" ZhZh: "Жж" ZZ: "Зз" YY: "Ии" II: "Іі" YiI: "Її" YI: "Йй" KK: "Кк" LL: "Лл" MM: "Мм" NN: "Нн" OO: "Оо" PP: "Пп" RR: "Рр" SS: "Сс" TT: "Тт" UU: "Уу" FF: "Фф" KhKh: "Хх" TsTs: "Цц" ChCh: "Чч" ShSh: "Шш" ShchShch: "Щщ" YuIu: "Юю" YaIa: "Яя" UkrainianToLatin )() module.exports = UkrainianToLatin: UkrainianToLatin
[ { "context": "er fabricate 'partner'\n @partner.set 'email', \"info@gagosian.com\"\n\n afterEach ->\n Backbone.sync.restore()\n\n d", "end": 427, "score": 0.9999121427536011, "start": 410, "tag": "EMAIL", "value": "info@gagosian.com" }, { "context": "ld', ->\n @mailto.query.should.containEql \"cc=inquiries@artsy.net\"\n\n it 'populates the subject field', ->\n ", "end": 4227, "score": 0.9997032880783081, "start": 4208, "tag": "EMAIL", "value": "inquiries@artsy.net" }, { "context": "Backbone.Model artist: fabricate('artist', name: 'Bitty'), represented_by: false, image_versions: ['tiny'", "end": 4861, "score": 0.999709963798523, "start": 4856, "tag": "NAME", "value": "Bitty" }, { "context": "nerArtist)\n artist.get('name').should.equal 'Bitty'\n artist.get('image_versions').length.should", "end": 5044, "score": 0.9997591376304626, "start": 5039, "tag": "NAME", "value": "Bitty" }, { "context": "Backbone.Model artist: fabricate('artist', name: 'Bitty'), represented_by: false, image_versions: null, i", "end": 5379, "score": 0.9997619390487671, "start": 5374, "tag": "NAME", "value": "Bitty" }, { "context": "nerArtist)\n artist.get('name').should.equal 'Bitty'\n artist.get('image_versions')?.should.not.b", "end": 5558, "score": 0.9997739791870117, "start": 5553, "tag": "NAME", "value": "Bitty" } ]
src/mobile/test/models/partner.coffee
kanaabe/force
1
urlParser = require 'url' sinon = require 'sinon' Backbone = require 'backbone' Partner = require '../../models/partner' PartnerLocations = require '../../collections/partner_locations' Artist = require '../../models/artist' { fabricate } = require 'antigravity' describe 'Partner', -> beforeEach -> sinon.stub Backbone, 'sync' @partner = new Partner fabricate 'partner' @partner.set 'email', "info@gagosian.com" afterEach -> Backbone.sync.restore() describe '#fetchLocations', -> it 'fetches locations', -> @partner.set(id: 'moobar').fetchLocations() Backbone.sync.args[0][1].url().should.containEql 'partner/moobar/locations' describe "#fetchArtistGroups", -> it 'fetches the partners artists and groups them in represented/unreped, taking image info from the partner artist relation', (done) -> @partner.fetchArtistGroups success: (represented, unrepresented) -> represented.length.should.equal 2 unrepresented.length.should.equal 1 unrepresented.models[0].get('image_versions')[0].should.equal 'tiny' unrepresented.models[0].get('image_url').should.equal 'bitty.jpg' done() Backbone.sync.args[0][2].success [ { artist: fabricate('artist'), represented_by: true } { artist: fabricate('artist'), represented_by: true } { artist: fabricate('artist'), represented_by: false, image_versions: ['tiny'], image_url: 'bitty.jpg', published_artworks_count: 0 } { artist: fabricate('artist'), represented_by: false, image_versions: ['tiny'], image_url: 'bitty.jpg', published_artworks_count: 1 } ] Backbone.sync.args[0][2].success [] it 'only returns unrepresented artists with published works', (done) -> @partner.fetchArtistGroups success: (represented, unrepresented) -> unrepresented.length.should.equal 1 unrepresented.models[0].get('name').should.equal 'artist with published works' unrepresented.where(name: 'artist without published works').should.have.lengthOf 0 done() Backbone.sync.args[0][2].success [ { artist: fabricate('artist'), represented_by: true } { artist: fabricate('artist', name: 'artist with published works'), published_artworks_count: 2, represented_by: false } { artist: fabricate('artist', name: 'artist without published works'), published_artworks_count: 0, represented_by: false } ] Backbone.sync.args[0][2].success [] it 'requests partner artists that have not been explicity hidden from the profile', -> @partner.fetchArtistGroups success: (represented, unrepresented) -> done() Backbone.sync.args[0][2].data.display_on_partner_profile.should.equal 1 describe '#fetchFeaturedShow', -> it 'fetches the partners shows and returns one that is featured', (done) -> @partner.fetchFeaturedShow success: (show) -> show.get('id').should.equal 'bitty' done() featuredShow = fabricate 'show', id: 'bitty', featured: true unfeaturedShow = fabricate 'show', id: 'some-other-cat', featured: false Backbone.sync.args[0][2].success [ featuredShow, unfeaturedShow ] Backbone.sync.args[0][2].success [] describe '#setEmailFromLocations', -> beforeEach -> @partnerLocations = new PartnerLocations [fabricate 'partner_location'] it 'does nothing if the partner has an email address set already', -> email = @partner.get 'email' @partner.setEmailFromLocations @partnerLocations @partner.get('email').should.equal email it 'sets the first locations email address to a partner', -> @partner.set 'email', '' @partner.setEmailFromLocations @partnerLocations @partner.get('email').should.equal @partnerLocations.first().get 'email' describe '#getMailTo', -> beforeEach -> @mailto = urlParser.parse @partner.getMailTo() it 'returns an email link', -> @mailto.href.should.containEql "mailto:" it 'ignores a emails for non gallery partners', -> @partner.set 'type', 'Institution' @partner.getMailTo().should.equal '' it 'includes artsy in the CC field', -> @mailto.query.should.containEql "cc=inquiries@artsy.net" it 'populates the subject field', -> @mailto.query.should.containEql 'subject=' @mailto.query.should.containEql encodeURIComponent("Connecting with #{@partner.get('name')} via Artsy") describe '#getSimpleWebsite', -> it 'removes "http://" and trailing slashes', -> @partner.set 'website', "http://www.lacma.org/" @partner.getSimpleWebsite().should == "www.lacma.org" describe '#artistFromPartnerArtist', -> it 'creates an artist model from the partner artist relationship, copying over the image info', -> partnerArtist = new Backbone.Model artist: fabricate('artist', name: 'Bitty'), represented_by: false, image_versions: ['tiny'], image_url: 'bitty.jpg' artist = @partner.artistFromPartnerArtist(partnerArtist) artist.get('name').should.equal 'Bitty' artist.get('image_versions').length.should.equal 1 artist.get('image_versions')[0].should.equal 'tiny' artist.get('image_url').should.equal 'bitty.jpg' it 'doesnt copy over image info when not included in the partner artist', -> partnerArtist = new Backbone.Model artist: fabricate('artist', name: 'Bitty'), represented_by: false, image_versions: null, image_url: 'bitty.jpg' artist = @partner.artistFromPartnerArtist(partnerArtist) artist.get('name').should.equal 'Bitty' artist.get('image_versions')?.should.not.be.ok() artist.get('image_url').should.not.equal 'bitty.jpg'
166635
urlParser = require 'url' sinon = require 'sinon' Backbone = require 'backbone' Partner = require '../../models/partner' PartnerLocations = require '../../collections/partner_locations' Artist = require '../../models/artist' { fabricate } = require 'antigravity' describe 'Partner', -> beforeEach -> sinon.stub Backbone, 'sync' @partner = new Partner fabricate 'partner' @partner.set 'email', "<EMAIL>" afterEach -> Backbone.sync.restore() describe '#fetchLocations', -> it 'fetches locations', -> @partner.set(id: 'moobar').fetchLocations() Backbone.sync.args[0][1].url().should.containEql 'partner/moobar/locations' describe "#fetchArtistGroups", -> it 'fetches the partners artists and groups them in represented/unreped, taking image info from the partner artist relation', (done) -> @partner.fetchArtistGroups success: (represented, unrepresented) -> represented.length.should.equal 2 unrepresented.length.should.equal 1 unrepresented.models[0].get('image_versions')[0].should.equal 'tiny' unrepresented.models[0].get('image_url').should.equal 'bitty.jpg' done() Backbone.sync.args[0][2].success [ { artist: fabricate('artist'), represented_by: true } { artist: fabricate('artist'), represented_by: true } { artist: fabricate('artist'), represented_by: false, image_versions: ['tiny'], image_url: 'bitty.jpg', published_artworks_count: 0 } { artist: fabricate('artist'), represented_by: false, image_versions: ['tiny'], image_url: 'bitty.jpg', published_artworks_count: 1 } ] Backbone.sync.args[0][2].success [] it 'only returns unrepresented artists with published works', (done) -> @partner.fetchArtistGroups success: (represented, unrepresented) -> unrepresented.length.should.equal 1 unrepresented.models[0].get('name').should.equal 'artist with published works' unrepresented.where(name: 'artist without published works').should.have.lengthOf 0 done() Backbone.sync.args[0][2].success [ { artist: fabricate('artist'), represented_by: true } { artist: fabricate('artist', name: 'artist with published works'), published_artworks_count: 2, represented_by: false } { artist: fabricate('artist', name: 'artist without published works'), published_artworks_count: 0, represented_by: false } ] Backbone.sync.args[0][2].success [] it 'requests partner artists that have not been explicity hidden from the profile', -> @partner.fetchArtistGroups success: (represented, unrepresented) -> done() Backbone.sync.args[0][2].data.display_on_partner_profile.should.equal 1 describe '#fetchFeaturedShow', -> it 'fetches the partners shows and returns one that is featured', (done) -> @partner.fetchFeaturedShow success: (show) -> show.get('id').should.equal 'bitty' done() featuredShow = fabricate 'show', id: 'bitty', featured: true unfeaturedShow = fabricate 'show', id: 'some-other-cat', featured: false Backbone.sync.args[0][2].success [ featuredShow, unfeaturedShow ] Backbone.sync.args[0][2].success [] describe '#setEmailFromLocations', -> beforeEach -> @partnerLocations = new PartnerLocations [fabricate 'partner_location'] it 'does nothing if the partner has an email address set already', -> email = @partner.get 'email' @partner.setEmailFromLocations @partnerLocations @partner.get('email').should.equal email it 'sets the first locations email address to a partner', -> @partner.set 'email', '' @partner.setEmailFromLocations @partnerLocations @partner.get('email').should.equal @partnerLocations.first().get 'email' describe '#getMailTo', -> beforeEach -> @mailto = urlParser.parse @partner.getMailTo() it 'returns an email link', -> @mailto.href.should.containEql "mailto:" it 'ignores a emails for non gallery partners', -> @partner.set 'type', 'Institution' @partner.getMailTo().should.equal '' it 'includes artsy in the CC field', -> @mailto.query.should.containEql "cc=<EMAIL>" it 'populates the subject field', -> @mailto.query.should.containEql 'subject=' @mailto.query.should.containEql encodeURIComponent("Connecting with #{@partner.get('name')} via Artsy") describe '#getSimpleWebsite', -> it 'removes "http://" and trailing slashes', -> @partner.set 'website', "http://www.lacma.org/" @partner.getSimpleWebsite().should == "www.lacma.org" describe '#artistFromPartnerArtist', -> it 'creates an artist model from the partner artist relationship, copying over the image info', -> partnerArtist = new Backbone.Model artist: fabricate('artist', name: '<NAME>'), represented_by: false, image_versions: ['tiny'], image_url: 'bitty.jpg' artist = @partner.artistFromPartnerArtist(partnerArtist) artist.get('name').should.equal '<NAME>' artist.get('image_versions').length.should.equal 1 artist.get('image_versions')[0].should.equal 'tiny' artist.get('image_url').should.equal 'bitty.jpg' it 'doesnt copy over image info when not included in the partner artist', -> partnerArtist = new Backbone.Model artist: fabricate('artist', name: '<NAME>'), represented_by: false, image_versions: null, image_url: 'bitty.jpg' artist = @partner.artistFromPartnerArtist(partnerArtist) artist.get('name').should.equal '<NAME>' artist.get('image_versions')?.should.not.be.ok() artist.get('image_url').should.not.equal 'bitty.jpg'
true
urlParser = require 'url' sinon = require 'sinon' Backbone = require 'backbone' Partner = require '../../models/partner' PartnerLocations = require '../../collections/partner_locations' Artist = require '../../models/artist' { fabricate } = require 'antigravity' describe 'Partner', -> beforeEach -> sinon.stub Backbone, 'sync' @partner = new Partner fabricate 'partner' @partner.set 'email', "PI:EMAIL:<EMAIL>END_PI" afterEach -> Backbone.sync.restore() describe '#fetchLocations', -> it 'fetches locations', -> @partner.set(id: 'moobar').fetchLocations() Backbone.sync.args[0][1].url().should.containEql 'partner/moobar/locations' describe "#fetchArtistGroups", -> it 'fetches the partners artists and groups them in represented/unreped, taking image info from the partner artist relation', (done) -> @partner.fetchArtistGroups success: (represented, unrepresented) -> represented.length.should.equal 2 unrepresented.length.should.equal 1 unrepresented.models[0].get('image_versions')[0].should.equal 'tiny' unrepresented.models[0].get('image_url').should.equal 'bitty.jpg' done() Backbone.sync.args[0][2].success [ { artist: fabricate('artist'), represented_by: true } { artist: fabricate('artist'), represented_by: true } { artist: fabricate('artist'), represented_by: false, image_versions: ['tiny'], image_url: 'bitty.jpg', published_artworks_count: 0 } { artist: fabricate('artist'), represented_by: false, image_versions: ['tiny'], image_url: 'bitty.jpg', published_artworks_count: 1 } ] Backbone.sync.args[0][2].success [] it 'only returns unrepresented artists with published works', (done) -> @partner.fetchArtistGroups success: (represented, unrepresented) -> unrepresented.length.should.equal 1 unrepresented.models[0].get('name').should.equal 'artist with published works' unrepresented.where(name: 'artist without published works').should.have.lengthOf 0 done() Backbone.sync.args[0][2].success [ { artist: fabricate('artist'), represented_by: true } { artist: fabricate('artist', name: 'artist with published works'), published_artworks_count: 2, represented_by: false } { artist: fabricate('artist', name: 'artist without published works'), published_artworks_count: 0, represented_by: false } ] Backbone.sync.args[0][2].success [] it 'requests partner artists that have not been explicity hidden from the profile', -> @partner.fetchArtistGroups success: (represented, unrepresented) -> done() Backbone.sync.args[0][2].data.display_on_partner_profile.should.equal 1 describe '#fetchFeaturedShow', -> it 'fetches the partners shows and returns one that is featured', (done) -> @partner.fetchFeaturedShow success: (show) -> show.get('id').should.equal 'bitty' done() featuredShow = fabricate 'show', id: 'bitty', featured: true unfeaturedShow = fabricate 'show', id: 'some-other-cat', featured: false Backbone.sync.args[0][2].success [ featuredShow, unfeaturedShow ] Backbone.sync.args[0][2].success [] describe '#setEmailFromLocations', -> beforeEach -> @partnerLocations = new PartnerLocations [fabricate 'partner_location'] it 'does nothing if the partner has an email address set already', -> email = @partner.get 'email' @partner.setEmailFromLocations @partnerLocations @partner.get('email').should.equal email it 'sets the first locations email address to a partner', -> @partner.set 'email', '' @partner.setEmailFromLocations @partnerLocations @partner.get('email').should.equal @partnerLocations.first().get 'email' describe '#getMailTo', -> beforeEach -> @mailto = urlParser.parse @partner.getMailTo() it 'returns an email link', -> @mailto.href.should.containEql "mailto:" it 'ignores a emails for non gallery partners', -> @partner.set 'type', 'Institution' @partner.getMailTo().should.equal '' it 'includes artsy in the CC field', -> @mailto.query.should.containEql "cc=PI:EMAIL:<EMAIL>END_PI" it 'populates the subject field', -> @mailto.query.should.containEql 'subject=' @mailto.query.should.containEql encodeURIComponent("Connecting with #{@partner.get('name')} via Artsy") describe '#getSimpleWebsite', -> it 'removes "http://" and trailing slashes', -> @partner.set 'website', "http://www.lacma.org/" @partner.getSimpleWebsite().should == "www.lacma.org" describe '#artistFromPartnerArtist', -> it 'creates an artist model from the partner artist relationship, copying over the image info', -> partnerArtist = new Backbone.Model artist: fabricate('artist', name: 'PI:NAME:<NAME>END_PI'), represented_by: false, image_versions: ['tiny'], image_url: 'bitty.jpg' artist = @partner.artistFromPartnerArtist(partnerArtist) artist.get('name').should.equal 'PI:NAME:<NAME>END_PI' artist.get('image_versions').length.should.equal 1 artist.get('image_versions')[0].should.equal 'tiny' artist.get('image_url').should.equal 'bitty.jpg' it 'doesnt copy over image info when not included in the partner artist', -> partnerArtist = new Backbone.Model artist: fabricate('artist', name: 'PI:NAME:<NAME>END_PI'), represented_by: false, image_versions: null, image_url: 'bitty.jpg' artist = @partner.artistFromPartnerArtist(partnerArtist) artist.get('name').should.equal 'PI:NAME:<NAME>END_PI' artist.get('image_versions')?.should.not.be.ok() artist.get('image_url').should.not.equal 'bitty.jpg'
[ { "context": "#\n# Copyright (c) 2012 Konstantin Bender.\n#\n# Permission is hereby granted, free of charge", "end": 40, "score": 0.9998638033866882, "start": 23, "tag": "NAME", "value": "Konstantin Bender" } ]
tests/test.coffee
konstantinbe/milk
0
# # Copyright (c) 2012 Konstantin Bender. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ----------------------------------------------------- Aliased Functions ------ spy_on = spyOn before = beforeEach after = afterEach jasmine.Spy::and_call_through = jasmine.Spy::andCallThrough jasmine.Spy::and_return = jasmine.Spy::andReturn jasmine.Spy::and_throw = jasmine.Spy::andThrow jasmine.Spy::and_call_fake = jasmine.Spy::andCallFake jasmine.Spy::reset = jasmine.Spy::reset # ------------------------------------------------------ Aliased Matchers ------ AliasedMatchers = to_be: jasmine.Matchers.prototype.toBe to_equal: jasmine.Matchers.prototype.toEqual to_match: jasmine.Matchers.prototype.toMatch to_be_defined: jasmine.Matchers.prototype.toBeDefined to_be_undefined: jasmine.Matchers.prototype.toBeUndefined to_be_null: jasmine.Matchers.prototype.toBeNull to_be_truthy: jasmine.Matchers.prototype.toBeTruthy to_be_falsy: jasmine.Matchers.prototype.toBeFalsy to_have_been_called: jasmine.Matchers.prototype.toHaveBeenCalled to_have_been_called_with: jasmine.Matchers.prototype.toHaveBeenCalledWith to_contain: jasmine.Matchers.prototype.toContain to_be_less_than: jasmine.Matchers.prototype.toBeLessThan to_be_greater_than: jasmine.Matchers.prototype.toBeGreaterThan to_throw: jasmine.Matchers.prototype.toThrow # ------------------------------------------------------- Custom Matchers ------ CustomMatchers = to_exist: -> @actual? to_be_a_dictionary: -> Object.is_dictioanary @actual to_be_kind_of: (klass) -> Object.is_kind_of @actual, klass to_be_instance_of: (klass) -> Object.is_instance_of @actual, klass to_be_frozen: (object) -> Object.is_frozen @actual to_be_sealed: (object) -> Object.is_sealed @actual to_equal: (object) -> @are_equal @actual, object to_contain: (value) -> @actual.contains value to_contain_all: (values) -> values.all (value) => @actual.contains value to_contain_any: (values) -> values.any (value) => @actual.contains value to_have_exactly: (count, options = {}) -> @actual.count() == count to_have_at_least: (count) -> @actual.count() >= count to_have_at_most: (count) -> @actual.count() <= count to_have_more_than: (count) -> @actual.count() > count to_have_less_than: (count) -> @actual.count() < count to_have_between: (bounds, options = {}) -> excluding_lower = @option options, 'excluding_lower', no excluding_upper = @option options, 'excluding_upper', no excluding_bounds = @option options, 'excluding_bounds', no [lower, upper] = bounds.sort() count = @actual.count() return lower < count <= upper if excluding_lower return lower <= count < upper if excluding_upper return lower < count < upper if excluding_bounds lower <= count <= upper to_respond_to: (method) -> Object.responds_to @actual, method # ----------------------------------------------------- Register Matchers ------ before -> @addMatchers AliasedMatchers @addMatchers CustomMatchers
220497
# # Copyright (c) 2012 <NAME>. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ----------------------------------------------------- Aliased Functions ------ spy_on = spyOn before = beforeEach after = afterEach jasmine.Spy::and_call_through = jasmine.Spy::andCallThrough jasmine.Spy::and_return = jasmine.Spy::andReturn jasmine.Spy::and_throw = jasmine.Spy::andThrow jasmine.Spy::and_call_fake = jasmine.Spy::andCallFake jasmine.Spy::reset = jasmine.Spy::reset # ------------------------------------------------------ Aliased Matchers ------ AliasedMatchers = to_be: jasmine.Matchers.prototype.toBe to_equal: jasmine.Matchers.prototype.toEqual to_match: jasmine.Matchers.prototype.toMatch to_be_defined: jasmine.Matchers.prototype.toBeDefined to_be_undefined: jasmine.Matchers.prototype.toBeUndefined to_be_null: jasmine.Matchers.prototype.toBeNull to_be_truthy: jasmine.Matchers.prototype.toBeTruthy to_be_falsy: jasmine.Matchers.prototype.toBeFalsy to_have_been_called: jasmine.Matchers.prototype.toHaveBeenCalled to_have_been_called_with: jasmine.Matchers.prototype.toHaveBeenCalledWith to_contain: jasmine.Matchers.prototype.toContain to_be_less_than: jasmine.Matchers.prototype.toBeLessThan to_be_greater_than: jasmine.Matchers.prototype.toBeGreaterThan to_throw: jasmine.Matchers.prototype.toThrow # ------------------------------------------------------- Custom Matchers ------ CustomMatchers = to_exist: -> @actual? to_be_a_dictionary: -> Object.is_dictioanary @actual to_be_kind_of: (klass) -> Object.is_kind_of @actual, klass to_be_instance_of: (klass) -> Object.is_instance_of @actual, klass to_be_frozen: (object) -> Object.is_frozen @actual to_be_sealed: (object) -> Object.is_sealed @actual to_equal: (object) -> @are_equal @actual, object to_contain: (value) -> @actual.contains value to_contain_all: (values) -> values.all (value) => @actual.contains value to_contain_any: (values) -> values.any (value) => @actual.contains value to_have_exactly: (count, options = {}) -> @actual.count() == count to_have_at_least: (count) -> @actual.count() >= count to_have_at_most: (count) -> @actual.count() <= count to_have_more_than: (count) -> @actual.count() > count to_have_less_than: (count) -> @actual.count() < count to_have_between: (bounds, options = {}) -> excluding_lower = @option options, 'excluding_lower', no excluding_upper = @option options, 'excluding_upper', no excluding_bounds = @option options, 'excluding_bounds', no [lower, upper] = bounds.sort() count = @actual.count() return lower < count <= upper if excluding_lower return lower <= count < upper if excluding_upper return lower < count < upper if excluding_bounds lower <= count <= upper to_respond_to: (method) -> Object.responds_to @actual, method # ----------------------------------------------------- Register Matchers ------ before -> @addMatchers AliasedMatchers @addMatchers CustomMatchers
true
# # Copyright (c) 2012 PI:NAME:<NAME>END_PI. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ----------------------------------------------------- Aliased Functions ------ spy_on = spyOn before = beforeEach after = afterEach jasmine.Spy::and_call_through = jasmine.Spy::andCallThrough jasmine.Spy::and_return = jasmine.Spy::andReturn jasmine.Spy::and_throw = jasmine.Spy::andThrow jasmine.Spy::and_call_fake = jasmine.Spy::andCallFake jasmine.Spy::reset = jasmine.Spy::reset # ------------------------------------------------------ Aliased Matchers ------ AliasedMatchers = to_be: jasmine.Matchers.prototype.toBe to_equal: jasmine.Matchers.prototype.toEqual to_match: jasmine.Matchers.prototype.toMatch to_be_defined: jasmine.Matchers.prototype.toBeDefined to_be_undefined: jasmine.Matchers.prototype.toBeUndefined to_be_null: jasmine.Matchers.prototype.toBeNull to_be_truthy: jasmine.Matchers.prototype.toBeTruthy to_be_falsy: jasmine.Matchers.prototype.toBeFalsy to_have_been_called: jasmine.Matchers.prototype.toHaveBeenCalled to_have_been_called_with: jasmine.Matchers.prototype.toHaveBeenCalledWith to_contain: jasmine.Matchers.prototype.toContain to_be_less_than: jasmine.Matchers.prototype.toBeLessThan to_be_greater_than: jasmine.Matchers.prototype.toBeGreaterThan to_throw: jasmine.Matchers.prototype.toThrow # ------------------------------------------------------- Custom Matchers ------ CustomMatchers = to_exist: -> @actual? to_be_a_dictionary: -> Object.is_dictioanary @actual to_be_kind_of: (klass) -> Object.is_kind_of @actual, klass to_be_instance_of: (klass) -> Object.is_instance_of @actual, klass to_be_frozen: (object) -> Object.is_frozen @actual to_be_sealed: (object) -> Object.is_sealed @actual to_equal: (object) -> @are_equal @actual, object to_contain: (value) -> @actual.contains value to_contain_all: (values) -> values.all (value) => @actual.contains value to_contain_any: (values) -> values.any (value) => @actual.contains value to_have_exactly: (count, options = {}) -> @actual.count() == count to_have_at_least: (count) -> @actual.count() >= count to_have_at_most: (count) -> @actual.count() <= count to_have_more_than: (count) -> @actual.count() > count to_have_less_than: (count) -> @actual.count() < count to_have_between: (bounds, options = {}) -> excluding_lower = @option options, 'excluding_lower', no excluding_upper = @option options, 'excluding_upper', no excluding_bounds = @option options, 'excluding_bounds', no [lower, upper] = bounds.sort() count = @actual.count() return lower < count <= upper if excluding_lower return lower <= count < upper if excluding_upper return lower < count < upper if excluding_bounds lower <= count <= upper to_respond_to: (method) -> Object.responds_to @actual, method # ----------------------------------------------------- Register Matchers ------ before -> @addMatchers AliasedMatchers @addMatchers CustomMatchers
[ { "context": "ands:\n# hide ya kids - Hide `em!\n#\n# Author:\n# Joseph Huttner\n\nmodule.exports = (robot) ->\n robot.hear /hide y", "end": 199, "score": 0.9998790621757507, "start": 185, "tag": "NAME", "value": "Joseph Huttner" } ]
src/scripts/hideyakids.coffee
Reelhouse/hubot-scripts
1,450
# Description: # Antoine Dodson's greatest hits... errr... only hit # # Dependencies: # None # # Configuration: # None # # Commands: # hide ya kids - Hide `em! # # Author: # Joseph Huttner module.exports = (robot) -> robot.hear /hide ya kids/i, (msg) -> msg.send "http://www.youtube.com/watch?v=hMtZfW2z9dw"
63107
# Description: # Antoine Dodson's greatest hits... errr... only hit # # Dependencies: # None # # Configuration: # None # # Commands: # hide ya kids - Hide `em! # # Author: # <NAME> module.exports = (robot) -> robot.hear /hide ya kids/i, (msg) -> msg.send "http://www.youtube.com/watch?v=hMtZfW2z9dw"
true
# Description: # Antoine Dodson's greatest hits... errr... only hit # # Dependencies: # None # # Configuration: # None # # Commands: # hide ya kids - Hide `em! # # Author: # PI:NAME:<NAME>END_PI module.exports = (robot) -> robot.hear /hide ya kids/i, (msg) -> msg.send "http://www.youtube.com/watch?v=hMtZfW2z9dw"
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9986017346382141, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "erver(options, (socket) ->\n options =\n host: \"127.0.0.1\"\n port: b.address().port\n rejectUnauthorize", "end": 1719, "score": 0.9447507858276367, "start": 1710, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "en common.PORT + 1, ->\n options =\n host: \"127.0.0.1\"\n port: a.address().port\n rejectUnautho", "end": 2097, "score": 0.999771773815155, "start": 2088, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
test/simple/test-tls-inception.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. unless process.versions.openssl console.error "Skipping because node compiled without OpenSSL." process.exit 0 common = require("../common") fs = require("fs") path = require("path") net = require("net") tls = require("tls") assert = require("assert") options = undefined a = undefined b = undefined portA = undefined portB = undefined gotHello = false options = key: fs.readFileSync(path.join(common.fixturesDir, "test_key.pem")) cert: fs.readFileSync(path.join(common.fixturesDir, "test_cert.pem")) # the "proxy" server a = tls.createServer(options, (socket) -> options = host: "127.0.0.1" port: b.address().port rejectUnauthorized: false dest = net.connect(options) dest.pipe socket socket.pipe dest return ) # the "target" server b = tls.createServer(options, (socket) -> socket.end "hello" return ) process.on "exit", -> assert gotHello return a.listen common.PORT, -> b.listen common.PORT + 1, -> options = host: "127.0.0.1" port: a.address().port rejectUnauthorized: false socket = tls.connect(options) ssl = undefined ssl = tls.connect( socket: socket rejectUnauthorized: false ) ssl.setEncoding "utf8" ssl.once "data", (data) -> assert.equal "hello", data gotHello = true return ssl.on "end", -> ssl.end() a.close() b.close() return return return
46339
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. unless process.versions.openssl console.error "Skipping because node compiled without OpenSSL." process.exit 0 common = require("../common") fs = require("fs") path = require("path") net = require("net") tls = require("tls") assert = require("assert") options = undefined a = undefined b = undefined portA = undefined portB = undefined gotHello = false options = key: fs.readFileSync(path.join(common.fixturesDir, "test_key.pem")) cert: fs.readFileSync(path.join(common.fixturesDir, "test_cert.pem")) # the "proxy" server a = tls.createServer(options, (socket) -> options = host: "127.0.0.1" port: b.address().port rejectUnauthorized: false dest = net.connect(options) dest.pipe socket socket.pipe dest return ) # the "target" server b = tls.createServer(options, (socket) -> socket.end "hello" return ) process.on "exit", -> assert gotHello return a.listen common.PORT, -> b.listen common.PORT + 1, -> options = host: "127.0.0.1" port: a.address().port rejectUnauthorized: false socket = tls.connect(options) ssl = undefined ssl = tls.connect( socket: socket rejectUnauthorized: false ) ssl.setEncoding "utf8" ssl.once "data", (data) -> assert.equal "hello", data gotHello = true return ssl.on "end", -> ssl.end() a.close() b.close() return return return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. unless process.versions.openssl console.error "Skipping because node compiled without OpenSSL." process.exit 0 common = require("../common") fs = require("fs") path = require("path") net = require("net") tls = require("tls") assert = require("assert") options = undefined a = undefined b = undefined portA = undefined portB = undefined gotHello = false options = key: fs.readFileSync(path.join(common.fixturesDir, "test_key.pem")) cert: fs.readFileSync(path.join(common.fixturesDir, "test_cert.pem")) # the "proxy" server a = tls.createServer(options, (socket) -> options = host: "127.0.0.1" port: b.address().port rejectUnauthorized: false dest = net.connect(options) dest.pipe socket socket.pipe dest return ) # the "target" server b = tls.createServer(options, (socket) -> socket.end "hello" return ) process.on "exit", -> assert gotHello return a.listen common.PORT, -> b.listen common.PORT + 1, -> options = host: "127.0.0.1" port: a.address().port rejectUnauthorized: false socket = tls.connect(options) ssl = undefined ssl = tls.connect( socket: socket rejectUnauthorized: false ) ssl.setEncoding "utf8" ssl.once "data", (data) -> assert.equal "hello", data gotHello = true return ssl.on "end", -> ssl.end() a.close() b.close() return return return
[ { "context": "\nnikita = require '@nikitajs/core'\n{tags, ssh, scratch} = require './test'\nthe", "end": 28, "score": 0.7176410555839539, "start": 26, "tag": "USERNAME", "value": "js" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{__", "end": 376, "score": 0.9987363815307617, "start": 368, "tag": "PASSWORD", "value": "changeit" }, { "context": "e: \"#{scratch}/a/dir/cacerts\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{__", "end": 726, "score": 0.9989044666290283, "start": 718, "tag": "PASSWORD", "value": "changeit" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{__", "end": 1081, "score": 0.989603579044342, "start": 1073, "tag": "PASSWORD", "value": "changeit" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{__", "end": 1279, "score": 0.9979135990142822, "start": 1271, "tag": "PASSWORD", "value": "changeit" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{__", "end": 1637, "score": 0.9983634948730469, "start": 1629, "tag": "PASSWORD", "value": "changeit" }, { "context": "ool -list -keystore #{scratch}/keystore -storepass changeit -alias my_alias\"\n content: /^my_alias,/m\n ", "end": 2098, "score": 0.8690306544303894, "start": 2090, "tag": "PASSWORD", "value": "changeit" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: '/pat", "end": 2342, "score": 0.9939981698989868, "start": 2334, "tag": "PASSWORD", "value": "changeit" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{sc", "end": 3515, "score": 0.9987969398498535, "start": 3507, "tag": "PASSWORD", "value": "changeit" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{sc", "end": 3752, "score": 0.9989073872566223, "start": 3744, "tag": "PASSWORD", "value": "changeit" }, { "context": "ool -list -keystore #{scratch}/keystore -storepass changeit -alias my_alias-0\"\n content: /^my_alias-0,", "end": 4003, "score": 0.7548878192901611, "start": 3995, "tag": "PASSWORD", "value": "changeit" }, { "context": "ool -list -keystore #{scratch}/keystore -storepass changeit -alias my_alias-2\"\n content: /^my_alias-2,", "end": 4321, "score": 0.5791833400726318, "start": 4313, "tag": "PASSWORD", "value": "changeit" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{sc", "end": 5736, "score": 0.9990216493606567, "start": 5728, "tag": "PASSWORD", "value": "changeit" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{sc", "end": 5974, "score": 0.9988312721252441, "start": 5966, "tag": "PASSWORD", "value": "changeit" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{__", "end": 6329, "score": 0.9987435936927795, "start": 6321, "tag": "PASSWORD", "value": "changeit" }, { "context": "eystore/certs1/node_1_cert.pem\"\n keypass: 'mypassword'\n name: 'node_1'\n , (err, {status}) -", "end": 6564, "score": 0.9982098937034607, "start": 6554, "tag": "PASSWORD", "value": "mypassword" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{__", "end": 6856, "score": 0.9935745596885681, "start": 6848, "tag": "PASSWORD", "value": "changeit" }, { "context": "eystore/certs1/node_1_cert.pem\"\n keypass: 'mypassword'\n name: 'node_1'\n , (err, {status}) -", "end": 7091, "score": 0.9984670877456665, "start": 7081, "tag": "PASSWORD", "value": "mypassword" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{__", "end": 7279, "score": 0.9771429300308228, "start": 7271, "tag": "PASSWORD", "value": "changeit" }, { "context": "eystore/certs1/node_1_cert.pem\"\n keypass: 'mypassword'\n name: 'node_1'\n , (err, {status}) -", "end": 7514, "score": 0.9984126687049866, "start": 7504, "tag": "PASSWORD", "value": "mypassword" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{__", "end": 7810, "score": 0.9936388731002808, "start": 7802, "tag": "PASSWORD", "value": "changeit" }, { "context": "eystore/certs1/node_1_cert.pem\"\n keypass: 'mypassword'\n name: 'node_1'\n .java.keystore_add\n", "end": 8045, "score": 0.9986840486526489, "start": 8035, "tag": "PASSWORD", "value": "mypassword" }, { "context": "eystore/certs2/node_1_cert.pem\"\n keypass: 'mypassword'\n name: 'node_1'\n , (err, {status}) -", "end": 8398, "score": 0.9986269474029541, "start": 8388, "tag": "PASSWORD", "value": "mypassword" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{__", "end": 8705, "score": 0.9992324113845825, "start": 8697, "tag": "PASSWORD", "value": "changeit" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changednow\"\n caname: \"my_alias\"\n cacert: \"#{__", "end": 8887, "score": 0.9994038939476013, "start": 8877, "tag": "PASSWORD", "value": "changednow" }, { "context": "ystore: \"#{scratch}/keystore\"\n storepass: \"changeit\"\n caname: \"my_alias\"\n cacert: \"#{__", "end": 9271, "score": 0.9993808269500732, "start": 9263, "tag": "PASSWORD", "value": "changeit" }, { "context": "eystore/certs2/node_1_cert.pem\"\n keypass: 'mypassword'\n openssl: '/doesnt/not/exists'\n na", "end": 9506, "score": 0.9990952014923096, "start": 9496, "tag": "PASSWORD", "value": "mypassword" } ]
packages/java/test/keystore_add.coffee
chibanemourad/node-nikita
1
nikita = require '@nikitajs/core' {tags, ssh, scratch} = require './test' they = require('ssh2-they').configure ssh... return unless tags.posix describe 'java.keystore_add', -> describe 'cacert', -> they 'create new cacerts file', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" , (err, {status}) -> status.should.be.true() unless err .promise() they 'create parent directory', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/a/dir/cacerts" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" , (err, {status}) -> status.should.be.true() unless err .promise() they 'detect existing cacert signature', ({ssh}) -> nikita ssh: null .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" shy: true .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" , (err, {status}) -> status.should.be.false() unless err .promise() they 'update a new cacert with same alias', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" shy: true .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" , (err, {status}) -> status.should.be.true() unless err .system.execute.assert cmd: "keytool -list -keystore #{scratch}/keystore -storepass changeit -alias my_alias" content: /^my_alias,/m .promise() they 'fail if ca file does not exist', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: '/path/to/missing/ca.cert.pem' relax: true , (err) -> err.message.should.eql 'CA file does not exist: /path/to/missing/ca.cert.pem' .promise() they 'import certificate chain', ({ssh}) -> nikita ssh: ssh .system.execute cmd: """ mkdir #{scratch}/tmp cd #{scratch}/tmp openssl req -new -nodes -out ca_int1.req -keyout ca_int1.key.pem -subj /CN=CAIntermediate1 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int1.req -CAkey #{__dirname}/keystore/certs1/cacert_key.pem -CA #{__dirname}/keystore/certs1/cacert.pem -days 20 -set_serial 01 -sha512 -out ca_int1.cert.pem openssl req -new -nodes -out ca_int2.req -keyout ca_int2.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2.cert.pem > ca.cert.pem """ .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{scratch}/tmp/ca.cert.pem" , (err, {status}) -> status.should.be.true() unless err .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{scratch}/tmp/ca.cert.pem" , (err, {status}) -> status.should.be.false() unless err .system.execute.assert cmd: "keytool -list -keystore #{scratch}/keystore -storepass changeit -alias my_alias-0" content: /^my_alias-0,/m .system.execute.assert cmd: "keytool -list -keystore #{scratch}/keystore -storepass changeit -alias my_alias-1" content: /^my_alias-1,/m .system.execute.assert cmd: "keytool -list -keystore #{scratch}/keystore -storepass changeit -alias my_alias-2" content: /^my_alias-2,/m .promise() they 'honors status with certificate chain', ({ssh}) -> nikita ssh: ssh .system.execute cmd: """ mkdir #{scratch}/ca cd #{scratch}/ca openssl req -new -nodes -out ca_int1.req -keyout ca_int1.key.pem -subj /CN=CAIntermediate1 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int1.req -CAkey #{__dirname}/keystore/certs1/cacert_key.pem -CA #{__dirname}/keystore/certs1/cacert.pem -days 20 -set_serial 01 -sha512 -out ca_int1.cert.pem openssl req -new -nodes -out ca_int2a.req -keyout ca_int2a.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2a.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2a.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2a.cert.pem > ca.a.cert.pem openssl req -new -nodes -out ca_int2b.req -keyout ca_int2b.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2b.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2b.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2b.cert.pem > ca.b.cert.pem """ .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{scratch}/ca/ca.a.cert.pem" , (err, {status}) -> status.should.be.true() unless err .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{scratch}/ca/ca.b.cert.pem" , (err, {status}) -> status.should.be.true() unless err .promise() describe 'key', -> they 'create new cacerts file', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'mypassword' name: 'node_1' , (err, {status}) -> status.should.be.true() unless err .promise() they 'detect existing cacert signature', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'mypassword' name: 'node_1' , (err, {status}) -> status.should.be.true() unless err .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'mypassword' name: 'node_1' , (err, {status}) -> status.should.be.false() unless err .promise() they 'update a new cacert with same alias', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'mypassword' name: 'node_1' .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" key: "#{__dirname}/keystore/certs2/node_1_key.pem" cert: "#{__dirname}/keystore/certs2/node_1_cert.pem" keypass: 'mypassword' name: 'node_1' , (err, {status}) -> status.should.be.true() unless err .promise() describe 'keystore', -> they.skip 'change password', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changednow" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" , (err, {status}) -> status.should.be.true() unless err .promise() describe 'option openssl', -> they 'throw error if not detected', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" key: "#{__dirname}/keystore/certs2/node_1_key.pem" cert: "#{__dirname}/keystore/certs2/node_1_cert.pem" keypass: 'mypassword' openssl: '/doesnt/not/exists' name: 'node_1' relax: true , (err) -> err.message.should.eql 'OpenSSL command line tool not detected' .promise()
114390
nikita = require '@nikitajs/core' {tags, ssh, scratch} = require './test' they = require('ssh2-they').configure ssh... return unless tags.posix describe 'java.keystore_add', -> describe 'cacert', -> they 'create new cacerts file', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" , (err, {status}) -> status.should.be.true() unless err .promise() they 'create parent directory', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/a/dir/cacerts" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" , (err, {status}) -> status.should.be.true() unless err .promise() they 'detect existing cacert signature', ({ssh}) -> nikita ssh: null .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" shy: true .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" , (err, {status}) -> status.should.be.false() unless err .promise() they 'update a new cacert with same alias', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" shy: true .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" , (err, {status}) -> status.should.be.true() unless err .system.execute.assert cmd: "keytool -list -keystore #{scratch}/keystore -storepass <PASSWORD> -alias my_alias" content: /^my_alias,/m .promise() they 'fail if ca file does not exist', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: '/path/to/missing/ca.cert.pem' relax: true , (err) -> err.message.should.eql 'CA file does not exist: /path/to/missing/ca.cert.pem' .promise() they 'import certificate chain', ({ssh}) -> nikita ssh: ssh .system.execute cmd: """ mkdir #{scratch}/tmp cd #{scratch}/tmp openssl req -new -nodes -out ca_int1.req -keyout ca_int1.key.pem -subj /CN=CAIntermediate1 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int1.req -CAkey #{__dirname}/keystore/certs1/cacert_key.pem -CA #{__dirname}/keystore/certs1/cacert.pem -days 20 -set_serial 01 -sha512 -out ca_int1.cert.pem openssl req -new -nodes -out ca_int2.req -keyout ca_int2.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2.cert.pem > ca.cert.pem """ .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{scratch}/tmp/ca.cert.pem" , (err, {status}) -> status.should.be.true() unless err .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{scratch}/tmp/ca.cert.pem" , (err, {status}) -> status.should.be.false() unless err .system.execute.assert cmd: "keytool -list -keystore #{scratch}/keystore -storepass <PASSWORD> -alias my_alias-0" content: /^my_alias-0,/m .system.execute.assert cmd: "keytool -list -keystore #{scratch}/keystore -storepass changeit -alias my_alias-1" content: /^my_alias-1,/m .system.execute.assert cmd: "keytool -list -keystore #{scratch}/keystore -storepass <PASSWORD> -alias my_alias-2" content: /^my_alias-2,/m .promise() they 'honors status with certificate chain', ({ssh}) -> nikita ssh: ssh .system.execute cmd: """ mkdir #{scratch}/ca cd #{scratch}/ca openssl req -new -nodes -out ca_int1.req -keyout ca_int1.key.pem -subj /CN=CAIntermediate1 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int1.req -CAkey #{__dirname}/keystore/certs1/cacert_key.pem -CA #{__dirname}/keystore/certs1/cacert.pem -days 20 -set_serial 01 -sha512 -out ca_int1.cert.pem openssl req -new -nodes -out ca_int2a.req -keyout ca_int2a.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2a.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2a.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2a.cert.pem > ca.a.cert.pem openssl req -new -nodes -out ca_int2b.req -keyout ca_int2b.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2b.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2b.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2b.cert.pem > ca.b.cert.pem """ .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{scratch}/ca/ca.a.cert.pem" , (err, {status}) -> status.should.be.true() unless err .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{scratch}/ca/ca.b.cert.pem" , (err, {status}) -> status.should.be.true() unless err .promise() describe 'key', -> they 'create new cacerts file', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: '<PASSWORD>' name: 'node_1' , (err, {status}) -> status.should.be.true() unless err .promise() they 'detect existing cacert signature', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: '<PASSWORD>' name: 'node_1' , (err, {status}) -> status.should.be.true() unless err .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: '<PASSWORD>' name: 'node_1' , (err, {status}) -> status.should.be.false() unless err .promise() they 'update a new cacert with same alias', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: '<PASSWORD>' name: 'node_1' .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" key: "#{__dirname}/keystore/certs2/node_1_key.pem" cert: "#{__dirname}/keystore/certs2/node_1_cert.pem" keypass: '<PASSWORD>' name: 'node_1' , (err, {status}) -> status.should.be.true() unless err .promise() describe 'keystore', -> they.skip 'change password', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" , (err, {status}) -> status.should.be.true() unless err .promise() describe 'option openssl', -> they 'throw error if not detected', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "<PASSWORD>" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" key: "#{__dirname}/keystore/certs2/node_1_key.pem" cert: "#{__dirname}/keystore/certs2/node_1_cert.pem" keypass: '<PASSWORD>' openssl: '/doesnt/not/exists' name: 'node_1' relax: true , (err) -> err.message.should.eql 'OpenSSL command line tool not detected' .promise()
true
nikita = require '@nikitajs/core' {tags, ssh, scratch} = require './test' they = require('ssh2-they').configure ssh... return unless tags.posix describe 'java.keystore_add', -> describe 'cacert', -> they 'create new cacerts file', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" , (err, {status}) -> status.should.be.true() unless err .promise() they 'create parent directory', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/a/dir/cacerts" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" , (err, {status}) -> status.should.be.true() unless err .promise() they 'detect existing cacert signature', ({ssh}) -> nikita ssh: null .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" shy: true .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" , (err, {status}) -> status.should.be.false() unless err .promise() they 'update a new cacert with same alias', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" shy: true .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" , (err, {status}) -> status.should.be.true() unless err .system.execute.assert cmd: "keytool -list -keystore #{scratch}/keystore -storepass PI:PASSWORD:<PASSWORD>END_PI -alias my_alias" content: /^my_alias,/m .promise() they 'fail if ca file does not exist', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: '/path/to/missing/ca.cert.pem' relax: true , (err) -> err.message.should.eql 'CA file does not exist: /path/to/missing/ca.cert.pem' .promise() they 'import certificate chain', ({ssh}) -> nikita ssh: ssh .system.execute cmd: """ mkdir #{scratch}/tmp cd #{scratch}/tmp openssl req -new -nodes -out ca_int1.req -keyout ca_int1.key.pem -subj /CN=CAIntermediate1 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int1.req -CAkey #{__dirname}/keystore/certs1/cacert_key.pem -CA #{__dirname}/keystore/certs1/cacert.pem -days 20 -set_serial 01 -sha512 -out ca_int1.cert.pem openssl req -new -nodes -out ca_int2.req -keyout ca_int2.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2.cert.pem > ca.cert.pem """ .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{scratch}/tmp/ca.cert.pem" , (err, {status}) -> status.should.be.true() unless err .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{scratch}/tmp/ca.cert.pem" , (err, {status}) -> status.should.be.false() unless err .system.execute.assert cmd: "keytool -list -keystore #{scratch}/keystore -storepass PI:PASSWORD:<PASSWORD>END_PI -alias my_alias-0" content: /^my_alias-0,/m .system.execute.assert cmd: "keytool -list -keystore #{scratch}/keystore -storepass changeit -alias my_alias-1" content: /^my_alias-1,/m .system.execute.assert cmd: "keytool -list -keystore #{scratch}/keystore -storepass PI:PASSWORD:<PASSWORD>END_PI -alias my_alias-2" content: /^my_alias-2,/m .promise() they 'honors status with certificate chain', ({ssh}) -> nikita ssh: ssh .system.execute cmd: """ mkdir #{scratch}/ca cd #{scratch}/ca openssl req -new -nodes -out ca_int1.req -keyout ca_int1.key.pem -subj /CN=CAIntermediate1 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int1.req -CAkey #{__dirname}/keystore/certs1/cacert_key.pem -CA #{__dirname}/keystore/certs1/cacert.pem -days 20 -set_serial 01 -sha512 -out ca_int1.cert.pem openssl req -new -nodes -out ca_int2a.req -keyout ca_int2a.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2a.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2a.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2a.cert.pem > ca.a.cert.pem openssl req -new -nodes -out ca_int2b.req -keyout ca_int2b.key.pem -subj /CN=CAIntermediate2 -newkey rsa:2048 -sha512 openssl x509 -req -in ca_int2b.req -CAkey ca_int1.key.pem -CA ca_int1.cert.pem -days 20 -set_serial 01 -sha512 -out ca_int2b.cert.pem cat #{__dirname}/keystore/certs1/cacert.pem ca_int1.cert.pem ca_int2b.cert.pem > ca.b.cert.pem """ .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{scratch}/ca/ca.a.cert.pem" , (err, {status}) -> status.should.be.true() unless err .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{scratch}/ca/ca.b.cert.pem" , (err, {status}) -> status.should.be.true() unless err .promise() describe 'key', -> they 'create new cacerts file', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'node_1' , (err, {status}) -> status.should.be.true() unless err .promise() they 'detect existing cacert signature', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'node_1' , (err, {status}) -> status.should.be.true() unless err .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'node_1' , (err, {status}) -> status.should.be.false() unless err .promise() they 'update a new cacert with same alias', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" key: "#{__dirname}/keystore/certs1/node_1_key.pem" cert: "#{__dirname}/keystore/certs1/node_1_cert.pem" keypass: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'node_1' .java.keystore_add keystore: "#{scratch}/keystore" storepass: "changeit" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" key: "#{__dirname}/keystore/certs2/node_1_key.pem" cert: "#{__dirname}/keystore/certs2/node_1_cert.pem" keypass: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'node_1' , (err, {status}) -> status.should.be.true() unless err .promise() describe 'keystore', -> they.skip 'change password', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs1/cacert.pem" , (err, {status}) -> status.should.be.true() unless err .promise() describe 'option openssl', -> they 'throw error if not detected', ({ssh}) -> nikita ssh: ssh .java.keystore_add keystore: "#{scratch}/keystore" storepass: "PI:PASSWORD:<PASSWORD>END_PI" caname: "my_alias" cacert: "#{__dirname}/keystore/certs2/cacert.pem" key: "#{__dirname}/keystore/certs2/node_1_key.pem" cert: "#{__dirname}/keystore/certs2/node_1_cert.pem" keypass: 'PI:PASSWORD:<PASSWORD>END_PI' openssl: '/doesnt/not/exists' name: 'node_1' relax: true , (err) -> err.message.should.eql 'OpenSSL command line tool not detected' .promise()
[ { "context": "\"../src/Api\"\napi = new Api\n username : \"test\"\n password : \"test\"\n account_id: \"test\"\n proj", "end": 289, "score": 0.9955647587776184, "start": 285, "tag": "USERNAME", "value": "test" }, { "context": " = new Api\n username : \"test\"\n password : \"test\"\n account_id: \"test\"\n project_id: \"test\"\napi.en", "end": 310, "score": 0.9993622899055481, "start": 306, "tag": "PASSWORD", "value": "test" } ]
test/test-api.coffee
kvz/baseamp
4
should = require("chai").should() debug = require("debug")("Baseamp:test-api") util = require "util" expect = require("chai").expect fixture_dir = "#{__dirname}/fixtures" port = 7000 Api = require "../src/Api" api = new Api username : "test" password : "test" account_id: "test" project_id: "test" api.endpoints.get_lists = "file://{{{fixture_dir}}}/6904769.todolists.json" describe "api", -> @timeout 10000 # <-- This is the Mocha timeout, allowing tests to run longer describe "_toFixture", -> it "should anonymize dataset", (done) -> input = hey: 7 hold: more: "strings" andbooleans: true account_id: "whatever" url: "https://basecamp.com/999999999/api/v1/projects/605816632/todolists/968316918.json" app_url: "https://basecamp.com/999999999/projects/605816632/todolists/968316918" anonymized = api._toFixture input # debug util.inspect anonymized expect(anonymized).to.deep.equal hey: 22 hold: more: "strings" andbooleans: false account_id: 11 url: "file://{{{fixture_dir}}}/605816632.todolists.968316918.json" app_url: "http://example.com/" done() describe "downloadTodoLists", -> it "should retrieve todoLists", (done) -> api.downloadTodoLists (err, todoLists) -> # debug util.inspect # todoLists: todoLists[0] expect(todoLists[0].name).to.deep.equal "Uncategorized" expect(todoLists[0].todos.remaining[0].content).to.deep.equal "Transloadify Blogpost (with animated Gif!)" done()
102733
should = require("chai").should() debug = require("debug")("Baseamp:test-api") util = require "util" expect = require("chai").expect fixture_dir = "#{__dirname}/fixtures" port = 7000 Api = require "../src/Api" api = new Api username : "test" password : "<PASSWORD>" account_id: "test" project_id: "test" api.endpoints.get_lists = "file://{{{fixture_dir}}}/6904769.todolists.json" describe "api", -> @timeout 10000 # <-- This is the Mocha timeout, allowing tests to run longer describe "_toFixture", -> it "should anonymize dataset", (done) -> input = hey: 7 hold: more: "strings" andbooleans: true account_id: "whatever" url: "https://basecamp.com/999999999/api/v1/projects/605816632/todolists/968316918.json" app_url: "https://basecamp.com/999999999/projects/605816632/todolists/968316918" anonymized = api._toFixture input # debug util.inspect anonymized expect(anonymized).to.deep.equal hey: 22 hold: more: "strings" andbooleans: false account_id: 11 url: "file://{{{fixture_dir}}}/605816632.todolists.968316918.json" app_url: "http://example.com/" done() describe "downloadTodoLists", -> it "should retrieve todoLists", (done) -> api.downloadTodoLists (err, todoLists) -> # debug util.inspect # todoLists: todoLists[0] expect(todoLists[0].name).to.deep.equal "Uncategorized" expect(todoLists[0].todos.remaining[0].content).to.deep.equal "Transloadify Blogpost (with animated Gif!)" done()
true
should = require("chai").should() debug = require("debug")("Baseamp:test-api") util = require "util" expect = require("chai").expect fixture_dir = "#{__dirname}/fixtures" port = 7000 Api = require "../src/Api" api = new Api username : "test" password : "PI:PASSWORD:<PASSWORD>END_PI" account_id: "test" project_id: "test" api.endpoints.get_lists = "file://{{{fixture_dir}}}/6904769.todolists.json" describe "api", -> @timeout 10000 # <-- This is the Mocha timeout, allowing tests to run longer describe "_toFixture", -> it "should anonymize dataset", (done) -> input = hey: 7 hold: more: "strings" andbooleans: true account_id: "whatever" url: "https://basecamp.com/999999999/api/v1/projects/605816632/todolists/968316918.json" app_url: "https://basecamp.com/999999999/projects/605816632/todolists/968316918" anonymized = api._toFixture input # debug util.inspect anonymized expect(anonymized).to.deep.equal hey: 22 hold: more: "strings" andbooleans: false account_id: 11 url: "file://{{{fixture_dir}}}/605816632.todolists.968316918.json" app_url: "http://example.com/" done() describe "downloadTodoLists", -> it "should retrieve todoLists", (done) -> api.downloadTodoLists (err, todoLists) -> # debug util.inspect # todoLists: todoLists[0] expect(todoLists[0].name).to.deep.equal "Uncategorized" expect(todoLists[0].todos.remaining[0].content).to.deep.equal "Transloadify Blogpost (with animated Gif!)" done()
[ { "context": " Copyright (c) 2011-#{(new Date()).getFullYear()} Kevin Malakoff.\n License: MIT (http://www.opensource.org/licens", "end": 742, "score": 0.9998490214347839, "start": 728, "tag": "NAME", "value": "Kevin Malakoff" }, { "context": "ses/mit-license.php)\n Source: https://github.com/kmalakoff/knockback\n Dependencies: Knockout.js, Backbone.j", "end": 850, "score": 0.981636643409729, "start": 841, "tag": "USERNAME", "value": "kmalakoff" }, { "context": " return # promises workaround: https://github.com/gulpjs/gulp/issues/455\n\ngulp.task 'watch', ['build'], ->", "end": 1378, "score": 0.9988223314285278, "start": 1372, "tag": "USERNAME", "value": "gulpjs" }, { "context": " return # promises workaround: https://github.com/gulpjs/gulp/issues/455\n\ngulp.task 'minify', ['build'], (", "end": 1542, "score": 0.998396635055542, "start": 1536, "tag": "USERNAME", "value": "gulpjs" }, { "context": " return # promises workaround: https://github.com/gulpjs/gulp/issues/455\n\ntestNode = (callback) ->\n tags ", "end": 1915, "score": 0.9992958307266235, "start": 1909, "tag": "USERNAME", "value": "gulpjs" }, { "context": " return # promises workaround: https://github.com/gulpjs/gulp/issues/455\n\ntestBrowsers = (callback) ->\n t", "end": 2365, "score": 0.9992095828056335, "start": 2359, "tag": "USERNAME", "value": "gulpjs" }, { "context": " return # promises workaround: https://github.com/gulpjs/gulp/issues/455\n\ngulp.task 'test-node', ['build']", "end": 2650, "score": 0.9992364645004272, "start": 2644, "tag": "USERNAME", "value": "gulpjs" }, { "context": " return # promises workaround: https://github.com/gulpjs/gulp/issues/455\n\ngulp.task 'publish', ['minify'],", "end": 3022, "score": 0.999306321144104, "start": 3016, "tag": "USERNAME", "value": "gulpjs" }, { "context": " return # promises workaround: https://github.com/gulpjs/gulp/issues/455\n\ngulp.task 'default', ['test-node", "end": 3922, "score": 0.9991298913955688, "start": 3916, "tag": "USERNAME", "value": "gulpjs" } ]
gulpfile.coffee
kmalakoff/knockback
160
path = require 'path' _ = require 'underscore' Queue = require 'queue-async' Async = require 'async' es = require 'event-stream' gulp = require 'gulp' gutil = require 'gulp-util' webpack = require 'gulp-webpack-config' rename = require 'gulp-rename' uglify = require 'gulp-uglify' header = require 'gulp-header' mocha = require 'gulp-mocha' nuget = require 'nuget' nugetGulp = -> es.map (file, callback) -> nuget.pack file, (err, nupkg_file) -> return callback(err) if err nuget.push nupkg_file, (err) -> if err then gutil.log(err) else callback() HEADER = module.exports = """ /* <%= file.path.split('/').splice(-1)[0].replace('.min', '') %> <%= pkg.version %> Copyright (c) 2011-#{(new Date()).getFullYear()} Kevin Malakoff. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */\n """ LIBRARY_FILES = require('./config/files').libraries gulp.task 'build', buildLibraries = (callback) -> errors = [] gulp.src('config/builds/library/**/*.webpack.config.coffee') .pipe(webpack()) .pipe(header(HEADER, {pkg: require('./package.json')})) .pipe(gulp.dest('.')) .on('end', callback) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'watch', ['build'], -> gulp.watch './src/**/*.coffee', -> buildLibraries(->) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'minify', ['build'], (callback) -> gulp.src(['*.js', '!*.min.js', '!_temp/**/*.js', '!node_modules/']) .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(header(HEADER, {pkg: require('./package.json')})) .pipe(gulp.dest((file) -> file.base)) .on('end', callback) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 testNode = (callback) -> tags = ("@#{tag.replace(/^[-]+/, '')}" for tag in process.argv.slice(3)).join(' ') mochaOptions = {reporter: 'dot', compilers: 'coffee:coffee-script/register'} mochaOptions.grep = tags if tags gutil.log "Running Node.js tests #{tags}" gulp.src('test/spec/**/*.tests.coffee') .pipe(mocha(mochaOptions)) .pipe es.writeArray callback return # promises workaround: https://github.com/gulpjs/gulp/issues/455 testBrowsers = (callback) -> tags = ("@#{tag.replace(/^[-]+/, '')}" for tag in process.argv.slice(3)).join(' ') gutil.log "Running Browser tests #{tags}" (require './config/karma/run')({tags}, callback) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'test-node', ['build'], testNode # gulp.task 'test-browsers', testBrowsers gulp.task 'test-browsers', ['minify'], testBrowsers gulp.task 'test', ['minify'], (callback) -> Async.series [testNode, testBrowsers], (err) -> not err || console.log(err); process.exit(if err then 1 else 0) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'publish', ['minify'], (callback) -> copyLibraryFiles = (destination, others, callback) -> gulp.src(LIBRARY_FILES.concat(['README.md', 'RELEASE_NOTES.md'].concat(others))) .pipe(gulp.dest((file) -> path.join(destination, path.dirname(file.path).replace(__dirname, '')))) .on('end', callback) queue = new Queue(1) queue.defer (callback) -> Async.series [testNode, testBrowsers], callback queue.defer (callback) -> copyLibraryFiles('packages/npm', ['component.json', 'bower.json'], callback) queue.defer (callback) -> copyLibraryFiles('packages/nuget/Content/Scripts', [], callback) queue.defer (callback) -> gulp.src('packages/nuget/*.nuspec') .pipe(nugetGulp()) .on('end', callback) queue.await (err) -> not err || console.log(err); process.exit(if err then 1 else 0) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'default', ['test-node']
57176
path = require 'path' _ = require 'underscore' Queue = require 'queue-async' Async = require 'async' es = require 'event-stream' gulp = require 'gulp' gutil = require 'gulp-util' webpack = require 'gulp-webpack-config' rename = require 'gulp-rename' uglify = require 'gulp-uglify' header = require 'gulp-header' mocha = require 'gulp-mocha' nuget = require 'nuget' nugetGulp = -> es.map (file, callback) -> nuget.pack file, (err, nupkg_file) -> return callback(err) if err nuget.push nupkg_file, (err) -> if err then gutil.log(err) else callback() HEADER = module.exports = """ /* <%= file.path.split('/').splice(-1)[0].replace('.min', '') %> <%= pkg.version %> Copyright (c) 2011-#{(new Date()).getFullYear()} <NAME>. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */\n """ LIBRARY_FILES = require('./config/files').libraries gulp.task 'build', buildLibraries = (callback) -> errors = [] gulp.src('config/builds/library/**/*.webpack.config.coffee') .pipe(webpack()) .pipe(header(HEADER, {pkg: require('./package.json')})) .pipe(gulp.dest('.')) .on('end', callback) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'watch', ['build'], -> gulp.watch './src/**/*.coffee', -> buildLibraries(->) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'minify', ['build'], (callback) -> gulp.src(['*.js', '!*.min.js', '!_temp/**/*.js', '!node_modules/']) .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(header(HEADER, {pkg: require('./package.json')})) .pipe(gulp.dest((file) -> file.base)) .on('end', callback) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 testNode = (callback) -> tags = ("@#{tag.replace(/^[-]+/, '')}" for tag in process.argv.slice(3)).join(' ') mochaOptions = {reporter: 'dot', compilers: 'coffee:coffee-script/register'} mochaOptions.grep = tags if tags gutil.log "Running Node.js tests #{tags}" gulp.src('test/spec/**/*.tests.coffee') .pipe(mocha(mochaOptions)) .pipe es.writeArray callback return # promises workaround: https://github.com/gulpjs/gulp/issues/455 testBrowsers = (callback) -> tags = ("@#{tag.replace(/^[-]+/, '')}" for tag in process.argv.slice(3)).join(' ') gutil.log "Running Browser tests #{tags}" (require './config/karma/run')({tags}, callback) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'test-node', ['build'], testNode # gulp.task 'test-browsers', testBrowsers gulp.task 'test-browsers', ['minify'], testBrowsers gulp.task 'test', ['minify'], (callback) -> Async.series [testNode, testBrowsers], (err) -> not err || console.log(err); process.exit(if err then 1 else 0) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'publish', ['minify'], (callback) -> copyLibraryFiles = (destination, others, callback) -> gulp.src(LIBRARY_FILES.concat(['README.md', 'RELEASE_NOTES.md'].concat(others))) .pipe(gulp.dest((file) -> path.join(destination, path.dirname(file.path).replace(__dirname, '')))) .on('end', callback) queue = new Queue(1) queue.defer (callback) -> Async.series [testNode, testBrowsers], callback queue.defer (callback) -> copyLibraryFiles('packages/npm', ['component.json', 'bower.json'], callback) queue.defer (callback) -> copyLibraryFiles('packages/nuget/Content/Scripts', [], callback) queue.defer (callback) -> gulp.src('packages/nuget/*.nuspec') .pipe(nugetGulp()) .on('end', callback) queue.await (err) -> not err || console.log(err); process.exit(if err then 1 else 0) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'default', ['test-node']
true
path = require 'path' _ = require 'underscore' Queue = require 'queue-async' Async = require 'async' es = require 'event-stream' gulp = require 'gulp' gutil = require 'gulp-util' webpack = require 'gulp-webpack-config' rename = require 'gulp-rename' uglify = require 'gulp-uglify' header = require 'gulp-header' mocha = require 'gulp-mocha' nuget = require 'nuget' nugetGulp = -> es.map (file, callback) -> nuget.pack file, (err, nupkg_file) -> return callback(err) if err nuget.push nupkg_file, (err) -> if err then gutil.log(err) else callback() HEADER = module.exports = """ /* <%= file.path.split('/').splice(-1)[0].replace('.min', '') %> <%= pkg.version %> Copyright (c) 2011-#{(new Date()).getFullYear()} PI:NAME:<NAME>END_PI. License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/kmalakoff/knockback Dependencies: Knockout.js, Backbone.js, and Underscore.js (or LoDash.js). Optional dependencies: Backbone.ModelRef.js and BackboneORM. */\n """ LIBRARY_FILES = require('./config/files').libraries gulp.task 'build', buildLibraries = (callback) -> errors = [] gulp.src('config/builds/library/**/*.webpack.config.coffee') .pipe(webpack()) .pipe(header(HEADER, {pkg: require('./package.json')})) .pipe(gulp.dest('.')) .on('end', callback) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'watch', ['build'], -> gulp.watch './src/**/*.coffee', -> buildLibraries(->) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'minify', ['build'], (callback) -> gulp.src(['*.js', '!*.min.js', '!_temp/**/*.js', '!node_modules/']) .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(header(HEADER, {pkg: require('./package.json')})) .pipe(gulp.dest((file) -> file.base)) .on('end', callback) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 testNode = (callback) -> tags = ("@#{tag.replace(/^[-]+/, '')}" for tag in process.argv.slice(3)).join(' ') mochaOptions = {reporter: 'dot', compilers: 'coffee:coffee-script/register'} mochaOptions.grep = tags if tags gutil.log "Running Node.js tests #{tags}" gulp.src('test/spec/**/*.tests.coffee') .pipe(mocha(mochaOptions)) .pipe es.writeArray callback return # promises workaround: https://github.com/gulpjs/gulp/issues/455 testBrowsers = (callback) -> tags = ("@#{tag.replace(/^[-]+/, '')}" for tag in process.argv.slice(3)).join(' ') gutil.log "Running Browser tests #{tags}" (require './config/karma/run')({tags}, callback) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'test-node', ['build'], testNode # gulp.task 'test-browsers', testBrowsers gulp.task 'test-browsers', ['minify'], testBrowsers gulp.task 'test', ['minify'], (callback) -> Async.series [testNode, testBrowsers], (err) -> not err || console.log(err); process.exit(if err then 1 else 0) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'publish', ['minify'], (callback) -> copyLibraryFiles = (destination, others, callback) -> gulp.src(LIBRARY_FILES.concat(['README.md', 'RELEASE_NOTES.md'].concat(others))) .pipe(gulp.dest((file) -> path.join(destination, path.dirname(file.path).replace(__dirname, '')))) .on('end', callback) queue = new Queue(1) queue.defer (callback) -> Async.series [testNode, testBrowsers], callback queue.defer (callback) -> copyLibraryFiles('packages/npm', ['component.json', 'bower.json'], callback) queue.defer (callback) -> copyLibraryFiles('packages/nuget/Content/Scripts', [], callback) queue.defer (callback) -> gulp.src('packages/nuget/*.nuspec') .pipe(nugetGulp()) .on('end', callback) queue.await (err) -> not err || console.log(err); process.exit(if err then 1 else 0) return # promises workaround: https://github.com/gulpjs/gulp/issues/455 gulp.task 'default', ['test-node']
[ { "context": " #\n # Tag.\n #\n # Created by hector spc <hector@aerstudio.com>\n # Aer Studio \n # http:/", "end": 40, "score": 0.9908232092857361, "start": 30, "tag": "NAME", "value": "hector spc" }, { "context": " #\n # Tag.\n #\n # Created by hector spc <hector@aerstudio.com>\n # Aer Studio \n # http://www.aerstudio.com\n #\n", "end": 62, "score": 0.9999327063560486, "start": 42, "tag": "EMAIL", "value": "hector@aerstudio.com" } ]
src/models/tag_model.coffee
aerstudio/Phallanxpress
1
# # Tag. # # Created by hector spc <hector@aerstudio.com> # Aer Studio # http://www.aerstudio.com # # Sun Mar 04 2012 # # models/tag_model.js.coffee # class Phallanxpress.Tag extends Phallanxpress.Model
201505
# # Tag. # # Created by <NAME> <<EMAIL>> # Aer Studio # http://www.aerstudio.com # # Sun Mar 04 2012 # # models/tag_model.js.coffee # class Phallanxpress.Tag extends Phallanxpress.Model
true
# # Tag. # # Created by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Aer Studio # http://www.aerstudio.com # # Sun Mar 04 2012 # # models/tag_model.js.coffee # class Phallanxpress.Tag extends Phallanxpress.Model
[ { "context": "e_1}\", (data)=>\n data.user.name.assert_Is 'Joe'\n\n @.GET_Json \"/api/v1/team/#{project}/get", "end": 818, "score": 0.9993468523025513, "start": 815, "tag": "NAME", "value": "Joe" } ]
test/http/api/files.qa.test.coffee
DinisCruz-Dev/Maturity-Models-QA
0
Http_API = require '../../../src/_Test_APIs/Http-API' describe 'http | api | files', -> http_API = null project = null team = null before ()-> http_API = new Http_API() project = 'bsimm' team = 'team-A' it '/api/v1/files/list', (done)-> http_API.GET_Json '/api/v1/team/bsimm/list', (data)-> data.assert_Contains [ 'coffee-data', 'json-data' ] done() it '/api/v1/team/:project/get/AAAA', (done)-> http_API.GET_Json "/api/v1/team/#{project}/get/AAA", (data)-> data.error.assert_Is 'not found' done() it '/api/v1/team/:project/get/:team', (done)-> using http_API, -> file_1 = 'json-data' file_2 = 'coffee-data' @.GET_Json "/api/v1/team/#{project}/get/#{file_1}", (data)=> data.user.name.assert_Is 'Joe' @.GET_Json "/api/v1/team/#{project}/get/#{file_2}", (data)-> data.user.assert_Is 'in coffee' done() it '/api/v1/team/:project/get/json-data?pretty', (done)-> using http_API, -> @.GET "/api/v1/team/#{project}/get/json-data", (data_json)=> @.GET "/api/v1/team/#{project}/get/json-data?pretty", (data_pretty)-> data_json.str() .assert_Is_Not data_pretty data_json.json_Parse().assert_Is data_pretty.json_Parse() done()
82102
Http_API = require '../../../src/_Test_APIs/Http-API' describe 'http | api | files', -> http_API = null project = null team = null before ()-> http_API = new Http_API() project = 'bsimm' team = 'team-A' it '/api/v1/files/list', (done)-> http_API.GET_Json '/api/v1/team/bsimm/list', (data)-> data.assert_Contains [ 'coffee-data', 'json-data' ] done() it '/api/v1/team/:project/get/AAAA', (done)-> http_API.GET_Json "/api/v1/team/#{project}/get/AAA", (data)-> data.error.assert_Is 'not found' done() it '/api/v1/team/:project/get/:team', (done)-> using http_API, -> file_1 = 'json-data' file_2 = 'coffee-data' @.GET_Json "/api/v1/team/#{project}/get/#{file_1}", (data)=> data.user.name.assert_Is '<NAME>' @.GET_Json "/api/v1/team/#{project}/get/#{file_2}", (data)-> data.user.assert_Is 'in coffee' done() it '/api/v1/team/:project/get/json-data?pretty', (done)-> using http_API, -> @.GET "/api/v1/team/#{project}/get/json-data", (data_json)=> @.GET "/api/v1/team/#{project}/get/json-data?pretty", (data_pretty)-> data_json.str() .assert_Is_Not data_pretty data_json.json_Parse().assert_Is data_pretty.json_Parse() done()
true
Http_API = require '../../../src/_Test_APIs/Http-API' describe 'http | api | files', -> http_API = null project = null team = null before ()-> http_API = new Http_API() project = 'bsimm' team = 'team-A' it '/api/v1/files/list', (done)-> http_API.GET_Json '/api/v1/team/bsimm/list', (data)-> data.assert_Contains [ 'coffee-data', 'json-data' ] done() it '/api/v1/team/:project/get/AAAA', (done)-> http_API.GET_Json "/api/v1/team/#{project}/get/AAA", (data)-> data.error.assert_Is 'not found' done() it '/api/v1/team/:project/get/:team', (done)-> using http_API, -> file_1 = 'json-data' file_2 = 'coffee-data' @.GET_Json "/api/v1/team/#{project}/get/#{file_1}", (data)=> data.user.name.assert_Is 'PI:NAME:<NAME>END_PI' @.GET_Json "/api/v1/team/#{project}/get/#{file_2}", (data)-> data.user.assert_Is 'in coffee' done() it '/api/v1/team/:project/get/json-data?pretty', (done)-> using http_API, -> @.GET "/api/v1/team/#{project}/get/json-data", (data_json)=> @.GET "/api/v1/team/#{project}/get/json-data?pretty", (data_pretty)-> data_json.str() .assert_Is_Not data_pretty data_json.json_Parse().assert_Is data_pretty.json_Parse() done()
[ { "context": "'\n serviceURL: 'https://render.ostr.io'\n auth: 'APIUser:APIPass'\n\napp.use(spiderable.handler).use (req, r", "end": 242, "score": 0.994704008102417, "start": 235, "tag": "USERNAME", "value": "APIUser" }, { "context": "iceURL: 'https://render.ostr.io'\n auth: 'APIUser:APIPass'\n\napp.use(spiderable.handler).use (req, res) ", "end": 246, "score": 0.6781956553459167, "start": 243, "tag": "USERNAME", "value": "API" }, { "context": "URL: 'https://render.ostr.io'\n auth: 'APIUser:APIPass'\n\napp.use(spiderable.handler).use (req, res) ->\n ", "end": 250, "score": 0.6700453162193298, "start": 246, "tag": "PASSWORD", "value": "Pass" } ]
examples/connect.middleware.coffee
VeliovGroup/spiderable-middleware
27
connect = require 'connect' http = require 'http' app = connect() Spiderable = require 'spiderable-middleware' spiderable = new Spiderable rootURL: 'http://example.com' serviceURL: 'https://render.ostr.io' auth: 'APIUser:APIPass' app.use(spiderable.handler).use (req, res) -> res.end 'Hello from Connect!\n' http.createServer(app).listen 3000
208893
connect = require 'connect' http = require 'http' app = connect() Spiderable = require 'spiderable-middleware' spiderable = new Spiderable rootURL: 'http://example.com' serviceURL: 'https://render.ostr.io' auth: 'APIUser:API<PASSWORD>' app.use(spiderable.handler).use (req, res) -> res.end 'Hello from Connect!\n' http.createServer(app).listen 3000
true
connect = require 'connect' http = require 'http' app = connect() Spiderable = require 'spiderable-middleware' spiderable = new Spiderable rootURL: 'http://example.com' serviceURL: 'https://render.ostr.io' auth: 'APIUser:APIPI:PASSWORD:<PASSWORD>END_PI' app.use(spiderable.handler).use (req, res) -> res.end 'Hello from Connect!\n' http.createServer(app).listen 3000
[ { "context": "$http.post('/login', {email: data.email, password: data.password})\n loginPromise.then (resp) ->\n $", "end": 1007, "score": 0.9991476535797119, "start": 994, "tag": "PASSWORD", "value": "data.password" } ]
frontend/javascripts/welcome.js.coffee
MakerButt/chaipcr
1
App = angular.module 'WelcomeApp', [] App.config ['$httpProvider', ($httpProvider) -> $httpProvider.defaults.headers.post['X-CSRF-Token'] = angular.element('meta[name="csrf-token"]').attr 'content' $httpProvider.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest' ] App.controller 'WelcomeCtrl', [ '$scope' '$http' '$window' '$rootScope' ($scope, $http, $window, $rootScope) -> $rootScope.pageTitle = "Open qPCR | Chai" $scope.user = role: 'admin' @getSoftwareData = () -> $http.get("/device").then((device) -> if device.data?.serial_number? $scope.serial_number = device.data.serial_number if device.data?.software?.version? $scope.software_version = device.data.software.version ) @getSoftwareData() $scope.submit = (data) -> promise = $http.post '/users', user: data promise.then (resp) -> loginPromise = $http.post('/login', {email: data.email, password: data.password}) loginPromise.then (resp) -> $.jStorage.set 'authToken', resp.data.authentication_token $.jStorage.set 'userId', resp.data.user_id $window.location.assign '/' promise.catch (resp) -> $scope.errors = resp.data.user.errors ]
142876
App = angular.module 'WelcomeApp', [] App.config ['$httpProvider', ($httpProvider) -> $httpProvider.defaults.headers.post['X-CSRF-Token'] = angular.element('meta[name="csrf-token"]').attr 'content' $httpProvider.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest' ] App.controller 'WelcomeCtrl', [ '$scope' '$http' '$window' '$rootScope' ($scope, $http, $window, $rootScope) -> $rootScope.pageTitle = "Open qPCR | Chai" $scope.user = role: 'admin' @getSoftwareData = () -> $http.get("/device").then((device) -> if device.data?.serial_number? $scope.serial_number = device.data.serial_number if device.data?.software?.version? $scope.software_version = device.data.software.version ) @getSoftwareData() $scope.submit = (data) -> promise = $http.post '/users', user: data promise.then (resp) -> loginPromise = $http.post('/login', {email: data.email, password: <PASSWORD>}) loginPromise.then (resp) -> $.jStorage.set 'authToken', resp.data.authentication_token $.jStorage.set 'userId', resp.data.user_id $window.location.assign '/' promise.catch (resp) -> $scope.errors = resp.data.user.errors ]
true
App = angular.module 'WelcomeApp', [] App.config ['$httpProvider', ($httpProvider) -> $httpProvider.defaults.headers.post['X-CSRF-Token'] = angular.element('meta[name="csrf-token"]').attr 'content' $httpProvider.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest' ] App.controller 'WelcomeCtrl', [ '$scope' '$http' '$window' '$rootScope' ($scope, $http, $window, $rootScope) -> $rootScope.pageTitle = "Open qPCR | Chai" $scope.user = role: 'admin' @getSoftwareData = () -> $http.get("/device").then((device) -> if device.data?.serial_number? $scope.serial_number = device.data.serial_number if device.data?.software?.version? $scope.software_version = device.data.software.version ) @getSoftwareData() $scope.submit = (data) -> promise = $http.post '/users', user: data promise.then (resp) -> loginPromise = $http.post('/login', {email: data.email, password: PI:PASSWORD:<PASSWORD>END_PI}) loginPromise.then (resp) -> $.jStorage.set 'authToken', resp.data.authentication_token $.jStorage.set 'userId', resp.data.user_id $window.location.assign '/' promise.catch (resp) -> $scope.errors = resp.data.user.errors ]
[ { "context": "o=bar#\"\n email: \"http://localhost:3500/?email=brian@cypress.io\"\n heroku: \"https://example.herokuapp.com\"\n he", "end": 655, "score": 0.9999045729637146, "start": 639, "tag": "EMAIL", "value": "brian@cypress.io" }, { "context": " expect(obj).to.deep.eq({\n username: \"cypress\"\n password: \"password123\"\n })\n\n it", "end": 1309, "score": 0.9725360870361328, "start": 1302, "tag": "USERNAME", "value": "cypress" }, { "context": "({\n username: \"cypress\"\n password: \"password123\"\n })\n\n it \"returns undefined when no user", "end": 1341, "score": 0.9993094801902771, "start": 1330, "tag": "PASSWORD", "value": "password123" }, { "context": ".create(urls.cypress, urls.signin)\n keys = [\"auth\", \"authObj\", \"hash\", \"href\", \"host\", \"hostname\", \"ori", "end": 5941, "score": 0.9446301460266113, "start": 5933, "tag": "KEY", "value": "auth\", \"" }, { "context": "urls.cypress, urls.signin)\n keys = [\"auth\", \"authObj\", \"hash\", \"href\", \"host\", \"hostname\", \"origin\", \"pa", "end": 5950, "score": 0.8354945778846741, "start": 5941, "tag": "KEY", "value": "authObj\"," }, { "context": "s, urls.signin)\n keys = [\"auth\", \"authObj\", \"hash\", \"href\", \"host\", \"hostname\", \"origin\", \"pathname\",", "end": 5958, "score": 0.840758204460144, "start": 5952, "tag": "KEY", "value": "hash\"," }, { "context": "o.uk/baz/quux\"\n\n describe \"localhost, 0.0.0.0, 127.0.0.1\", ->\n _.each [\"localhost\", \"0.0.0.0\", \"127.0", "end": 7886, "score": 0.9996750950813293, "start": 7877, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "0.0.1\", ->\n _.each [\"localhost\", \"0.0.0.0\", \"127.0.0.1\"], (host) =>\n it \"inserts http:// automati", "end": 7940, "score": 0.999674916267395, "start": 7931, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
packages/driver/test/cypress/integration/cypress/location_spec.coffee
Everworks/cypress
3
{ _, Location, Promise } = Cypress urls = { blank: "about:blank" cypress: "http://0.0.0.0:2020/__/#/tests/app.coffee" signin: "http://localhost:2020/signin" users: "http://localhost:2020/users/1" google: "https://www.google.com" ember: "http://localhost:2020/index.html#/posts" app: "http://localhost:2020/app/#posts/1" search: "http://localhost:2020/search?q=books" pathname: "http://localhost:2020/app/index.html" local: "http://127.0.0.1:8080/foo/bar" stack: "https://stackoverflow.com/" trailHash:"http://localhost:3500/index.html?foo=bar#" email: "http://localhost:3500/?email=brian@cypress.io" heroku: "https://example.herokuapp.com" herokuSub:"https://foo.example.herokuapp.com" unknown: "http://what.is.so.unknown" auth: "http://cypress:password123@localhost:8080/foo" } describe "src/cypress/location", -> beforeEach -> @setup = (remote) => new Location(urls[remote]) context "#getAuth", -> it "returns string with username + password", -> str = @setup("auth").getAuth() expect(str).to.eq("cypress:password123") context "#getAuthObj", -> it "returns an object with username and password", -> obj = @setup("auth").getAuthObj() expect(obj).to.deep.eq({ username: "cypress" password: "password123" }) it "returns undefined when no username or password", -> expect(@setup("app").getAuthObj()).to.be.undefined context "#getHash", -> it "returns the hash fragment prepended with #", -> str = @setup("app").getHash() expect(str).to.eq "#posts/1" it "returns empty string when no hash", -> str = @setup("signin").getHash() expect(str).to.eq "" it "returns empty when only hash is present", -> ## its weird, but this matches current browser behavior str = @setup("hash").getHash() expect(str).to.eq("") context "#getHref", -> it "returns the full url", -> str = @setup("signin").getHref() expect(str).to.eq "http://localhost:2020/signin" it "does not apply a leading slash after removing query params", -> str = @setup("ember").getHref() expect(str).to.eq "http://localhost:2020/index.html#/posts" it "includes hash even when hash is empty", -> str = @setup("trailHash").getHref() expect(str).to.eq(urls.trailHash) context "#getHost", -> it "returns port if port is present", -> str = @setup("signin").getHost() expect(str).to.eq("localhost:2020") it "omits port if port is blank", -> str = @setup("google").getHost() expect(str).to.eq("www.google.com") context "#getHostName", -> it "returns host without port", -> str = @setup("signin").getHostName() expect(str).to.eq("localhost") context "#getOrigin", -> it "returns the origin including port", -> str = @setup("signin").getOrigin() expect(str).to.eq("http://localhost:2020") it "returns the origin without port", -> str = @setup("google").getOrigin() expect(str).to.eq("https://www.google.com") it "returns the origin as null for about:blank", -> origin = @setup("blank").getOrigin() expect(origin).to.eq(null) context "#getPathName", -> it "returns the path", -> str = @setup("signin").getPathName() expect(str).to.eq("/signin") it "returns a / with no path", -> str = @setup("google").getPathName() expect(str).to.eq("/") it "returns the full pathname without a host", -> str = @setup("pathname").getPathName() expect(str).to.eq("/app/index.html") context "#getPort", -> it "returns the port", -> str = @setup("signin").getPort() expect(str).to.eq("2020") it "returns empty string if port is blank", -> str = @setup("google").getPort() expect(str).to.eq("") context "#getProtocol", -> it "returns the http protocol", -> str = @setup("signin").getProtocol() expect(str).to.eq("http:") it "returns the https protocol", -> str = @setup("google").getProtocol() expect(str).to.eq("https:") context "#getSearch", -> it "returns the search params with ? prepended", -> str = @setup("search").getSearch() expect(str).to.eq("?q=books") it "returns an empty string with no seach params", -> str = @setup("google").getSearch() expect(str).to.eq("") context "#getToString", -> it "returns the toString function", -> str = @setup("signin").getToString() expect(str).to.eq("http://localhost:2020/signin") context "#getOriginPolicy", -> it "handles ip addresses", -> str = @setup("local").getOriginPolicy() expect(str).to.eq("http://127.0.0.1:8080") it "handles 1 part localhost", -> str = @setup("users").getOriginPolicy() expect(str).to.eq("http://localhost:2020") it "handles 2 parts stack", -> str = @setup("stack").getOriginPolicy() expect(str).to.eq("https://stackoverflow.com") it "handles subdomains google", -> str = @setup("google").getOriginPolicy() expect(str).to.eq("https://google.com") it "issue: #255 two domains in the url", -> str = @setup("email").getOriginPolicy() expect(str).to.eq("http://localhost:3500") it "handles private tlds in the public suffix", -> str = @setup("heroku").getOriginPolicy() expect(str).to.eq("https://example.herokuapp.com") it "handles subdomains of private tlds in the public suffix", -> str = @setup("herokuSub").getOriginPolicy() expect(str).to.eq("https://example.herokuapp.com") it "falls back to dumb check when invalid tld", -> str = @setup("unknown").getOriginPolicy() expect(str).to.eq("http://so.unknown") context ".create", -> it "returns an object literal", -> obj = Location.create(urls.cypress, urls.signin) keys = ["auth", "authObj", "hash", "href", "host", "hostname", "origin", "pathname", "port", "protocol", "search", "toString", "originPolicy", "superDomain"] expect(obj).to.have.keys(keys) it "can invoke toString function", -> obj = Location.create(urls.signin) expect(obj.toString()).to.eq("http://localhost:2020/signin") context ".normalize", -> beforeEach -> @url = (source, expected) -> url = Location.normalize(source) expect(url).to.eq(expected) describe "http urls", -> it "does not trim url", -> @url "http://github.com/foo/", "http://github.com/foo/" it "adds trailing slash to host", -> @url "https://localhost:4200", "https://localhost:4200/" it "does not mutate hash when setting path to slash", -> @url "http://0.0.0.0:3000#foo/bar", "http://0.0.0.0:3000/#foo/bar" it "does not mutate path when it exists", -> @url "http://localhost:3000/foo/bar", "http://localhost:3000/foo/bar" describe "http-less urls", -> it "trims url", -> @url "/index.html/", "/index.html/" it "does not add trailing slash with query params", -> @url "timeout?ms=1000", "timeout?ms=1000" it "does not strip path segments", -> @url "fixtures/sinon.html", "fixtures/sinon.html" it "formats urls with protocols", -> @url "beta.cypress.io", "http://beta.cypress.io/" it "formats urls with protocols and query params", -> @url "beta.cypress.io?foo=bar", "http://beta.cypress.io/?foo=bar" it "formats urls with 3 segments and path", -> @url "aws.amazon.com/s3/bucket", "http://aws.amazon.com/s3/bucket" it "formats urls with 4 segments", -> @url "foo.bar.co.uk", "http://foo.bar.co.uk/" it "formats urls with 4 segments and path", -> @url "foo.bar.co.uk/baz/quux", "http://foo.bar.co.uk/baz/quux" describe "localhost, 0.0.0.0, 127.0.0.1", -> _.each ["localhost", "0.0.0.0", "127.0.0.1"], (host) => it "inserts http:// automatically for #{host}", -> @url "#{host}:4200", "http://#{host}:4200/" describe "localhost", -> it "keeps path / query params / hash around", -> @url "localhost:4200/foo/bar?quux=asdf#/main", "http://localhost:4200/foo/bar?quux=asdf#/main" context ".fullyQualifyUrl", -> beforeEach -> @normalize = (url) -> Location.normalize(url) it "does not append trailing slash on a sub directory", -> url = @normalize("http://localhost:4200/app") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:4200/app" it "does not append a trailing slash to url with hash", -> url = @normalize("http://localhost:4000/#/home") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:4000/#/home" it "does not append a trailing slash to protocol-less url with hash", -> url = @normalize("www.github.com/#/home") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://www.github.com/#/home" it "handles urls without a host", -> url = @normalize("index.html") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:3500/index.html" it "does not insert trailing slash without a host", -> url = Location.fullyQualifyUrl("index.html") expect(url).to.eq "http://localhost:3500/index.html" it "handles no host + query params", -> url = @normalize("timeout?ms=1000") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:3500/timeout?ms=1000" it "does not strip off path", -> url = @normalize("fixtures/sinon.html") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:3500/fixtures/sinon.html"
11422
{ _, Location, Promise } = Cypress urls = { blank: "about:blank" cypress: "http://0.0.0.0:2020/__/#/tests/app.coffee" signin: "http://localhost:2020/signin" users: "http://localhost:2020/users/1" google: "https://www.google.com" ember: "http://localhost:2020/index.html#/posts" app: "http://localhost:2020/app/#posts/1" search: "http://localhost:2020/search?q=books" pathname: "http://localhost:2020/app/index.html" local: "http://127.0.0.1:8080/foo/bar" stack: "https://stackoverflow.com/" trailHash:"http://localhost:3500/index.html?foo=bar#" email: "http://localhost:3500/?email=<EMAIL>" heroku: "https://example.herokuapp.com" herokuSub:"https://foo.example.herokuapp.com" unknown: "http://what.is.so.unknown" auth: "http://cypress:password123@localhost:8080/foo" } describe "src/cypress/location", -> beforeEach -> @setup = (remote) => new Location(urls[remote]) context "#getAuth", -> it "returns string with username + password", -> str = @setup("auth").getAuth() expect(str).to.eq("cypress:password123") context "#getAuthObj", -> it "returns an object with username and password", -> obj = @setup("auth").getAuthObj() expect(obj).to.deep.eq({ username: "cypress" password: "<PASSWORD>" }) it "returns undefined when no username or password", -> expect(@setup("app").getAuthObj()).to.be.undefined context "#getHash", -> it "returns the hash fragment prepended with #", -> str = @setup("app").getHash() expect(str).to.eq "#posts/1" it "returns empty string when no hash", -> str = @setup("signin").getHash() expect(str).to.eq "" it "returns empty when only hash is present", -> ## its weird, but this matches current browser behavior str = @setup("hash").getHash() expect(str).to.eq("") context "#getHref", -> it "returns the full url", -> str = @setup("signin").getHref() expect(str).to.eq "http://localhost:2020/signin" it "does not apply a leading slash after removing query params", -> str = @setup("ember").getHref() expect(str).to.eq "http://localhost:2020/index.html#/posts" it "includes hash even when hash is empty", -> str = @setup("trailHash").getHref() expect(str).to.eq(urls.trailHash) context "#getHost", -> it "returns port if port is present", -> str = @setup("signin").getHost() expect(str).to.eq("localhost:2020") it "omits port if port is blank", -> str = @setup("google").getHost() expect(str).to.eq("www.google.com") context "#getHostName", -> it "returns host without port", -> str = @setup("signin").getHostName() expect(str).to.eq("localhost") context "#getOrigin", -> it "returns the origin including port", -> str = @setup("signin").getOrigin() expect(str).to.eq("http://localhost:2020") it "returns the origin without port", -> str = @setup("google").getOrigin() expect(str).to.eq("https://www.google.com") it "returns the origin as null for about:blank", -> origin = @setup("blank").getOrigin() expect(origin).to.eq(null) context "#getPathName", -> it "returns the path", -> str = @setup("signin").getPathName() expect(str).to.eq("/signin") it "returns a / with no path", -> str = @setup("google").getPathName() expect(str).to.eq("/") it "returns the full pathname without a host", -> str = @setup("pathname").getPathName() expect(str).to.eq("/app/index.html") context "#getPort", -> it "returns the port", -> str = @setup("signin").getPort() expect(str).to.eq("2020") it "returns empty string if port is blank", -> str = @setup("google").getPort() expect(str).to.eq("") context "#getProtocol", -> it "returns the http protocol", -> str = @setup("signin").getProtocol() expect(str).to.eq("http:") it "returns the https protocol", -> str = @setup("google").getProtocol() expect(str).to.eq("https:") context "#getSearch", -> it "returns the search params with ? prepended", -> str = @setup("search").getSearch() expect(str).to.eq("?q=books") it "returns an empty string with no seach params", -> str = @setup("google").getSearch() expect(str).to.eq("") context "#getToString", -> it "returns the toString function", -> str = @setup("signin").getToString() expect(str).to.eq("http://localhost:2020/signin") context "#getOriginPolicy", -> it "handles ip addresses", -> str = @setup("local").getOriginPolicy() expect(str).to.eq("http://127.0.0.1:8080") it "handles 1 part localhost", -> str = @setup("users").getOriginPolicy() expect(str).to.eq("http://localhost:2020") it "handles 2 parts stack", -> str = @setup("stack").getOriginPolicy() expect(str).to.eq("https://stackoverflow.com") it "handles subdomains google", -> str = @setup("google").getOriginPolicy() expect(str).to.eq("https://google.com") it "issue: #255 two domains in the url", -> str = @setup("email").getOriginPolicy() expect(str).to.eq("http://localhost:3500") it "handles private tlds in the public suffix", -> str = @setup("heroku").getOriginPolicy() expect(str).to.eq("https://example.herokuapp.com") it "handles subdomains of private tlds in the public suffix", -> str = @setup("herokuSub").getOriginPolicy() expect(str).to.eq("https://example.herokuapp.com") it "falls back to dumb check when invalid tld", -> str = @setup("unknown").getOriginPolicy() expect(str).to.eq("http://so.unknown") context ".create", -> it "returns an object literal", -> obj = Location.create(urls.cypress, urls.signin) keys = ["<KEY> <KEY> "<KEY> "href", "host", "hostname", "origin", "pathname", "port", "protocol", "search", "toString", "originPolicy", "superDomain"] expect(obj).to.have.keys(keys) it "can invoke toString function", -> obj = Location.create(urls.signin) expect(obj.toString()).to.eq("http://localhost:2020/signin") context ".normalize", -> beforeEach -> @url = (source, expected) -> url = Location.normalize(source) expect(url).to.eq(expected) describe "http urls", -> it "does not trim url", -> @url "http://github.com/foo/", "http://github.com/foo/" it "adds trailing slash to host", -> @url "https://localhost:4200", "https://localhost:4200/" it "does not mutate hash when setting path to slash", -> @url "http://0.0.0.0:3000#foo/bar", "http://0.0.0.0:3000/#foo/bar" it "does not mutate path when it exists", -> @url "http://localhost:3000/foo/bar", "http://localhost:3000/foo/bar" describe "http-less urls", -> it "trims url", -> @url "/index.html/", "/index.html/" it "does not add trailing slash with query params", -> @url "timeout?ms=1000", "timeout?ms=1000" it "does not strip path segments", -> @url "fixtures/sinon.html", "fixtures/sinon.html" it "formats urls with protocols", -> @url "beta.cypress.io", "http://beta.cypress.io/" it "formats urls with protocols and query params", -> @url "beta.cypress.io?foo=bar", "http://beta.cypress.io/?foo=bar" it "formats urls with 3 segments and path", -> @url "aws.amazon.com/s3/bucket", "http://aws.amazon.com/s3/bucket" it "formats urls with 4 segments", -> @url "foo.bar.co.uk", "http://foo.bar.co.uk/" it "formats urls with 4 segments and path", -> @url "foo.bar.co.uk/baz/quux", "http://foo.bar.co.uk/baz/quux" describe "localhost, 0.0.0.0, 127.0.0.1", -> _.each ["localhost", "0.0.0.0", "127.0.0.1"], (host) => it "inserts http:// automatically for #{host}", -> @url "#{host}:4200", "http://#{host}:4200/" describe "localhost", -> it "keeps path / query params / hash around", -> @url "localhost:4200/foo/bar?quux=asdf#/main", "http://localhost:4200/foo/bar?quux=asdf#/main" context ".fullyQualifyUrl", -> beforeEach -> @normalize = (url) -> Location.normalize(url) it "does not append trailing slash on a sub directory", -> url = @normalize("http://localhost:4200/app") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:4200/app" it "does not append a trailing slash to url with hash", -> url = @normalize("http://localhost:4000/#/home") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:4000/#/home" it "does not append a trailing slash to protocol-less url with hash", -> url = @normalize("www.github.com/#/home") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://www.github.com/#/home" it "handles urls without a host", -> url = @normalize("index.html") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:3500/index.html" it "does not insert trailing slash without a host", -> url = Location.fullyQualifyUrl("index.html") expect(url).to.eq "http://localhost:3500/index.html" it "handles no host + query params", -> url = @normalize("timeout?ms=1000") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:3500/timeout?ms=1000" it "does not strip off path", -> url = @normalize("fixtures/sinon.html") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:3500/fixtures/sinon.html"
true
{ _, Location, Promise } = Cypress urls = { blank: "about:blank" cypress: "http://0.0.0.0:2020/__/#/tests/app.coffee" signin: "http://localhost:2020/signin" users: "http://localhost:2020/users/1" google: "https://www.google.com" ember: "http://localhost:2020/index.html#/posts" app: "http://localhost:2020/app/#posts/1" search: "http://localhost:2020/search?q=books" pathname: "http://localhost:2020/app/index.html" local: "http://127.0.0.1:8080/foo/bar" stack: "https://stackoverflow.com/" trailHash:"http://localhost:3500/index.html?foo=bar#" email: "http://localhost:3500/?email=PI:EMAIL:<EMAIL>END_PI" heroku: "https://example.herokuapp.com" herokuSub:"https://foo.example.herokuapp.com" unknown: "http://what.is.so.unknown" auth: "http://cypress:password123@localhost:8080/foo" } describe "src/cypress/location", -> beforeEach -> @setup = (remote) => new Location(urls[remote]) context "#getAuth", -> it "returns string with username + password", -> str = @setup("auth").getAuth() expect(str).to.eq("cypress:password123") context "#getAuthObj", -> it "returns an object with username and password", -> obj = @setup("auth").getAuthObj() expect(obj).to.deep.eq({ username: "cypress" password: "PI:PASSWORD:<PASSWORD>END_PI" }) it "returns undefined when no username or password", -> expect(@setup("app").getAuthObj()).to.be.undefined context "#getHash", -> it "returns the hash fragment prepended with #", -> str = @setup("app").getHash() expect(str).to.eq "#posts/1" it "returns empty string when no hash", -> str = @setup("signin").getHash() expect(str).to.eq "" it "returns empty when only hash is present", -> ## its weird, but this matches current browser behavior str = @setup("hash").getHash() expect(str).to.eq("") context "#getHref", -> it "returns the full url", -> str = @setup("signin").getHref() expect(str).to.eq "http://localhost:2020/signin" it "does not apply a leading slash after removing query params", -> str = @setup("ember").getHref() expect(str).to.eq "http://localhost:2020/index.html#/posts" it "includes hash even when hash is empty", -> str = @setup("trailHash").getHref() expect(str).to.eq(urls.trailHash) context "#getHost", -> it "returns port if port is present", -> str = @setup("signin").getHost() expect(str).to.eq("localhost:2020") it "omits port if port is blank", -> str = @setup("google").getHost() expect(str).to.eq("www.google.com") context "#getHostName", -> it "returns host without port", -> str = @setup("signin").getHostName() expect(str).to.eq("localhost") context "#getOrigin", -> it "returns the origin including port", -> str = @setup("signin").getOrigin() expect(str).to.eq("http://localhost:2020") it "returns the origin without port", -> str = @setup("google").getOrigin() expect(str).to.eq("https://www.google.com") it "returns the origin as null for about:blank", -> origin = @setup("blank").getOrigin() expect(origin).to.eq(null) context "#getPathName", -> it "returns the path", -> str = @setup("signin").getPathName() expect(str).to.eq("/signin") it "returns a / with no path", -> str = @setup("google").getPathName() expect(str).to.eq("/") it "returns the full pathname without a host", -> str = @setup("pathname").getPathName() expect(str).to.eq("/app/index.html") context "#getPort", -> it "returns the port", -> str = @setup("signin").getPort() expect(str).to.eq("2020") it "returns empty string if port is blank", -> str = @setup("google").getPort() expect(str).to.eq("") context "#getProtocol", -> it "returns the http protocol", -> str = @setup("signin").getProtocol() expect(str).to.eq("http:") it "returns the https protocol", -> str = @setup("google").getProtocol() expect(str).to.eq("https:") context "#getSearch", -> it "returns the search params with ? prepended", -> str = @setup("search").getSearch() expect(str).to.eq("?q=books") it "returns an empty string with no seach params", -> str = @setup("google").getSearch() expect(str).to.eq("") context "#getToString", -> it "returns the toString function", -> str = @setup("signin").getToString() expect(str).to.eq("http://localhost:2020/signin") context "#getOriginPolicy", -> it "handles ip addresses", -> str = @setup("local").getOriginPolicy() expect(str).to.eq("http://127.0.0.1:8080") it "handles 1 part localhost", -> str = @setup("users").getOriginPolicy() expect(str).to.eq("http://localhost:2020") it "handles 2 parts stack", -> str = @setup("stack").getOriginPolicy() expect(str).to.eq("https://stackoverflow.com") it "handles subdomains google", -> str = @setup("google").getOriginPolicy() expect(str).to.eq("https://google.com") it "issue: #255 two domains in the url", -> str = @setup("email").getOriginPolicy() expect(str).to.eq("http://localhost:3500") it "handles private tlds in the public suffix", -> str = @setup("heroku").getOriginPolicy() expect(str).to.eq("https://example.herokuapp.com") it "handles subdomains of private tlds in the public suffix", -> str = @setup("herokuSub").getOriginPolicy() expect(str).to.eq("https://example.herokuapp.com") it "falls back to dumb check when invalid tld", -> str = @setup("unknown").getOriginPolicy() expect(str).to.eq("http://so.unknown") context ".create", -> it "returns an object literal", -> obj = Location.create(urls.cypress, urls.signin) keys = ["PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI "href", "host", "hostname", "origin", "pathname", "port", "protocol", "search", "toString", "originPolicy", "superDomain"] expect(obj).to.have.keys(keys) it "can invoke toString function", -> obj = Location.create(urls.signin) expect(obj.toString()).to.eq("http://localhost:2020/signin") context ".normalize", -> beforeEach -> @url = (source, expected) -> url = Location.normalize(source) expect(url).to.eq(expected) describe "http urls", -> it "does not trim url", -> @url "http://github.com/foo/", "http://github.com/foo/" it "adds trailing slash to host", -> @url "https://localhost:4200", "https://localhost:4200/" it "does not mutate hash when setting path to slash", -> @url "http://0.0.0.0:3000#foo/bar", "http://0.0.0.0:3000/#foo/bar" it "does not mutate path when it exists", -> @url "http://localhost:3000/foo/bar", "http://localhost:3000/foo/bar" describe "http-less urls", -> it "trims url", -> @url "/index.html/", "/index.html/" it "does not add trailing slash with query params", -> @url "timeout?ms=1000", "timeout?ms=1000" it "does not strip path segments", -> @url "fixtures/sinon.html", "fixtures/sinon.html" it "formats urls with protocols", -> @url "beta.cypress.io", "http://beta.cypress.io/" it "formats urls with protocols and query params", -> @url "beta.cypress.io?foo=bar", "http://beta.cypress.io/?foo=bar" it "formats urls with 3 segments and path", -> @url "aws.amazon.com/s3/bucket", "http://aws.amazon.com/s3/bucket" it "formats urls with 4 segments", -> @url "foo.bar.co.uk", "http://foo.bar.co.uk/" it "formats urls with 4 segments and path", -> @url "foo.bar.co.uk/baz/quux", "http://foo.bar.co.uk/baz/quux" describe "localhost, 0.0.0.0, 127.0.0.1", -> _.each ["localhost", "0.0.0.0", "127.0.0.1"], (host) => it "inserts http:// automatically for #{host}", -> @url "#{host}:4200", "http://#{host}:4200/" describe "localhost", -> it "keeps path / query params / hash around", -> @url "localhost:4200/foo/bar?quux=asdf#/main", "http://localhost:4200/foo/bar?quux=asdf#/main" context ".fullyQualifyUrl", -> beforeEach -> @normalize = (url) -> Location.normalize(url) it "does not append trailing slash on a sub directory", -> url = @normalize("http://localhost:4200/app") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:4200/app" it "does not append a trailing slash to url with hash", -> url = @normalize("http://localhost:4000/#/home") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:4000/#/home" it "does not append a trailing slash to protocol-less url with hash", -> url = @normalize("www.github.com/#/home") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://www.github.com/#/home" it "handles urls without a host", -> url = @normalize("index.html") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:3500/index.html" it "does not insert trailing slash without a host", -> url = Location.fullyQualifyUrl("index.html") expect(url).to.eq "http://localhost:3500/index.html" it "handles no host + query params", -> url = @normalize("timeout?ms=1000") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:3500/timeout?ms=1000" it "does not strip off path", -> url = @normalize("fixtures/sinon.html") url = Location.fullyQualifyUrl(url) expect(url).to.eq "http://localhost:3500/fixtures/sinon.html"