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": ": ObjectId(\"ffffffffffffb00000000001\")\n name: \"Best Child\",\n hidden: 'Nice Surprise'\n },\n {\n ", "end": 131, "score": 0.7226483821868896, "start": 127, "tag": "NAME", "value": "Best" }, { "context": " ObjectId(\"ffffffffffffb00000000002\"),\n name: \"Worst Child\",\n hidden: 'Awful Secret'\n }\n]\n\n", "end": 240, "score": 0.6411247849464417, "start": 235, "tag": "NAME", "value": "Worst" } ]
test/integration/fixtures/basic/childresources.coffee
gigwell/nerm
0
ObjectId = require('mongoose').Types.ObjectId module.exports = [ { _id: ObjectId("ffffffffffffb00000000001") name: "Best Child", hidden: 'Nice Surprise' }, { _id: ObjectId("ffffffffffffb00000000002"), name: "Worst Child", hidden: 'Awful Secret' } ]
71082
ObjectId = require('mongoose').Types.ObjectId module.exports = [ { _id: ObjectId("ffffffffffffb00000000001") name: "<NAME> Child", hidden: 'Nice Surprise' }, { _id: ObjectId("ffffffffffffb00000000002"), name: "<NAME> Child", hidden: 'Awful Secret' } ]
true
ObjectId = require('mongoose').Types.ObjectId module.exports = [ { _id: ObjectId("ffffffffffffb00000000001") name: "PI:NAME:<NAME>END_PI Child", hidden: 'Nice Surprise' }, { _id: ObjectId("ffffffffffffb00000000002"), name: "PI:NAME:<NAME>END_PI Child", hidden: 'Awful Secret' } ]
[ { "context": "r\n credentials = { scheme: \"basic\", user: \"username\", password: \"wrong\" }\n browser.visit \"http", "end": 874, "score": 0.9592278599739075, "start": 866, "tag": "USERNAME", "value": "username" }, { "context": "= { scheme: \"basic\", user: \"username\", password: \"wrong\" }\n browser.visit \"http://localhost:3003/a", "end": 893, "score": 0.9995036125183105, "start": 888, "tag": "PASSWORD", "value": "wrong" }, { "context": "r\n credentials = { scheme: \"basic\", user: \"username\", password: \"pass123\" }\n browser.visit \"ht", "end": 1220, "score": 0.9872027039527893, "start": 1212, "tag": "USERNAME", "value": "username" }, { "context": "= { scheme: \"basic\", user: \"username\", password: \"pass123\" }\n browser.visit \"http://localhost:3003/a", "end": 1241, "score": 0.9993067979812622, "start": 1234, "tag": "PASSWORD", "value": "pass123" }, { "context": " credentials = { scheme: \"bearer\", token: \"wrong\" }\n browser.visit \"http://localhost:3003/a", "end": 2228, "score": 0.851070761680603, "start": 2223, "tag": "PASSWORD", "value": "wrong" }, { "context": " credentials = { scheme: \"bearer\", token: \"12345\" }\n browser.visit \"http://localhost:3003/a", "end": 2555, "score": 0.9814753532409668, "start": 2550, "tag": "PASSWORD", "value": "12345" } ]
libs/tester/node_modules/zombie/spec/authentication_spec.coffee
wudi/chico
1
{ Vows, assert, brains, Browser } = require("./helpers") Vows.describe("Authentication").addBatch "basic": topic: -> brains.get "/auth/basic", (req, res) -> if auth = req.headers.authorization if auth == "Basic dXNlcm5hbWU6cGFzczEyMw==" res.send "<html><body>#{req.headers["authorization"]}</body></html>" else res.send "Invalid credentials", 401 else res.send "Missing credentials", 401 brains.ready @callback "without credentials": topic: -> browser = new Browser browser.visit "http://localhost:3003/auth/basic", @callback "should return status code 401": (browser)-> assert.equal browser.statusCode, 401 "with invalid credentials": topic: -> browser = new Browser credentials = { scheme: "basic", user: "username", password: "wrong" } browser.visit "http://localhost:3003/auth/basic", credentials: credentials, @callback "should return status code 401": (browser)-> assert.equal browser.statusCode, 401 "with valid credentials": topic: -> browser = new Browser credentials = { scheme: "basic", user: "username", password: "pass123" } browser.visit "http://localhost:3003/auth/basic", credentials: credentials, @callback "should have the authentication header": (browser)-> assert.equal browser.text("body"), "Basic dXNlcm5hbWU6cGFzczEyMw==" "OAuth bearer": topic: -> brains.get "/auth/oauth2", (req, res) -> if auth = req.headers.authorization if auth == "Bearer 12345" res.send "<html><body>#{req.headers["authorization"]}</body></html>" else res.send "Invalid token", 401 else res.send "Missing token", 401 brains.ready @callback "without credentials": topic: -> browser = new Browser browser.visit "http://localhost:3003/auth/oauth2", @callback "should return status code 401": (browser)-> assert.equal browser.statusCode, 401 "with invalid credentials": topic: -> browser = new Browser credentials = { scheme: "bearer", token: "wrong" } browser.visit "http://localhost:3003/auth/oauth2", credentials: credentials, @callback "should return status code 401": (browser)-> assert.equal browser.statusCode, 401 "with valid credentials": topic: -> browser = new Browser credentials = { scheme: "bearer", token: "12345" } browser.visit "http://localhost:3003/auth/oauth2", credentials: credentials, @callback "should have the authentication header": (browser)-> assert.equal browser.text("body"), "Bearer 12345" .export(module)
31805
{ Vows, assert, brains, Browser } = require("./helpers") Vows.describe("Authentication").addBatch "basic": topic: -> brains.get "/auth/basic", (req, res) -> if auth = req.headers.authorization if auth == "Basic dXNlcm5hbWU6cGFzczEyMw==" res.send "<html><body>#{req.headers["authorization"]}</body></html>" else res.send "Invalid credentials", 401 else res.send "Missing credentials", 401 brains.ready @callback "without credentials": topic: -> browser = new Browser browser.visit "http://localhost:3003/auth/basic", @callback "should return status code 401": (browser)-> assert.equal browser.statusCode, 401 "with invalid credentials": topic: -> browser = new Browser credentials = { scheme: "basic", user: "username", password: "<PASSWORD>" } browser.visit "http://localhost:3003/auth/basic", credentials: credentials, @callback "should return status code 401": (browser)-> assert.equal browser.statusCode, 401 "with valid credentials": topic: -> browser = new Browser credentials = { scheme: "basic", user: "username", password: "<PASSWORD>" } browser.visit "http://localhost:3003/auth/basic", credentials: credentials, @callback "should have the authentication header": (browser)-> assert.equal browser.text("body"), "Basic dXNlcm5hbWU6cGFzczEyMw==" "OAuth bearer": topic: -> brains.get "/auth/oauth2", (req, res) -> if auth = req.headers.authorization if auth == "Bearer 12345" res.send "<html><body>#{req.headers["authorization"]}</body></html>" else res.send "Invalid token", 401 else res.send "Missing token", 401 brains.ready @callback "without credentials": topic: -> browser = new Browser browser.visit "http://localhost:3003/auth/oauth2", @callback "should return status code 401": (browser)-> assert.equal browser.statusCode, 401 "with invalid credentials": topic: -> browser = new Browser credentials = { scheme: "bearer", token: "<PASSWORD>" } browser.visit "http://localhost:3003/auth/oauth2", credentials: credentials, @callback "should return status code 401": (browser)-> assert.equal browser.statusCode, 401 "with valid credentials": topic: -> browser = new Browser credentials = { scheme: "bearer", token: "<PASSWORD>" } browser.visit "http://localhost:3003/auth/oauth2", credentials: credentials, @callback "should have the authentication header": (browser)-> assert.equal browser.text("body"), "Bearer 12345" .export(module)
true
{ Vows, assert, brains, Browser } = require("./helpers") Vows.describe("Authentication").addBatch "basic": topic: -> brains.get "/auth/basic", (req, res) -> if auth = req.headers.authorization if auth == "Basic dXNlcm5hbWU6cGFzczEyMw==" res.send "<html><body>#{req.headers["authorization"]}</body></html>" else res.send "Invalid credentials", 401 else res.send "Missing credentials", 401 brains.ready @callback "without credentials": topic: -> browser = new Browser browser.visit "http://localhost:3003/auth/basic", @callback "should return status code 401": (browser)-> assert.equal browser.statusCode, 401 "with invalid credentials": topic: -> browser = new Browser credentials = { scheme: "basic", user: "username", password: "PI:PASSWORD:<PASSWORD>END_PI" } browser.visit "http://localhost:3003/auth/basic", credentials: credentials, @callback "should return status code 401": (browser)-> assert.equal browser.statusCode, 401 "with valid credentials": topic: -> browser = new Browser credentials = { scheme: "basic", user: "username", password: "PI:PASSWORD:<PASSWORD>END_PI" } browser.visit "http://localhost:3003/auth/basic", credentials: credentials, @callback "should have the authentication header": (browser)-> assert.equal browser.text("body"), "Basic dXNlcm5hbWU6cGFzczEyMw==" "OAuth bearer": topic: -> brains.get "/auth/oauth2", (req, res) -> if auth = req.headers.authorization if auth == "Bearer 12345" res.send "<html><body>#{req.headers["authorization"]}</body></html>" else res.send "Invalid token", 401 else res.send "Missing token", 401 brains.ready @callback "without credentials": topic: -> browser = new Browser browser.visit "http://localhost:3003/auth/oauth2", @callback "should return status code 401": (browser)-> assert.equal browser.statusCode, 401 "with invalid credentials": topic: -> browser = new Browser credentials = { scheme: "bearer", token: "PI:PASSWORD:<PASSWORD>END_PI" } browser.visit "http://localhost:3003/auth/oauth2", credentials: credentials, @callback "should return status code 401": (browser)-> assert.equal browser.statusCode, 401 "with valid credentials": topic: -> browser = new Browser credentials = { scheme: "bearer", token: "PI:PASSWORD:<PASSWORD>END_PI" } browser.visit "http://localhost:3003/auth/oauth2", credentials: credentials, @callback "should have the authentication header": (browser)-> assert.equal browser.text("body"), "Bearer 12345" .export(module)
[ { "context": " set_metric_timer: (hmetric) =>\n metric_key = [hmetric.hostname, hmetric.name].join('|')\n @metric_timers[metric_key] ||= setInterval ()", "end": 3872, "score": 0.964415431022644, "start": 3831, "tag": "KEY", "value": "hmetric.hostname, hmetric.name].join('|')" } ]
src/gmond.coffee
seryl/node-gmond
1
net = require 'net' dgram = require 'dgram' Gmetric = require 'gmetric' builder = require 'xmlbuilder' async = require 'async' config = require 'nconf' logger = require './logger' CLI = require './cli' WebServer = require './webserver' ###* * The ganglia gmond class. ### class Gmond constructor: -> @gmetric = new Gmetric() @socket = dgram.createSocket('udp4') @gmond_started = @unix_time() @host_timers = new Object() @metric_timers = new Object() @hosts = new Object() @clusters = new Object() @udp_server = null @xml_server = null @start_udp_service() @start_xml_service() ###* * Starts the udp gmond service. ### start_udp_service: => @socket.on 'message', (msg, rinfo) => # console.log msg # console.log rinfo @add_metric(msg) @socket.on 'error', (err) => console.log err @socket.bind(config.get('gmond_udp_port')) logger.info "Started udp service #{config.get('gmond_udp_port')}" ###* * Stops the udp gmond service. ### stop_udp_service: => @socket.close() ###* * Starts up the xml service. ### start_xml_service: => @xml_server = net.createServer (sock) => sock.end(@generate_xml_snapshot()) @xml_server.listen config.get('gmond_tcp_port') , config.get('listen_address') ###* * Stops the xml service. * @param {Function} (fn) The callback function ### stop_xml_service: (fn) => @xml_server.close(fn) ###* * Stops all external services. * @param {Function} (fn) The callback function ### stop_services: (fn) => @stop_udp_service() @stop_xml_service(fn) ###* * Stop all timers. ### stop_timers: (fn) => htimers = Object.keys(@host_timers) mtimers = Object.keys(@metric_timers) for ht in htimers clearInterval(@host_timers[ht]) delete(@host_timers[ht]) for mt in mtimers clearInterval(@metric_timers[mt]) delete(@metric_timers[mt]) fn() ###* * Returns the current unix timestamp. * @return {Integer} The unix timestamp integer ### unix_time: -> Math.floor(new Date().getTime() / 1000) ###* * Adds a new metric automatically determining the cluster or using defaults. * @param {Object} (metric) The raw metric packet to add ### add_metric: (metric) => msg_type = metric.readInt32BE(0) if (msg_type == 128) || (msg_type == 133) hmet = @gmetric.unpack(metric) @hosts[hmet.hostname] ||= new Object() if msg_type == 128 cluster = @determine_cluster_from_metric(hmet) @hosts[hmet.hostname].cluster ||= cluster @clusters[cluster] ||= new Object() @clusters[cluster].hosts ||= new Object() @clusters[cluster].hosts[hmet.hostname] = true @set_metric_timer(hmet) @set_host_timer(hmet) @merge_metric @hosts[hmet.hostname], hmet ###* * Sets up the host DMAX timer for host cleanup. * @param {Object} (hmetric) The host metric information ### set_host_timer: (hmetric) => @host_timers[hmetric.hostname] ||= setInterval () => try timeout = @hosts[hmetric.hostname].dmax || config.get('dmax') tn = @unix_time() - @hosts[hmetric.hostname]['host_reported'] if tn > timeout cluster = hmetric.cluster delete @hosts[hmetric.hostname] if @clusters[cluster] and @clusters[cluster].hasOwnProperty('hosts') delete @clusters[cluster].hosts[hmetric.hostname] clearInterval(@host_timers[hmetric.hostname]) delete @host_timers[hmetric.hostname] catch e null , config.get('cleanup_threshold') ###* * Sets up the metric DMAX timer for metric cleanup. * @param {Object} (hmetric) The host metric information ### set_metric_timer: (hmetric) => metric_key = [hmetric.hostname, hmetric.name].join('|') @metric_timers[metric_key] ||= setInterval () => try timeout = hmetric.dmax || config.get('dmax') tn = @unix_time() - @hosts[hmetric.hostname]['reported'][hmetric.name] if tn > timeout if @hosts[gmetric.hostname] and @hosts[hmetric.hostname]['metrics'] delete @hosts[hmetric.hostname]['metrics'][hmetric.name] clearInterval(@metric_timers[metric_key]) delete @metric_timers[metric_key] catch e null , config.get('cleanup_threshold') ###* * Merges a metric with the hosts object. * @param {Object} (target) The target hosts object to modify * @param {Object} (hgmetric) The host information to merge ### merge_metric: (target, hmetric) => now = @unix_time() target['host_reported'] = now target['reported'] ||= new Object() target['tags'] ||= new Array() target['ip'] ||= hmetric.hostname target['metrics'] ||= new Object() target['metrics'][hmetric.name] ||= new Object() for key in Object.keys(hmetric) target['metrics'][hmetric.name][key] = hmetric[key] target['reported'][hmetric.name] = now ###* * Returns the cluster of the metric or assumes the default. * @param {Object} (hgmetric) The host information to merge * @return {String} The name of the cluster for the metric ### determine_cluster_from_metric: (hmetric) => cluster = hmetric['cluster'] || config.get('cluster') delete hmetric['cluster'] return cluster ###* * Generates an xml snapshot of the gmond state. * @return {String} The ganglia xml snapshot pretty-printed ### generate_xml_snapshot: => @generate_ganglia_xml().end({ pretty: true, indent: ' ', newline: "\n" }) ###* * Generates the xml builder for a ganglia xml view. * @return {Object} The root node of the full ganglia xml view ### generate_ganglia_xml: => root = @get_gmond_xml_root() for cluster in Object.keys(@clusters) root = @generate_cluster_element(root, cluster) return root ###* * Appends the cluster_xml for a single cluster to the a given node. * @param {Object} (root) The root node to create the cluster element on * @param {String} (cluster) The cluster to generate elements for * @return {Object} The root node with the newly attached cluster ### generate_cluster_element: (root, cluster) => if Object.keys(@clusters[cluster].hosts).length == 0 delete_cluster(cluster) ce = root.ele('CLUSTER') ce.att('NAME', cluster || config.get('cluster')) ce.att('LOCALTIME', @unix_time()) ce.att('OWNER', @clusters[cluster].owner || config.get('owner')) ce.att('LATLONG', @clusters[cluster].latlong || config.get('latlong')) ce.att('URL', @clusters[cluster].url || config.get('url')) if @clusters[cluster] == undefined return root hostlist = Object.keys(@clusters[cluster].hosts) if hostlist.length == 0 return root for h in hostlist ce = @generate_host_element(ce, @hosts[h], h) return root ###* * Generates a host element for a given host and attaches to the parent. * @param {Object} (parent) The parent node to append the host elem to * @param {Object} (hostinfo) The host information for the given host * @param {String} (hostname) The hostname of the current host * @return {Object} The parent node with host elements attached ### generate_host_element: (parent, hostinfo, hostname) -> if hostinfo == undefined return parent he = parent.ele('HOST') he.att('NAME', hostname) he.att('IP', hostinfo['ip']) he.att('TAGS', (hostinfo['tags'] || []).join(',')) he.att('REPORTED', hostinfo['host_reported']) he.att('TN', @unix_time() - hostinfo['host_reported']) he.att('TMAX', hostinfo.tmax || config.get('tmax')) he.att('DMAX', hostinfo.dmax || config.get('dmax')) he.att('LOCATION', hostinfo.location || config.get('latlong')) he.att('GMOND_STARTED', 0) for m in Object.keys(hostinfo.metrics) he = @generate_metric_element(he, hostinfo, hostinfo.metrics[m]) return parent ###* * Generates the metric element and attaches to the parent. * @param {Object} (parent) The parent node to append the metric elem to * @param {Object} (host) The host information for the given metric * @param {Object} (metric) The metric to generate metric xml from * @return {Object} The parent node with metric elements attached ### generate_metric_element: (parent, hostinfo, metric) -> me = parent.ele('METRIC') me.att('NAME', metric.name) me.att('VAL', metric.value || 0) me.att('TYPE', metric.type) me.att('UNITS', metric.units) me.att('TN', @unix_time() - hostinfo['reported'][metric.name]) me.att('TMAX', metric.tmax || config.get('tmax')) me.att('DMAX', metric.dmax || config.get('dmax')) me.att('SLOPE', metric.slope) me = @generate_extra_elements(me, metric) return parent ###* * Generates the extra elems for a metric and attaches to the parent. * @param {Object} (parent) The parent node to append the extra data to * @param {Object} (metric) The metric to generate extra_elements from * @return {Object} The parent node with extra elements attached ### generate_extra_elements: (parent, metric) -> extras = @gmetric.extra_elements(metric) if extras.length < 1 return parent ed = parent.ele('EXTRA_DATA') for extra in extras ee = ed.ele('EXTRA_ELEMENT') ee.att('NAME', extra.toUpperCase()) ee.att('VAL', metric[extra]) return parent ###* * Returns the gmond_xml root node to build upon. * @return {Object} The root gmond xmlbuilder ### get_gmond_xml_root: -> root = builder.create 'GANGLIA_XML' , { version: '1.0', encoding: 'ISO-8859-1' , standalone: 'yes' }, ext: """[ <!ELEMENT GANGLIA_XML (GRID|CLUSTER|HOST)*> <!ATTLIST GANGLIA_XML VERSION CDATA #REQUIRED> <!ATTLIST GANGLIA_XML SOURCE CDATA #REQUIRED> <!ELEMENT GRID (CLUSTER | GRID | HOSTS | METRICS)*> <!ATTLIST GRID NAME CDATA #REQUIRED> <!ATTLIST GRID AUTHORITY CDATA #REQUIRED> <!ATTLIST GRID LOCALTIME CDATA #IMPLIED> <!ELEMENT CLUSTER (HOST | HOSTS | METRICS)*> <!ATTLIST CLUSTER NAME CDATA #REQUIRED> <!ATTLIST CLUSTER OWNER CDATA #IMPLIED> <!ATTLIST CLUSTER LATLONG CDATA #IMPLIED> <!ATTLIST CLUSTER URL CDATA #IMPLIED> <!ATTLIST CLUSTER LOCALTIME CDATA #REQUIRED> <!ELEMENT HOST (METRIC)*> <!ATTLIST HOST NAME CDATA #REQUIRED> <!ATTLIST HOST IP CDATA #REQUIRED> <!ATTLIST HOST LOCATION CDATA #IMPLIED> <!ATTLIST HOST TAGS CDATA #IMPLIED> <!ATTLIST HOST REPORTED CDATA #REQUIRED> <!ATTLIST HOST TN CDATA #IMPLIED> <!ATTLIST HOST TMAX CDATA #IMPLIED> <!ATTLIST HOST DMAX CDATA #IMPLIED> <!ATTLIST HOST GMOND_STARTED CDATA #IMPLIED> <!ELEMENT METRIC (EXTRA_DATA*)> <!ATTLIST METRIC NAME CDATA #REQUIRED> <!ATTLIST METRIC VAL CDATA #REQUIRED> <!ATTLIST METRIC TYPE (string | int8 | uint8 | int16 | uint16 | int32 | uint32 | int64 | uint64 | float | double | timestamp) #REQUIRED> <!ATTLIST METRIC UNITS CDATA #IMPLIED> <!ATTLIST METRIC TN CDATA #IMPLIED> <!ATTLIST METRIC TMAX CDATA #IMPLIED> <!ATTLIST METRIC DMAX CDATA #IMPLIED> <!ATTLIST METRIC SLOPE (zero | positive | negative | both | unspecified) #IMPLIED> <!ATTLIST METRIC SOURCE (gmond) 'gmond'> <!ELEMENT EXTRA_DATA (EXTRA_ELEMENT*)> <!ELEMENT EXTRA_ELEMENT EMPTY> <!ATTLIST EXTRA_ELEMENT NAME CDATA #REQUIRED> <!ATTLIST EXTRA_ELEMENT VAL CDATA #REQUIRED> <!ELEMENT HOSTS EMPTY> <!ATTLIST HOSTS UP CDATA #REQUIRED> <!ATTLIST HOSTS DOWN CDATA #REQUIRED> <!ATTLIST HOSTS SOURCE (gmond | gmetad) #REQUIRED> <!ELEMENT METRICS (EXTRA_DATA*)> <!ATTLIST METRICS NAME CDATA #REQUIRED> <!ATTLIST METRICS SUM CDATA #REQUIRED> <!ATTLIST METRICS NUM CDATA #REQUIRED> <!ATTLIST METRICS TYPE (string | int8 | uint8 | int16 | uint16 | int32 | uint32 | int64| uint64 | float | double | timestamp) #REQUIRED> <!ATTLIST METRICS UNITS CDATA #IMPLIED> <!ATTLIST METRICS SLOPE (zero | positive | negative | both | unspecified) #IMPLIED> <!ATTLIST METRICS SOURCE (gmond) 'gmond'> ]""" root.att('VERSION', '3.5.0') root.att('SOURCE', 'gmond') return root module.exports = Gmond
10747
net = require 'net' dgram = require 'dgram' Gmetric = require 'gmetric' builder = require 'xmlbuilder' async = require 'async' config = require 'nconf' logger = require './logger' CLI = require './cli' WebServer = require './webserver' ###* * The ganglia gmond class. ### class Gmond constructor: -> @gmetric = new Gmetric() @socket = dgram.createSocket('udp4') @gmond_started = @unix_time() @host_timers = new Object() @metric_timers = new Object() @hosts = new Object() @clusters = new Object() @udp_server = null @xml_server = null @start_udp_service() @start_xml_service() ###* * Starts the udp gmond service. ### start_udp_service: => @socket.on 'message', (msg, rinfo) => # console.log msg # console.log rinfo @add_metric(msg) @socket.on 'error', (err) => console.log err @socket.bind(config.get('gmond_udp_port')) logger.info "Started udp service #{config.get('gmond_udp_port')}" ###* * Stops the udp gmond service. ### stop_udp_service: => @socket.close() ###* * Starts up the xml service. ### start_xml_service: => @xml_server = net.createServer (sock) => sock.end(@generate_xml_snapshot()) @xml_server.listen config.get('gmond_tcp_port') , config.get('listen_address') ###* * Stops the xml service. * @param {Function} (fn) The callback function ### stop_xml_service: (fn) => @xml_server.close(fn) ###* * Stops all external services. * @param {Function} (fn) The callback function ### stop_services: (fn) => @stop_udp_service() @stop_xml_service(fn) ###* * Stop all timers. ### stop_timers: (fn) => htimers = Object.keys(@host_timers) mtimers = Object.keys(@metric_timers) for ht in htimers clearInterval(@host_timers[ht]) delete(@host_timers[ht]) for mt in mtimers clearInterval(@metric_timers[mt]) delete(@metric_timers[mt]) fn() ###* * Returns the current unix timestamp. * @return {Integer} The unix timestamp integer ### unix_time: -> Math.floor(new Date().getTime() / 1000) ###* * Adds a new metric automatically determining the cluster or using defaults. * @param {Object} (metric) The raw metric packet to add ### add_metric: (metric) => msg_type = metric.readInt32BE(0) if (msg_type == 128) || (msg_type == 133) hmet = @gmetric.unpack(metric) @hosts[hmet.hostname] ||= new Object() if msg_type == 128 cluster = @determine_cluster_from_metric(hmet) @hosts[hmet.hostname].cluster ||= cluster @clusters[cluster] ||= new Object() @clusters[cluster].hosts ||= new Object() @clusters[cluster].hosts[hmet.hostname] = true @set_metric_timer(hmet) @set_host_timer(hmet) @merge_metric @hosts[hmet.hostname], hmet ###* * Sets up the host DMAX timer for host cleanup. * @param {Object} (hmetric) The host metric information ### set_host_timer: (hmetric) => @host_timers[hmetric.hostname] ||= setInterval () => try timeout = @hosts[hmetric.hostname].dmax || config.get('dmax') tn = @unix_time() - @hosts[hmetric.hostname]['host_reported'] if tn > timeout cluster = hmetric.cluster delete @hosts[hmetric.hostname] if @clusters[cluster] and @clusters[cluster].hasOwnProperty('hosts') delete @clusters[cluster].hosts[hmetric.hostname] clearInterval(@host_timers[hmetric.hostname]) delete @host_timers[hmetric.hostname] catch e null , config.get('cleanup_threshold') ###* * Sets up the metric DMAX timer for metric cleanup. * @param {Object} (hmetric) The host metric information ### set_metric_timer: (hmetric) => metric_key = [<KEY> @metric_timers[metric_key] ||= setInterval () => try timeout = hmetric.dmax || config.get('dmax') tn = @unix_time() - @hosts[hmetric.hostname]['reported'][hmetric.name] if tn > timeout if @hosts[gmetric.hostname] and @hosts[hmetric.hostname]['metrics'] delete @hosts[hmetric.hostname]['metrics'][hmetric.name] clearInterval(@metric_timers[metric_key]) delete @metric_timers[metric_key] catch e null , config.get('cleanup_threshold') ###* * Merges a metric with the hosts object. * @param {Object} (target) The target hosts object to modify * @param {Object} (hgmetric) The host information to merge ### merge_metric: (target, hmetric) => now = @unix_time() target['host_reported'] = now target['reported'] ||= new Object() target['tags'] ||= new Array() target['ip'] ||= hmetric.hostname target['metrics'] ||= new Object() target['metrics'][hmetric.name] ||= new Object() for key in Object.keys(hmetric) target['metrics'][hmetric.name][key] = hmetric[key] target['reported'][hmetric.name] = now ###* * Returns the cluster of the metric or assumes the default. * @param {Object} (hgmetric) The host information to merge * @return {String} The name of the cluster for the metric ### determine_cluster_from_metric: (hmetric) => cluster = hmetric['cluster'] || config.get('cluster') delete hmetric['cluster'] return cluster ###* * Generates an xml snapshot of the gmond state. * @return {String} The ganglia xml snapshot pretty-printed ### generate_xml_snapshot: => @generate_ganglia_xml().end({ pretty: true, indent: ' ', newline: "\n" }) ###* * Generates the xml builder for a ganglia xml view. * @return {Object} The root node of the full ganglia xml view ### generate_ganglia_xml: => root = @get_gmond_xml_root() for cluster in Object.keys(@clusters) root = @generate_cluster_element(root, cluster) return root ###* * Appends the cluster_xml for a single cluster to the a given node. * @param {Object} (root) The root node to create the cluster element on * @param {String} (cluster) The cluster to generate elements for * @return {Object} The root node with the newly attached cluster ### generate_cluster_element: (root, cluster) => if Object.keys(@clusters[cluster].hosts).length == 0 delete_cluster(cluster) ce = root.ele('CLUSTER') ce.att('NAME', cluster || config.get('cluster')) ce.att('LOCALTIME', @unix_time()) ce.att('OWNER', @clusters[cluster].owner || config.get('owner')) ce.att('LATLONG', @clusters[cluster].latlong || config.get('latlong')) ce.att('URL', @clusters[cluster].url || config.get('url')) if @clusters[cluster] == undefined return root hostlist = Object.keys(@clusters[cluster].hosts) if hostlist.length == 0 return root for h in hostlist ce = @generate_host_element(ce, @hosts[h], h) return root ###* * Generates a host element for a given host and attaches to the parent. * @param {Object} (parent) The parent node to append the host elem to * @param {Object} (hostinfo) The host information for the given host * @param {String} (hostname) The hostname of the current host * @return {Object} The parent node with host elements attached ### generate_host_element: (parent, hostinfo, hostname) -> if hostinfo == undefined return parent he = parent.ele('HOST') he.att('NAME', hostname) he.att('IP', hostinfo['ip']) he.att('TAGS', (hostinfo['tags'] || []).join(',')) he.att('REPORTED', hostinfo['host_reported']) he.att('TN', @unix_time() - hostinfo['host_reported']) he.att('TMAX', hostinfo.tmax || config.get('tmax')) he.att('DMAX', hostinfo.dmax || config.get('dmax')) he.att('LOCATION', hostinfo.location || config.get('latlong')) he.att('GMOND_STARTED', 0) for m in Object.keys(hostinfo.metrics) he = @generate_metric_element(he, hostinfo, hostinfo.metrics[m]) return parent ###* * Generates the metric element and attaches to the parent. * @param {Object} (parent) The parent node to append the metric elem to * @param {Object} (host) The host information for the given metric * @param {Object} (metric) The metric to generate metric xml from * @return {Object} The parent node with metric elements attached ### generate_metric_element: (parent, hostinfo, metric) -> me = parent.ele('METRIC') me.att('NAME', metric.name) me.att('VAL', metric.value || 0) me.att('TYPE', metric.type) me.att('UNITS', metric.units) me.att('TN', @unix_time() - hostinfo['reported'][metric.name]) me.att('TMAX', metric.tmax || config.get('tmax')) me.att('DMAX', metric.dmax || config.get('dmax')) me.att('SLOPE', metric.slope) me = @generate_extra_elements(me, metric) return parent ###* * Generates the extra elems for a metric and attaches to the parent. * @param {Object} (parent) The parent node to append the extra data to * @param {Object} (metric) The metric to generate extra_elements from * @return {Object} The parent node with extra elements attached ### generate_extra_elements: (parent, metric) -> extras = @gmetric.extra_elements(metric) if extras.length < 1 return parent ed = parent.ele('EXTRA_DATA') for extra in extras ee = ed.ele('EXTRA_ELEMENT') ee.att('NAME', extra.toUpperCase()) ee.att('VAL', metric[extra]) return parent ###* * Returns the gmond_xml root node to build upon. * @return {Object} The root gmond xmlbuilder ### get_gmond_xml_root: -> root = builder.create 'GANGLIA_XML' , { version: '1.0', encoding: 'ISO-8859-1' , standalone: 'yes' }, ext: """[ <!ELEMENT GANGLIA_XML (GRID|CLUSTER|HOST)*> <!ATTLIST GANGLIA_XML VERSION CDATA #REQUIRED> <!ATTLIST GANGLIA_XML SOURCE CDATA #REQUIRED> <!ELEMENT GRID (CLUSTER | GRID | HOSTS | METRICS)*> <!ATTLIST GRID NAME CDATA #REQUIRED> <!ATTLIST GRID AUTHORITY CDATA #REQUIRED> <!ATTLIST GRID LOCALTIME CDATA #IMPLIED> <!ELEMENT CLUSTER (HOST | HOSTS | METRICS)*> <!ATTLIST CLUSTER NAME CDATA #REQUIRED> <!ATTLIST CLUSTER OWNER CDATA #IMPLIED> <!ATTLIST CLUSTER LATLONG CDATA #IMPLIED> <!ATTLIST CLUSTER URL CDATA #IMPLIED> <!ATTLIST CLUSTER LOCALTIME CDATA #REQUIRED> <!ELEMENT HOST (METRIC)*> <!ATTLIST HOST NAME CDATA #REQUIRED> <!ATTLIST HOST IP CDATA #REQUIRED> <!ATTLIST HOST LOCATION CDATA #IMPLIED> <!ATTLIST HOST TAGS CDATA #IMPLIED> <!ATTLIST HOST REPORTED CDATA #REQUIRED> <!ATTLIST HOST TN CDATA #IMPLIED> <!ATTLIST HOST TMAX CDATA #IMPLIED> <!ATTLIST HOST DMAX CDATA #IMPLIED> <!ATTLIST HOST GMOND_STARTED CDATA #IMPLIED> <!ELEMENT METRIC (EXTRA_DATA*)> <!ATTLIST METRIC NAME CDATA #REQUIRED> <!ATTLIST METRIC VAL CDATA #REQUIRED> <!ATTLIST METRIC TYPE (string | int8 | uint8 | int16 | uint16 | int32 | uint32 | int64 | uint64 | float | double | timestamp) #REQUIRED> <!ATTLIST METRIC UNITS CDATA #IMPLIED> <!ATTLIST METRIC TN CDATA #IMPLIED> <!ATTLIST METRIC TMAX CDATA #IMPLIED> <!ATTLIST METRIC DMAX CDATA #IMPLIED> <!ATTLIST METRIC SLOPE (zero | positive | negative | both | unspecified) #IMPLIED> <!ATTLIST METRIC SOURCE (gmond) 'gmond'> <!ELEMENT EXTRA_DATA (EXTRA_ELEMENT*)> <!ELEMENT EXTRA_ELEMENT EMPTY> <!ATTLIST EXTRA_ELEMENT NAME CDATA #REQUIRED> <!ATTLIST EXTRA_ELEMENT VAL CDATA #REQUIRED> <!ELEMENT HOSTS EMPTY> <!ATTLIST HOSTS UP CDATA #REQUIRED> <!ATTLIST HOSTS DOWN CDATA #REQUIRED> <!ATTLIST HOSTS SOURCE (gmond | gmetad) #REQUIRED> <!ELEMENT METRICS (EXTRA_DATA*)> <!ATTLIST METRICS NAME CDATA #REQUIRED> <!ATTLIST METRICS SUM CDATA #REQUIRED> <!ATTLIST METRICS NUM CDATA #REQUIRED> <!ATTLIST METRICS TYPE (string | int8 | uint8 | int16 | uint16 | int32 | uint32 | int64| uint64 | float | double | timestamp) #REQUIRED> <!ATTLIST METRICS UNITS CDATA #IMPLIED> <!ATTLIST METRICS SLOPE (zero | positive | negative | both | unspecified) #IMPLIED> <!ATTLIST METRICS SOURCE (gmond) 'gmond'> ]""" root.att('VERSION', '3.5.0') root.att('SOURCE', 'gmond') return root module.exports = Gmond
true
net = require 'net' dgram = require 'dgram' Gmetric = require 'gmetric' builder = require 'xmlbuilder' async = require 'async' config = require 'nconf' logger = require './logger' CLI = require './cli' WebServer = require './webserver' ###* * The ganglia gmond class. ### class Gmond constructor: -> @gmetric = new Gmetric() @socket = dgram.createSocket('udp4') @gmond_started = @unix_time() @host_timers = new Object() @metric_timers = new Object() @hosts = new Object() @clusters = new Object() @udp_server = null @xml_server = null @start_udp_service() @start_xml_service() ###* * Starts the udp gmond service. ### start_udp_service: => @socket.on 'message', (msg, rinfo) => # console.log msg # console.log rinfo @add_metric(msg) @socket.on 'error', (err) => console.log err @socket.bind(config.get('gmond_udp_port')) logger.info "Started udp service #{config.get('gmond_udp_port')}" ###* * Stops the udp gmond service. ### stop_udp_service: => @socket.close() ###* * Starts up the xml service. ### start_xml_service: => @xml_server = net.createServer (sock) => sock.end(@generate_xml_snapshot()) @xml_server.listen config.get('gmond_tcp_port') , config.get('listen_address') ###* * Stops the xml service. * @param {Function} (fn) The callback function ### stop_xml_service: (fn) => @xml_server.close(fn) ###* * Stops all external services. * @param {Function} (fn) The callback function ### stop_services: (fn) => @stop_udp_service() @stop_xml_service(fn) ###* * Stop all timers. ### stop_timers: (fn) => htimers = Object.keys(@host_timers) mtimers = Object.keys(@metric_timers) for ht in htimers clearInterval(@host_timers[ht]) delete(@host_timers[ht]) for mt in mtimers clearInterval(@metric_timers[mt]) delete(@metric_timers[mt]) fn() ###* * Returns the current unix timestamp. * @return {Integer} The unix timestamp integer ### unix_time: -> Math.floor(new Date().getTime() / 1000) ###* * Adds a new metric automatically determining the cluster or using defaults. * @param {Object} (metric) The raw metric packet to add ### add_metric: (metric) => msg_type = metric.readInt32BE(0) if (msg_type == 128) || (msg_type == 133) hmet = @gmetric.unpack(metric) @hosts[hmet.hostname] ||= new Object() if msg_type == 128 cluster = @determine_cluster_from_metric(hmet) @hosts[hmet.hostname].cluster ||= cluster @clusters[cluster] ||= new Object() @clusters[cluster].hosts ||= new Object() @clusters[cluster].hosts[hmet.hostname] = true @set_metric_timer(hmet) @set_host_timer(hmet) @merge_metric @hosts[hmet.hostname], hmet ###* * Sets up the host DMAX timer for host cleanup. * @param {Object} (hmetric) The host metric information ### set_host_timer: (hmetric) => @host_timers[hmetric.hostname] ||= setInterval () => try timeout = @hosts[hmetric.hostname].dmax || config.get('dmax') tn = @unix_time() - @hosts[hmetric.hostname]['host_reported'] if tn > timeout cluster = hmetric.cluster delete @hosts[hmetric.hostname] if @clusters[cluster] and @clusters[cluster].hasOwnProperty('hosts') delete @clusters[cluster].hosts[hmetric.hostname] clearInterval(@host_timers[hmetric.hostname]) delete @host_timers[hmetric.hostname] catch e null , config.get('cleanup_threshold') ###* * Sets up the metric DMAX timer for metric cleanup. * @param {Object} (hmetric) The host metric information ### set_metric_timer: (hmetric) => metric_key = [PI:KEY:<KEY>END_PI @metric_timers[metric_key] ||= setInterval () => try timeout = hmetric.dmax || config.get('dmax') tn = @unix_time() - @hosts[hmetric.hostname]['reported'][hmetric.name] if tn > timeout if @hosts[gmetric.hostname] and @hosts[hmetric.hostname]['metrics'] delete @hosts[hmetric.hostname]['metrics'][hmetric.name] clearInterval(@metric_timers[metric_key]) delete @metric_timers[metric_key] catch e null , config.get('cleanup_threshold') ###* * Merges a metric with the hosts object. * @param {Object} (target) The target hosts object to modify * @param {Object} (hgmetric) The host information to merge ### merge_metric: (target, hmetric) => now = @unix_time() target['host_reported'] = now target['reported'] ||= new Object() target['tags'] ||= new Array() target['ip'] ||= hmetric.hostname target['metrics'] ||= new Object() target['metrics'][hmetric.name] ||= new Object() for key in Object.keys(hmetric) target['metrics'][hmetric.name][key] = hmetric[key] target['reported'][hmetric.name] = now ###* * Returns the cluster of the metric or assumes the default. * @param {Object} (hgmetric) The host information to merge * @return {String} The name of the cluster for the metric ### determine_cluster_from_metric: (hmetric) => cluster = hmetric['cluster'] || config.get('cluster') delete hmetric['cluster'] return cluster ###* * Generates an xml snapshot of the gmond state. * @return {String} The ganglia xml snapshot pretty-printed ### generate_xml_snapshot: => @generate_ganglia_xml().end({ pretty: true, indent: ' ', newline: "\n" }) ###* * Generates the xml builder for a ganglia xml view. * @return {Object} The root node of the full ganglia xml view ### generate_ganglia_xml: => root = @get_gmond_xml_root() for cluster in Object.keys(@clusters) root = @generate_cluster_element(root, cluster) return root ###* * Appends the cluster_xml for a single cluster to the a given node. * @param {Object} (root) The root node to create the cluster element on * @param {String} (cluster) The cluster to generate elements for * @return {Object} The root node with the newly attached cluster ### generate_cluster_element: (root, cluster) => if Object.keys(@clusters[cluster].hosts).length == 0 delete_cluster(cluster) ce = root.ele('CLUSTER') ce.att('NAME', cluster || config.get('cluster')) ce.att('LOCALTIME', @unix_time()) ce.att('OWNER', @clusters[cluster].owner || config.get('owner')) ce.att('LATLONG', @clusters[cluster].latlong || config.get('latlong')) ce.att('URL', @clusters[cluster].url || config.get('url')) if @clusters[cluster] == undefined return root hostlist = Object.keys(@clusters[cluster].hosts) if hostlist.length == 0 return root for h in hostlist ce = @generate_host_element(ce, @hosts[h], h) return root ###* * Generates a host element for a given host and attaches to the parent. * @param {Object} (parent) The parent node to append the host elem to * @param {Object} (hostinfo) The host information for the given host * @param {String} (hostname) The hostname of the current host * @return {Object} The parent node with host elements attached ### generate_host_element: (parent, hostinfo, hostname) -> if hostinfo == undefined return parent he = parent.ele('HOST') he.att('NAME', hostname) he.att('IP', hostinfo['ip']) he.att('TAGS', (hostinfo['tags'] || []).join(',')) he.att('REPORTED', hostinfo['host_reported']) he.att('TN', @unix_time() - hostinfo['host_reported']) he.att('TMAX', hostinfo.tmax || config.get('tmax')) he.att('DMAX', hostinfo.dmax || config.get('dmax')) he.att('LOCATION', hostinfo.location || config.get('latlong')) he.att('GMOND_STARTED', 0) for m in Object.keys(hostinfo.metrics) he = @generate_metric_element(he, hostinfo, hostinfo.metrics[m]) return parent ###* * Generates the metric element and attaches to the parent. * @param {Object} (parent) The parent node to append the metric elem to * @param {Object} (host) The host information for the given metric * @param {Object} (metric) The metric to generate metric xml from * @return {Object} The parent node with metric elements attached ### generate_metric_element: (parent, hostinfo, metric) -> me = parent.ele('METRIC') me.att('NAME', metric.name) me.att('VAL', metric.value || 0) me.att('TYPE', metric.type) me.att('UNITS', metric.units) me.att('TN', @unix_time() - hostinfo['reported'][metric.name]) me.att('TMAX', metric.tmax || config.get('tmax')) me.att('DMAX', metric.dmax || config.get('dmax')) me.att('SLOPE', metric.slope) me = @generate_extra_elements(me, metric) return parent ###* * Generates the extra elems for a metric and attaches to the parent. * @param {Object} (parent) The parent node to append the extra data to * @param {Object} (metric) The metric to generate extra_elements from * @return {Object} The parent node with extra elements attached ### generate_extra_elements: (parent, metric) -> extras = @gmetric.extra_elements(metric) if extras.length < 1 return parent ed = parent.ele('EXTRA_DATA') for extra in extras ee = ed.ele('EXTRA_ELEMENT') ee.att('NAME', extra.toUpperCase()) ee.att('VAL', metric[extra]) return parent ###* * Returns the gmond_xml root node to build upon. * @return {Object} The root gmond xmlbuilder ### get_gmond_xml_root: -> root = builder.create 'GANGLIA_XML' , { version: '1.0', encoding: 'ISO-8859-1' , standalone: 'yes' }, ext: """[ <!ELEMENT GANGLIA_XML (GRID|CLUSTER|HOST)*> <!ATTLIST GANGLIA_XML VERSION CDATA #REQUIRED> <!ATTLIST GANGLIA_XML SOURCE CDATA #REQUIRED> <!ELEMENT GRID (CLUSTER | GRID | HOSTS | METRICS)*> <!ATTLIST GRID NAME CDATA #REQUIRED> <!ATTLIST GRID AUTHORITY CDATA #REQUIRED> <!ATTLIST GRID LOCALTIME CDATA #IMPLIED> <!ELEMENT CLUSTER (HOST | HOSTS | METRICS)*> <!ATTLIST CLUSTER NAME CDATA #REQUIRED> <!ATTLIST CLUSTER OWNER CDATA #IMPLIED> <!ATTLIST CLUSTER LATLONG CDATA #IMPLIED> <!ATTLIST CLUSTER URL CDATA #IMPLIED> <!ATTLIST CLUSTER LOCALTIME CDATA #REQUIRED> <!ELEMENT HOST (METRIC)*> <!ATTLIST HOST NAME CDATA #REQUIRED> <!ATTLIST HOST IP CDATA #REQUIRED> <!ATTLIST HOST LOCATION CDATA #IMPLIED> <!ATTLIST HOST TAGS CDATA #IMPLIED> <!ATTLIST HOST REPORTED CDATA #REQUIRED> <!ATTLIST HOST TN CDATA #IMPLIED> <!ATTLIST HOST TMAX CDATA #IMPLIED> <!ATTLIST HOST DMAX CDATA #IMPLIED> <!ATTLIST HOST GMOND_STARTED CDATA #IMPLIED> <!ELEMENT METRIC (EXTRA_DATA*)> <!ATTLIST METRIC NAME CDATA #REQUIRED> <!ATTLIST METRIC VAL CDATA #REQUIRED> <!ATTLIST METRIC TYPE (string | int8 | uint8 | int16 | uint16 | int32 | uint32 | int64 | uint64 | float | double | timestamp) #REQUIRED> <!ATTLIST METRIC UNITS CDATA #IMPLIED> <!ATTLIST METRIC TN CDATA #IMPLIED> <!ATTLIST METRIC TMAX CDATA #IMPLIED> <!ATTLIST METRIC DMAX CDATA #IMPLIED> <!ATTLIST METRIC SLOPE (zero | positive | negative | both | unspecified) #IMPLIED> <!ATTLIST METRIC SOURCE (gmond) 'gmond'> <!ELEMENT EXTRA_DATA (EXTRA_ELEMENT*)> <!ELEMENT EXTRA_ELEMENT EMPTY> <!ATTLIST EXTRA_ELEMENT NAME CDATA #REQUIRED> <!ATTLIST EXTRA_ELEMENT VAL CDATA #REQUIRED> <!ELEMENT HOSTS EMPTY> <!ATTLIST HOSTS UP CDATA #REQUIRED> <!ATTLIST HOSTS DOWN CDATA #REQUIRED> <!ATTLIST HOSTS SOURCE (gmond | gmetad) #REQUIRED> <!ELEMENT METRICS (EXTRA_DATA*)> <!ATTLIST METRICS NAME CDATA #REQUIRED> <!ATTLIST METRICS SUM CDATA #REQUIRED> <!ATTLIST METRICS NUM CDATA #REQUIRED> <!ATTLIST METRICS TYPE (string | int8 | uint8 | int16 | uint16 | int32 | uint32 | int64| uint64 | float | double | timestamp) #REQUIRED> <!ATTLIST METRICS UNITS CDATA #IMPLIED> <!ATTLIST METRICS SLOPE (zero | positive | negative | both | unspecified) #IMPLIED> <!ATTLIST METRICS SOURCE (gmond) 'gmond'> ]""" root.att('VERSION', '3.5.0') root.att('SOURCE', 'gmond') return root module.exports = Gmond
[ { "context": "'''\nwatchOS : Apps\n\n@auther Jungho song (threeword.com)\n@since 2016.11.23\n'''\nclass expor", "end": 39, "score": 0.9998630285263062, "start": 28, "tag": "NAME", "value": "Jungho song" } ]
modules/watchos-kit-apps.coffee
framer-modules/watchos
2
''' watchOS : Apps @auther Jungho song (threeword.com) @since 2016.11.23 ''' class exports.Apps extends Layer clockSize = 84 clockScale = 1 appSize = clockSize - 10 appScale = 1 # Constructor constructor: (options = {}) -> options.name ?= "Apps" options.image ?= "images/apps.jpg" super options clockScale = clockSize / Math.sqrt( Math.pow(@width, 2) + Math.pow(@height, 2) ) appScale = appSize / Math.sqrt( Math.pow(@width, 2) + Math.pow(@height, 2) ) @_clockfaces = options.clockfaces @_appInfo = options.appInfo @_app = @_appInfo.app @aniOptionsShow = time: .3, curve: "ease-out" @aniOptionsDismiss = time: .25, curve: "ease-in" @clockface = new App name: "clockfaces" point: Align.center size: clockSize parent: @ @clockface.onClick => @dismiss @_clockfaces # Exist app if @_app @app = new App name: "app" x:Align.center(90), y: Align.center size: appSize html: "APP" style: fontSize: "20px", fontWeight: "600" lineHeight: "#{appSize}px" textAlign: "center" borderStyle: "dashed" borderRadius: appSize/2, borderWidth: 1, borderColor: "white" parent: @ if @_appInfo.icon @app.props = html: "" borderWidth: 0 image: @_appInfo.icon @app.onClick => @dismiss @_app @scale = 1 / clockScale @sendToBack() init: -> @props = visible: true, scale: 1, point: Align.center show: (app) -> return if @isAnimating # ClockFace if app is @_clockfaces @props = scale: 1 / clockScale, point: Align.center @animate scale: 1, options: @aniOptionsShow @clockface.addContent @_clockfaces, clockScale @_clockfaces.timeStop() @visible = true @bringToFront() @clockface.show() @_clockfaces.animateStop() @_clockfaces.animate scale: clockScale * 2/3 # App (Kakaostock) else if app is @_app @props = scale: 1 / appScale, x: Align.center(-90 / appScale), y: Align.center @animate scale: 1, x: Align.center, y: Align.center, options: @aniOptionsShow @app.addContent @_app, appScale @visible = true @bringToFront() @app.show() @_app.animateStop() @_app.animate scale: appScale * 2/3 dismiss: (app) -> return if @isAnimating # ClockFace if app is @_clockfaces return if @_clockfaces.isAnimating @animate scale: 1 / clockScale, options: @aniOptionsDismiss @clockface.dismiss() @_clockfaces.visible = true @_clockfaces.animate scale: clockScale, options: { time: .8 } Utils.delay .9, => @clockface.removeContent @_clockfaces @_clockfaces.timeStart() @visible = false # App (Kakaostock) else if app is @_app return if @_app.isAnimating # if _.isEmpty(@app.content.children) @app.addContent @_app, appScale @animate scale: 1 / appScale, x: Align.center(-90 / appScale), y: Align.center, options: @aniOptionsDismiss @app.dismiss() @_app.visible = true @_app.animate scale: appScale, options: { time: .8 } Utils.delay .9, => @app.removeContent @_app @visible = false # App class App extends Layer # Constructor constructor: (options = {}) -> options.backgroundColor ?= "" options.clip ?= true super options @iconSize = options.size @startPoint = @point @bg = new Layer name: ".bg" point: Align.center size: @iconSize backgroundColor: "black" borderRadius: 42 opacity: 0 parent: @ @content = new Layer name: "content" point: Align.center size: 0 backgroundColor: "black" borderRadius: 42 clip: true parent: @ @content.on "change:size", => @content.center() return unless app = @content.children[0] app.props = x: (@content.width - app.width) / 2, y: (@content.height - app.height) / 2 @aniOptionsShow = time: .3, curve: "ease-out" @aniOptionsDismiss = time: .25, curve: "ease-in" init: -> @bg.opacity = 0 @content.size = 0 show: -> return if @bg.isAnimating @bg.opacity = 1 @content.size = @iconSize @bg.animate opacity: 0, options: @aniOptionsShow @content.animate width: 0, height: 0, options: @aniOptionsShow dismiss: -> return if @bg.isAnimating @bg.animate opacity: 1, options: @aniOptionsDismiss @content.animate width: @iconSize, height: @iconSize, options: @aniOptionsDismiss addContent: (layer, scale) -> if layer @content.addChild layer layer.props = point: Align.center, scale: scale, clip: true removeContent: (layer) -> if layer @content.removeChild layer layer.props = point: 0, scale: 1, clip: false layer.bringToFront() @init()
122384
''' watchOS : Apps @auther <NAME> (threeword.com) @since 2016.11.23 ''' class exports.Apps extends Layer clockSize = 84 clockScale = 1 appSize = clockSize - 10 appScale = 1 # Constructor constructor: (options = {}) -> options.name ?= "Apps" options.image ?= "images/apps.jpg" super options clockScale = clockSize / Math.sqrt( Math.pow(@width, 2) + Math.pow(@height, 2) ) appScale = appSize / Math.sqrt( Math.pow(@width, 2) + Math.pow(@height, 2) ) @_clockfaces = options.clockfaces @_appInfo = options.appInfo @_app = @_appInfo.app @aniOptionsShow = time: .3, curve: "ease-out" @aniOptionsDismiss = time: .25, curve: "ease-in" @clockface = new App name: "clockfaces" point: Align.center size: clockSize parent: @ @clockface.onClick => @dismiss @_clockfaces # Exist app if @_app @app = new App name: "app" x:Align.center(90), y: Align.center size: appSize html: "APP" style: fontSize: "20px", fontWeight: "600" lineHeight: "#{appSize}px" textAlign: "center" borderStyle: "dashed" borderRadius: appSize/2, borderWidth: 1, borderColor: "white" parent: @ if @_appInfo.icon @app.props = html: "" borderWidth: 0 image: @_appInfo.icon @app.onClick => @dismiss @_app @scale = 1 / clockScale @sendToBack() init: -> @props = visible: true, scale: 1, point: Align.center show: (app) -> return if @isAnimating # ClockFace if app is @_clockfaces @props = scale: 1 / clockScale, point: Align.center @animate scale: 1, options: @aniOptionsShow @clockface.addContent @_clockfaces, clockScale @_clockfaces.timeStop() @visible = true @bringToFront() @clockface.show() @_clockfaces.animateStop() @_clockfaces.animate scale: clockScale * 2/3 # App (Kakaostock) else if app is @_app @props = scale: 1 / appScale, x: Align.center(-90 / appScale), y: Align.center @animate scale: 1, x: Align.center, y: Align.center, options: @aniOptionsShow @app.addContent @_app, appScale @visible = true @bringToFront() @app.show() @_app.animateStop() @_app.animate scale: appScale * 2/3 dismiss: (app) -> return if @isAnimating # ClockFace if app is @_clockfaces return if @_clockfaces.isAnimating @animate scale: 1 / clockScale, options: @aniOptionsDismiss @clockface.dismiss() @_clockfaces.visible = true @_clockfaces.animate scale: clockScale, options: { time: .8 } Utils.delay .9, => @clockface.removeContent @_clockfaces @_clockfaces.timeStart() @visible = false # App (Kakaostock) else if app is @_app return if @_app.isAnimating # if _.isEmpty(@app.content.children) @app.addContent @_app, appScale @animate scale: 1 / appScale, x: Align.center(-90 / appScale), y: Align.center, options: @aniOptionsDismiss @app.dismiss() @_app.visible = true @_app.animate scale: appScale, options: { time: .8 } Utils.delay .9, => @app.removeContent @_app @visible = false # App class App extends Layer # Constructor constructor: (options = {}) -> options.backgroundColor ?= "" options.clip ?= true super options @iconSize = options.size @startPoint = @point @bg = new Layer name: ".bg" point: Align.center size: @iconSize backgroundColor: "black" borderRadius: 42 opacity: 0 parent: @ @content = new Layer name: "content" point: Align.center size: 0 backgroundColor: "black" borderRadius: 42 clip: true parent: @ @content.on "change:size", => @content.center() return unless app = @content.children[0] app.props = x: (@content.width - app.width) / 2, y: (@content.height - app.height) / 2 @aniOptionsShow = time: .3, curve: "ease-out" @aniOptionsDismiss = time: .25, curve: "ease-in" init: -> @bg.opacity = 0 @content.size = 0 show: -> return if @bg.isAnimating @bg.opacity = 1 @content.size = @iconSize @bg.animate opacity: 0, options: @aniOptionsShow @content.animate width: 0, height: 0, options: @aniOptionsShow dismiss: -> return if @bg.isAnimating @bg.animate opacity: 1, options: @aniOptionsDismiss @content.animate width: @iconSize, height: @iconSize, options: @aniOptionsDismiss addContent: (layer, scale) -> if layer @content.addChild layer layer.props = point: Align.center, scale: scale, clip: true removeContent: (layer) -> if layer @content.removeChild layer layer.props = point: 0, scale: 1, clip: false layer.bringToFront() @init()
true
''' watchOS : Apps @auther PI:NAME:<NAME>END_PI (threeword.com) @since 2016.11.23 ''' class exports.Apps extends Layer clockSize = 84 clockScale = 1 appSize = clockSize - 10 appScale = 1 # Constructor constructor: (options = {}) -> options.name ?= "Apps" options.image ?= "images/apps.jpg" super options clockScale = clockSize / Math.sqrt( Math.pow(@width, 2) + Math.pow(@height, 2) ) appScale = appSize / Math.sqrt( Math.pow(@width, 2) + Math.pow(@height, 2) ) @_clockfaces = options.clockfaces @_appInfo = options.appInfo @_app = @_appInfo.app @aniOptionsShow = time: .3, curve: "ease-out" @aniOptionsDismiss = time: .25, curve: "ease-in" @clockface = new App name: "clockfaces" point: Align.center size: clockSize parent: @ @clockface.onClick => @dismiss @_clockfaces # Exist app if @_app @app = new App name: "app" x:Align.center(90), y: Align.center size: appSize html: "APP" style: fontSize: "20px", fontWeight: "600" lineHeight: "#{appSize}px" textAlign: "center" borderStyle: "dashed" borderRadius: appSize/2, borderWidth: 1, borderColor: "white" parent: @ if @_appInfo.icon @app.props = html: "" borderWidth: 0 image: @_appInfo.icon @app.onClick => @dismiss @_app @scale = 1 / clockScale @sendToBack() init: -> @props = visible: true, scale: 1, point: Align.center show: (app) -> return if @isAnimating # ClockFace if app is @_clockfaces @props = scale: 1 / clockScale, point: Align.center @animate scale: 1, options: @aniOptionsShow @clockface.addContent @_clockfaces, clockScale @_clockfaces.timeStop() @visible = true @bringToFront() @clockface.show() @_clockfaces.animateStop() @_clockfaces.animate scale: clockScale * 2/3 # App (Kakaostock) else if app is @_app @props = scale: 1 / appScale, x: Align.center(-90 / appScale), y: Align.center @animate scale: 1, x: Align.center, y: Align.center, options: @aniOptionsShow @app.addContent @_app, appScale @visible = true @bringToFront() @app.show() @_app.animateStop() @_app.animate scale: appScale * 2/3 dismiss: (app) -> return if @isAnimating # ClockFace if app is @_clockfaces return if @_clockfaces.isAnimating @animate scale: 1 / clockScale, options: @aniOptionsDismiss @clockface.dismiss() @_clockfaces.visible = true @_clockfaces.animate scale: clockScale, options: { time: .8 } Utils.delay .9, => @clockface.removeContent @_clockfaces @_clockfaces.timeStart() @visible = false # App (Kakaostock) else if app is @_app return if @_app.isAnimating # if _.isEmpty(@app.content.children) @app.addContent @_app, appScale @animate scale: 1 / appScale, x: Align.center(-90 / appScale), y: Align.center, options: @aniOptionsDismiss @app.dismiss() @_app.visible = true @_app.animate scale: appScale, options: { time: .8 } Utils.delay .9, => @app.removeContent @_app @visible = false # App class App extends Layer # Constructor constructor: (options = {}) -> options.backgroundColor ?= "" options.clip ?= true super options @iconSize = options.size @startPoint = @point @bg = new Layer name: ".bg" point: Align.center size: @iconSize backgroundColor: "black" borderRadius: 42 opacity: 0 parent: @ @content = new Layer name: "content" point: Align.center size: 0 backgroundColor: "black" borderRadius: 42 clip: true parent: @ @content.on "change:size", => @content.center() return unless app = @content.children[0] app.props = x: (@content.width - app.width) / 2, y: (@content.height - app.height) / 2 @aniOptionsShow = time: .3, curve: "ease-out" @aniOptionsDismiss = time: .25, curve: "ease-in" init: -> @bg.opacity = 0 @content.size = 0 show: -> return if @bg.isAnimating @bg.opacity = 1 @content.size = @iconSize @bg.animate opacity: 0, options: @aniOptionsShow @content.animate width: 0, height: 0, options: @aniOptionsShow dismiss: -> return if @bg.isAnimating @bg.animate opacity: 1, options: @aniOptionsDismiss @content.animate width: @iconSize, height: @iconSize, options: @aniOptionsDismiss addContent: (layer, scale) -> if layer @content.addChild layer layer.props = point: Align.center, scale: scale, clip: true removeContent: (layer) -> if layer @content.removeChild layer layer.props = point: 0, scale: 1, clip: false layer.bringToFront() @init()
[ { "context": " host: 'http://help.s2way.com:3000'\n key: '8931687dc430de3ddd2776e95588f979ae474673'\n es:\n host: process.env.ES_HOST or 'lo", "end": 127, "score": 0.9997732043266296, "start": 87, "tag": "KEY", "value": "8931687dc430de3ddd2776e95588f979ae474673" } ]
src/config.coffee
s2way/redmine_kms
0
module.exports = redmine: host: 'http://help.s2way.com:3000' key: '8931687dc430de3ddd2776e95588f979ae474673' es: host: process.env.ES_HOST or 'localhost' port: process.env.ES_PORT or 9200 keepAlive: true # default is true timeout: process.env.ES_TIMEOUT or 30000 # default is 30000
181470
module.exports = redmine: host: 'http://help.s2way.com:3000' key: '<KEY>' es: host: process.env.ES_HOST or 'localhost' port: process.env.ES_PORT or 9200 keepAlive: true # default is true timeout: process.env.ES_TIMEOUT or 30000 # default is 30000
true
module.exports = redmine: host: 'http://help.s2way.com:3000' key: 'PI:KEY:<KEY>END_PI' es: host: process.env.ES_HOST or 'localhost' port: process.env.ES_PORT or 9200 keepAlive: true # default is true timeout: process.env.ES_TIMEOUT or 30000 # default is 30000
[ { "context": "tempest',\n title : \"The Tempest\",\n name : \"William\"\n surname : \"Shakespeare\"\n length : 123\n\nok te", "end": 484, "score": 0.9998073577880859, "start": 477, "tag": "NAME", "value": "William" }, { "context": "\"The Tempest\",\n name : \"William\"\n surname : \"Shakespeare\"\n length : 123\n\nok tempest.fullName() is \"Willi", "end": 510, "score": 0.9998317956924438, "start": 499, "tag": "NAME", "value": "Shakespeare" }, { "context": "peare\"\n length : 123\n\nok tempest.fullName() is \"William Shakespeare\"\nok tempest.get('length') is 123\n\n\nclass ProperDo", "end": 574, "score": 0.9998660683631897, "start": 555, "tag": "NAME", "value": "William Shakespeare" }, { "context": "st.attributes\n\nok properTempest.fullName() is \"Mr. William Shakespeare\"\nok properTempest.get('length') is 123\n\n\nconsole.", "end": 794, "score": 0.9998292922973633, "start": 775, "tag": "NAME", "value": "William Shakespeare" } ]
test/model.coffee
mikesten/backbone
12,684
# Quick Backbone/CoffeeScript tests to make sure that inheritance # works correctly. {ok, equal, deepEqual} = require 'assert' {Model, Collection, Events} = require '../backbone' # Patch `ok` to store a count of passed tests... count = 0 oldOk = ok ok = -> oldOk arguments... count++ class Document extends Model fullName: -> @get('name') + ' ' + @get('surname') tempest = new Document id : '1-the-tempest', title : "The Tempest", name : "William" surname : "Shakespeare" length : 123 ok tempest.fullName() is "William Shakespeare" ok tempest.get('length') is 123 class ProperDocument extends Document fullName: -> "Mr. " + super properTempest = new ProperDocument tempest.attributes ok properTempest.fullName() is "Mr. William Shakespeare" ok properTempest.get('length') is 123 console.log "passed #{count} tests"
186211
# Quick Backbone/CoffeeScript tests to make sure that inheritance # works correctly. {ok, equal, deepEqual} = require 'assert' {Model, Collection, Events} = require '../backbone' # Patch `ok` to store a count of passed tests... count = 0 oldOk = ok ok = -> oldOk arguments... count++ class Document extends Model fullName: -> @get('name') + ' ' + @get('surname') tempest = new Document id : '1-the-tempest', title : "The Tempest", name : "<NAME>" surname : "<NAME>" length : 123 ok tempest.fullName() is "<NAME>" ok tempest.get('length') is 123 class ProperDocument extends Document fullName: -> "Mr. " + super properTempest = new ProperDocument tempest.attributes ok properTempest.fullName() is "Mr. <NAME>" ok properTempest.get('length') is 123 console.log "passed #{count} tests"
true
# Quick Backbone/CoffeeScript tests to make sure that inheritance # works correctly. {ok, equal, deepEqual} = require 'assert' {Model, Collection, Events} = require '../backbone' # Patch `ok` to store a count of passed tests... count = 0 oldOk = ok ok = -> oldOk arguments... count++ class Document extends Model fullName: -> @get('name') + ' ' + @get('surname') tempest = new Document id : '1-the-tempest', title : "The Tempest", name : "PI:NAME:<NAME>END_PI" surname : "PI:NAME:<NAME>END_PI" length : 123 ok tempest.fullName() is "PI:NAME:<NAME>END_PI" ok tempest.get('length') is 123 class ProperDocument extends Document fullName: -> "Mr. " + super properTempest = new ProperDocument tempest.attributes ok properTempest.fullName() is "Mr. PI:NAME:<NAME>END_PI" ok properTempest.get('length') is 123 console.log "passed #{count} tests"
[ { "context": "pyOn(@storage, 'update')\n @dream.save(name: 'New dream')\n expect(@storage.update).toHaveBeenC", "end": 1414, "score": 0.5147351026535034, "start": 1411, "tag": "NAME", "value": "New" } ]
spec/lib/offline_spec.coffee
alekseykulikov/backbone-offline
33
describe 'Offline', -> beforeEach -> localStorage.setItem('dreams', '') @dreams = new Dreams() afterEach -> window.localStorage.clear() describe 'onLine', -> it 'should returns true when onLine is undefined', -> window.navigator = {} expect(Offline.onLine()).toBeTruthy() it 'should returns true when onLine is true', -> window.navigator = {onLine: true} expect(Offline.onLine()).toBeTruthy() it 'should returns false when onLine is false', -> window.navigator = {onLine: false} expect(Offline.onLine()).toBeFalsy() describe 'localSync', -> beforeEach -> @storage = @dreams.storage @dream = @dreams.create() registerFakeAjax url: '/api/dreams', successData: {} it 'should call "findAll" when reading collection', -> spyOn(@storage, 'findAll') @dreams.fetch() expect(@storage.findAll).toHaveBeenCalledWith(jasmine.any(Object)) it 'should call "find" when reading model', -> spyOn(@storage, 'find') @dream.fetch() expect(@storage.find).toHaveBeenCalledWith(@dream, jasmine.any(Object)) it 'should call "create" when creating model', -> spyOn(@storage, 'create') @dreams.create(name: 'New dream') expect(@storage.create).toHaveBeenCalled() it 'should call "update" when update model', -> spyOn(@storage, 'update') @dream.save(name: 'New dream') expect(@storage.update).toHaveBeenCalledWith(@dream, jasmine.any(Object)) it 'should call "destroy" when delete model', -> spyOn(@storage, 'destroy') @dream.destroy() expect(@storage.destroy).toHaveBeenCalledWith(@dream, jasmine.any(Object)) it "should calls \"options.success\" when storage's method responses something", -> successCallback = jasmine.createSpy('-Success Callback-') @dream.save({name: 'New dream'}, {success: (model, resp, options) -> successCallback(resp) }) expect(successCallback).toHaveBeenCalledWith(@dream.attributes) it 'should call "options.error" when response is blank', -> errorCallback = jasmine.createSpy('-Error Callback-') spyOn(@storage, 'update').andReturn(null) @dream.save({name: ''}, {error: (message) -> errorCallback(message)}) expect(errorCallback).toHaveBeenCalled() describe 'sync', -> beforeEach -> spyOn(Offline, 'localSync') spyOn(Backbone, 'ajaxSync') describe 'when @storage exists', -> it 'should delegates actions to Offline.localSync if @support equal true', -> @dreams.fetch() expect(Offline.localSync).toHaveBeenCalled() it 'should delegates actions to Backbone.ajaxSync if @support equal false', -> @dreams.storage.support = false @dreams.fetch() expect(Backbone.ajaxSync).toHaveBeenCalled() describe 'when @storage empty', -> it 'should delegate actions to Backbone.ajaxSync', -> @dreams.storage = null @dreams.fetch() expect(Backbone.ajaxSync).toHaveBeenCalled()
14141
describe 'Offline', -> beforeEach -> localStorage.setItem('dreams', '') @dreams = new Dreams() afterEach -> window.localStorage.clear() describe 'onLine', -> it 'should returns true when onLine is undefined', -> window.navigator = {} expect(Offline.onLine()).toBeTruthy() it 'should returns true when onLine is true', -> window.navigator = {onLine: true} expect(Offline.onLine()).toBeTruthy() it 'should returns false when onLine is false', -> window.navigator = {onLine: false} expect(Offline.onLine()).toBeFalsy() describe 'localSync', -> beforeEach -> @storage = @dreams.storage @dream = @dreams.create() registerFakeAjax url: '/api/dreams', successData: {} it 'should call "findAll" when reading collection', -> spyOn(@storage, 'findAll') @dreams.fetch() expect(@storage.findAll).toHaveBeenCalledWith(jasmine.any(Object)) it 'should call "find" when reading model', -> spyOn(@storage, 'find') @dream.fetch() expect(@storage.find).toHaveBeenCalledWith(@dream, jasmine.any(Object)) it 'should call "create" when creating model', -> spyOn(@storage, 'create') @dreams.create(name: 'New dream') expect(@storage.create).toHaveBeenCalled() it 'should call "update" when update model', -> spyOn(@storage, 'update') @dream.save(name: '<NAME> dream') expect(@storage.update).toHaveBeenCalledWith(@dream, jasmine.any(Object)) it 'should call "destroy" when delete model', -> spyOn(@storage, 'destroy') @dream.destroy() expect(@storage.destroy).toHaveBeenCalledWith(@dream, jasmine.any(Object)) it "should calls \"options.success\" when storage's method responses something", -> successCallback = jasmine.createSpy('-Success Callback-') @dream.save({name: 'New dream'}, {success: (model, resp, options) -> successCallback(resp) }) expect(successCallback).toHaveBeenCalledWith(@dream.attributes) it 'should call "options.error" when response is blank', -> errorCallback = jasmine.createSpy('-Error Callback-') spyOn(@storage, 'update').andReturn(null) @dream.save({name: ''}, {error: (message) -> errorCallback(message)}) expect(errorCallback).toHaveBeenCalled() describe 'sync', -> beforeEach -> spyOn(Offline, 'localSync') spyOn(Backbone, 'ajaxSync') describe 'when @storage exists', -> it 'should delegates actions to Offline.localSync if @support equal true', -> @dreams.fetch() expect(Offline.localSync).toHaveBeenCalled() it 'should delegates actions to Backbone.ajaxSync if @support equal false', -> @dreams.storage.support = false @dreams.fetch() expect(Backbone.ajaxSync).toHaveBeenCalled() describe 'when @storage empty', -> it 'should delegate actions to Backbone.ajaxSync', -> @dreams.storage = null @dreams.fetch() expect(Backbone.ajaxSync).toHaveBeenCalled()
true
describe 'Offline', -> beforeEach -> localStorage.setItem('dreams', '') @dreams = new Dreams() afterEach -> window.localStorage.clear() describe 'onLine', -> it 'should returns true when onLine is undefined', -> window.navigator = {} expect(Offline.onLine()).toBeTruthy() it 'should returns true when onLine is true', -> window.navigator = {onLine: true} expect(Offline.onLine()).toBeTruthy() it 'should returns false when onLine is false', -> window.navigator = {onLine: false} expect(Offline.onLine()).toBeFalsy() describe 'localSync', -> beforeEach -> @storage = @dreams.storage @dream = @dreams.create() registerFakeAjax url: '/api/dreams', successData: {} it 'should call "findAll" when reading collection', -> spyOn(@storage, 'findAll') @dreams.fetch() expect(@storage.findAll).toHaveBeenCalledWith(jasmine.any(Object)) it 'should call "find" when reading model', -> spyOn(@storage, 'find') @dream.fetch() expect(@storage.find).toHaveBeenCalledWith(@dream, jasmine.any(Object)) it 'should call "create" when creating model', -> spyOn(@storage, 'create') @dreams.create(name: 'New dream') expect(@storage.create).toHaveBeenCalled() it 'should call "update" when update model', -> spyOn(@storage, 'update') @dream.save(name: 'PI:NAME:<NAME>END_PI dream') expect(@storage.update).toHaveBeenCalledWith(@dream, jasmine.any(Object)) it 'should call "destroy" when delete model', -> spyOn(@storage, 'destroy') @dream.destroy() expect(@storage.destroy).toHaveBeenCalledWith(@dream, jasmine.any(Object)) it "should calls \"options.success\" when storage's method responses something", -> successCallback = jasmine.createSpy('-Success Callback-') @dream.save({name: 'New dream'}, {success: (model, resp, options) -> successCallback(resp) }) expect(successCallback).toHaveBeenCalledWith(@dream.attributes) it 'should call "options.error" when response is blank', -> errorCallback = jasmine.createSpy('-Error Callback-') spyOn(@storage, 'update').andReturn(null) @dream.save({name: ''}, {error: (message) -> errorCallback(message)}) expect(errorCallback).toHaveBeenCalled() describe 'sync', -> beforeEach -> spyOn(Offline, 'localSync') spyOn(Backbone, 'ajaxSync') describe 'when @storage exists', -> it 'should delegates actions to Offline.localSync if @support equal true', -> @dreams.fetch() expect(Offline.localSync).toHaveBeenCalled() it 'should delegates actions to Backbone.ajaxSync if @support equal false', -> @dreams.storage.support = false @dreams.fetch() expect(Backbone.ajaxSync).toHaveBeenCalled() describe 'when @storage empty', -> it 'should delegate actions to Backbone.ajaxSync', -> @dreams.storage = null @dreams.fetch() expect(Backbone.ajaxSync).toHaveBeenCalled()
[ { "context": "class Person\n \n named: (@name) ->\n @\n\n withSpouse: (@spouse) ->\n @\n\n", "end": 24, "score": 0.5957663059234619, "start": 24, "tag": "NAME", "value": "" }, { "context": "class Person\n \n named: (@name) ->\n @\n\n withSpouse: (@spouse) ->\n @\n\n bo", "end": 31, "score": 0.8343538641929626, "start": 27, "tag": "USERNAME", "value": "name" }, { "context": "b) ->\n @\n\n build : ->\n return {\n name: @name\n spouse: @spouse\n dob: @dob\n }\n\n", "end": 141, "score": 0.9656230807304382, "start": 141, "tag": "NAME", "value": "" }, { "context": " ->\n @\n\n build : ->\n return {\n name: @name\n spouse: @spouse\n dob: @dob\n }\n\ncons", "end": 147, "score": 0.40797972679138184, "start": 143, "tag": "USERNAME", "value": "name" }, { "context": " dob: @dob\n }\n\nconsole.log new Person().named('Adam').withSpouse('Rachel').build() ", "end": 229, "score": 0.9995365738868713, "start": 225, "tag": "NAME", "value": "Adam" }, { "context": "onsole.log new Person().named('Adam').withSpouse('Rachel').build() ", "end": 250, "score": 0.9996829628944397, "start": 244, "tag": "NAME", "value": "Rachel" } ]
index.coffee
adamnengland/coffee-fluent-interface
1
class Person named: (@name) -> @ withSpouse: (@spouse) -> @ bornOn: (@dob) -> @ build : -> return { name: @name spouse: @spouse dob: @dob } console.log new Person().named('Adam').withSpouse('Rachel').build()
147492
class Person named:<NAME> (@name) -> @ withSpouse: (@spouse) -> @ bornOn: (@dob) -> @ build : -> return { name:<NAME> @name spouse: @spouse dob: @dob } console.log new Person().named('<NAME>').withSpouse('<NAME>').build()
true
class Person named:PI:NAME:<NAME>END_PI (@name) -> @ withSpouse: (@spouse) -> @ bornOn: (@dob) -> @ build : -> return { name:PI:NAME:<NAME>END_PI @name spouse: @spouse dob: @dob } console.log new Person().named('PI:NAME:<NAME>END_PI').withSpouse('PI:NAME:<NAME>END_PI').build()
[ { "context": "ent without an explicit \"type\" attribute\n# @author Filipp Riabchun\n###\n'use strict'\n\n# -----------------------------", "end": 107, "score": 0.9998507499694824, "start": 92, "tag": "NAME", "value": "Filipp Riabchun" } ]
src/tests/rules/button-has-type.coffee
helixbass/eslint-plugin-coffee
21
###* # @fileoverview Forbid "button" element without an explicit "type" attribute # @author Filipp Riabchun ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require 'eslint-plugin-react/lib/rules/button-has-type' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'button-has-type', rule, valid: [ code: '<span/>' , code: '<span type="foo"/>' , code: '<button type="button"/>' , code: '<button type="submit"/>' , code: '<button type="reset"/>' , code: '<button type="button"/>' options: [reset: no] , code: 'React.createElement("span")' , code: 'React.createElement("span", {type: "foo"})' , code: 'React.createElement "span", type: "foo"' , code: 'React.createElement("button", {type: "button"})' , code: 'React.createElement("button", {type: "submit"})' , code: 'React.createElement("button", {type: "reset"})' , code: 'React.createElement("button", {type: "button"})' options: [reset: no] , code: 'document.createElement("button")' , code: 'Foo.createElement("span")' settings: react: pragma: 'Foo' ] invalid: [ code: '<button/>' errors: [message: 'Missing an explicit type attribute for button'] , code: '<button type="foo"/>' errors: [message: '"foo" is an invalid value for button type attribute'] , code: '<button type={foo}/>' errors: [ message: 'The button type attribute must be specified by a static string or a trivial ternary expression' ] , code: '<button type="reset"/>' options: [reset: no] errors: [message: '"reset" is an invalid value for button type attribute'] , code: 'React.createElement("button")' errors: [message: 'Missing an explicit type attribute for button'] , code: 'React.createElement("button", {type: "foo"})' errors: [message: '"foo" is an invalid value for button type attribute'] , code: 'React.createElement "button", type: "foo"' errors: [message: '"foo" is an invalid value for button type attribute'] , code: 'React.createElement("button", {type: "reset"})' options: [reset: no] errors: [message: '"reset" is an invalid value for button type attribute'] , code: 'Foo.createElement("button")' errors: [message: 'Missing an explicit type attribute for button'] settings: react: pragma: 'Foo' ]
190832
###* # @fileoverview Forbid "button" element without an explicit "type" attribute # @author <NAME> ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require 'eslint-plugin-react/lib/rules/button-has-type' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'button-has-type', rule, valid: [ code: '<span/>' , code: '<span type="foo"/>' , code: '<button type="button"/>' , code: '<button type="submit"/>' , code: '<button type="reset"/>' , code: '<button type="button"/>' options: [reset: no] , code: 'React.createElement("span")' , code: 'React.createElement("span", {type: "foo"})' , code: 'React.createElement "span", type: "foo"' , code: 'React.createElement("button", {type: "button"})' , code: 'React.createElement("button", {type: "submit"})' , code: 'React.createElement("button", {type: "reset"})' , code: 'React.createElement("button", {type: "button"})' options: [reset: no] , code: 'document.createElement("button")' , code: 'Foo.createElement("span")' settings: react: pragma: 'Foo' ] invalid: [ code: '<button/>' errors: [message: 'Missing an explicit type attribute for button'] , code: '<button type="foo"/>' errors: [message: '"foo" is an invalid value for button type attribute'] , code: '<button type={foo}/>' errors: [ message: 'The button type attribute must be specified by a static string or a trivial ternary expression' ] , code: '<button type="reset"/>' options: [reset: no] errors: [message: '"reset" is an invalid value for button type attribute'] , code: 'React.createElement("button")' errors: [message: 'Missing an explicit type attribute for button'] , code: 'React.createElement("button", {type: "foo"})' errors: [message: '"foo" is an invalid value for button type attribute'] , code: 'React.createElement "button", type: "foo"' errors: [message: '"foo" is an invalid value for button type attribute'] , code: 'React.createElement("button", {type: "reset"})' options: [reset: no] errors: [message: '"reset" is an invalid value for button type attribute'] , code: 'Foo.createElement("button")' errors: [message: 'Missing an explicit type attribute for button'] settings: react: pragma: 'Foo' ]
true
###* # @fileoverview Forbid "button" element without an explicit "type" attribute # @author PI:NAME:<NAME>END_PI ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require 'eslint-plugin-react/lib/rules/button-has-type' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'button-has-type', rule, valid: [ code: '<span/>' , code: '<span type="foo"/>' , code: '<button type="button"/>' , code: '<button type="submit"/>' , code: '<button type="reset"/>' , code: '<button type="button"/>' options: [reset: no] , code: 'React.createElement("span")' , code: 'React.createElement("span", {type: "foo"})' , code: 'React.createElement "span", type: "foo"' , code: 'React.createElement("button", {type: "button"})' , code: 'React.createElement("button", {type: "submit"})' , code: 'React.createElement("button", {type: "reset"})' , code: 'React.createElement("button", {type: "button"})' options: [reset: no] , code: 'document.createElement("button")' , code: 'Foo.createElement("span")' settings: react: pragma: 'Foo' ] invalid: [ code: '<button/>' errors: [message: 'Missing an explicit type attribute for button'] , code: '<button type="foo"/>' errors: [message: '"foo" is an invalid value for button type attribute'] , code: '<button type={foo}/>' errors: [ message: 'The button type attribute must be specified by a static string or a trivial ternary expression' ] , code: '<button type="reset"/>' options: [reset: no] errors: [message: '"reset" is an invalid value for button type attribute'] , code: 'React.createElement("button")' errors: [message: 'Missing an explicit type attribute for button'] , code: 'React.createElement("button", {type: "foo"})' errors: [message: '"foo" is an invalid value for button type attribute'] , code: 'React.createElement "button", type: "foo"' errors: [message: '"foo" is an invalid value for button type attribute'] , code: 'React.createElement("button", {type: "reset"})' options: [reset: no] errors: [message: '"reset" is an invalid value for button type attribute'] , code: 'Foo.createElement("button")' errors: [message: 'Missing an explicit type attribute for button'] settings: react: pragma: 'Foo' ]
[ { "context": " 2 spaces'\n\n line1Expected = /var name = ['\"]Josh['\"];/\n line2Expected = /if \\( {0,1}name ={2,", "end": 29063, "score": 0.998833417892456, "start": 29059, "tag": "NAME", "value": "Josh" }, { "context": " line2Expected = /if \\( {0,1}name ={2,3} ['\"]Peter['\"] {0,1}\\) {/\n line3Expected = /console\\.lo", "end": 29125, "score": 0.996502161026001, "start": 29120, "tag": "NAME", "value": "Peter" }, { "context": " {/\n line3Expected = /console\\.log\\(['\"]Hello Peter['\"]\\);/\n line4Expected = /} else if \\( {0,1}", "end": 29193, "score": 0.9997963309288025, "start": 29188, "tag": "NAME", "value": "Peter" }, { "context": "ine4Expected = /} else if \\( {0,1}name ={2,3} ['\"]John['\"] {0,1}\\) {/\n line5Expected = /console\\.lo", "end": 29263, "score": 0.9997686743736267, "start": 29259, "tag": "NAME", "value": "John" }, { "context": " {/\n line5Expected = /console\\.log\\(['\"]Hello John['\"]\\);/\n line6Expected = '} else {'\n li", "end": 29330, "score": 0.9997807741165161, "start": 29326, "tag": "NAME", "value": "John" }, { "context": "k if variable has name <i>name</i> and value <b>\\'Josh\\'</b>, check spaces before and after assignment o", "end": 29601, "score": 0.9758808612823486, "start": 29597, "tag": "NAME", "value": "Josh" }, { "context": "ndition which compares variable name with value \\'Peter\\', do you have space after if?'\n\n if !line3E", "end": 29848, "score": 0.9530429244041443, "start": 29843, "tag": "NAME", "value": "Peter" }, { "context": " return TAPi18n.__ 'Error on line 3, print \\'Hello Peter\\' with console.log(), check if the statement ends", "end": 29981, "score": 0.9997852444648743, "start": 29976, "tag": "NAME", "value": "Peter" }, { "context": " return TAPi18n.__ 'Error on line 5, print \\'Hello John\\' with console.log(), check if the statement ends", "end": 30302, "score": 0.9662838578224182, "start": 30298, "tag": "NAME", "value": "John" }, { "context": " return TAPi18n.__ \"Error on line 7, print 'Hello stranger' with console.log(), check if the statement ends ", "end": 30619, "score": 0.8658076524734497, "start": 30611, "tag": "NAME", "value": "stranger" }, { "context": "= '}'\n line5Expected = /printNameAndAge\\([\"']Tom['\"], 28\\);/\n\n unless /name/.test(line1)\n ", "end": 46939, "score": 0.9680289626121521, "start": 46936, "tag": "NAME", "value": "Tom" } ]
lib/lessons/JSExercise.coffee
Elfoslav/codermania
56
class @JSExercise ### # @param opts Object # lesson # exercise # code # @returns true on success, string message on failure ### @checkExercise: (opts) -> opts.code = $.trim(opts.code) exercise = opts.exercise lesson = opts.lesson success = false resultMsg = '' ###################### # Expressions ###################### if exercise.id is '1ce1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line1Expected = /console\.log\( {0,1}\({0,1} {0,1}1 \+ 2 {0,1}\){0,1} < 4 {0,1}\);/ if line1Expected.test(line1) success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1ce2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line1Expected = /console\.log\( {0,1}\({0,1} {0,1}2 \+ 3 {0,1}\){0,1} > 5 {0,1}\);/ if line1Expected.test(line1) success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1ce3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line1Expected = /console\.log\( {0,1}\({0,1}5 \+ 2 {0,1}\){0,1} <= \({0,1} {0,1}14 \/ 2 {0,1}\){0,1} {0,1}\);/ if line1Expected.test(line1) success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1ce4' lines = opts.code.split('\n') line1 = $.trim(lines[0]) #console.log(9 - 3 >= 2 * 3); #console.log((9 - 3) >= (2 * 3)); line1Expected = /console\.log\( {0,1}\({0,1} {0,1}9 \- 3 {0,1}\){0,1} >= \({0,1} {0,1}2 \* 3 {0,1}\){0,1} {0,1}\);/ if line1Expected.test(line1) success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' ############# # Arithmetic operators ############# if exercise.id is '1ie1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = /var i = 5;/ line2Expected = /(i\+\+;|\+\+i;)/ line3Expected = /console\.log\(i\);/ if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if the variable name is <i>i</i> and value is 5, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if you increment variable <i>i</i> with operator ++, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, read assignment for line 3 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1ie2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = /var i = 5;/ line2Expected = /(i--;|--i;)/ line3Expected = /console\.log\(i\);/ if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if the variable name is <i>i</i> and value is 5, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if you decrement variable <i>i</i> with operator --, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, read assignment for line 3 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1ie3' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('%') result = numbers[0] % numbers[1] if result is 2 success = true else return resultMsg = TAPi18n.__ "Expected result is 2 but your result is #{result}" ####################### # comparision operators ####################### if exercise.id is '1se1' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('<') result = parseInt(numbers[0]) < parseInt(numbers[1]) if result success = true else if result is false return TAPi18n.__ 'Result is false, it should be true' else return TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1se2' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('<=') result = parseInt(numbers[0]) <= parseInt(numbers[1]) if result success = true else if result is false return TAPi18n.__ 'Result is false, it should be true' else return TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1se3' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('>=') result = parseInt(numbers[0]) >= parseInt(numbers[1]) if result success = true else if result is false return TAPi18n.__ 'Result is false, it should be true' else return TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1se4' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('==') type1 = typeof numbers[0] if isNaN(parseInt(numbers[0])) return TAPi18n.__ "First argument should be number. #{type1} given" if numbers[1].indexOf("'") is -1 and numbers[1].indexOf('"') is -1 return TAPi18n.__ "Second argument should be string. Something like '2' or \"2\"" #strip quotes numbers[1] = numbers[1].replace(/[\'\"]/g, '') #use JS operator == result = `$.trim(numbers[0]) == $.trim(numbers[1])` if result success = true else if result is false return TAPi18n.__ 'Result is false, it should be true' else return TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' ###################### # Assignment operators ###################### if exercise.id is '1je1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line1Expected = 'var number = 1;' line2Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number", check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print variable number with console.log(), check if the statement ends with semicolon' if line1 is line1Expected and line2 is line2Expected success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1je2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = 'var number = 2;' line2Expected = 'number += 5;' line3Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number" and value 2, check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, add number 5 to variable number using operator +=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable number with console.log(), check if the statement ends with semicolon' if line1 is line1Expected and line2 is line2Expected and line3 is line3Expected success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1je3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = 'var number = 3;' line2Expected = 'number -= 1;' line3Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number" and value 3, check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, subtract number 1 from variable number using operator -=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable number with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1je4' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = 'var number = 4;' line2Expected = 'number *= 2;' line3Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number" and value 4, check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, multiply variable number by 2 using operator *=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable number with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1je5' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = 'var number = 5;' line2Expected = 'number /= 2;' line3Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number" and value 4, check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, divide variable number by 2 using operator /=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable number with console.log(), check if the statement ends with semicolon' success = true ###################### # Assignment operators ###################### if exercise.id is '1ke1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = /var someText = ['"]Lorem ipsum['"];/ line2Expected = /someText \+= ['"] dolor sit amet['"];/ line3Expected = 'console.log(someText);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "someText" and value "Lorem ipsum", check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, add text " dolor sit amet" to variable someText using operator +=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable someText with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1ke2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var fruit1 = ['"]apple['"];/ line2Expected = /var fruit2 = ['"]banana['"];/ line3Expected = /var appleAndBanana = fruit1 \+ ['"] and ['"] \+ fruit2;/ line4Expected = 'console.log(appleAndBanana);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "fruit1" and value "apple", check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "fruit2" and value "banana", check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, read assignment on Line 3 and try again.' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print variable appleAndBanana with console.log(), check if the statement ends with semicolon' success = true ###################### # Integer variables ###################### if exercise.id is '1fe1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var number1 = 45;/ line2Expected = /var number2 = 100;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'console.log(result);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 45, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 100, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print variable result with console.log(), check if the statement ends with semicolon' success = true ###################### # Float variables ###################### if exercise.id is '1ge1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var number1 = 0.55;/ line2Expected = /var number2 = 0.199;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'console.log(result);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 0.55, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 0.199, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print variable result with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1ge2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var number1 = 0.55;/ line2Expected = /var number2 = 0.199;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'console.log(result.toFixed(2));' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 0.55, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 0.199, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, round variable result to 2 decimal places and print it with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1ge3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line1Expected = /var number1 = 0.55;/ line2Expected = /var number2 = 0.199;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'var roundedResult = result.toFixed(2);' line5Expected = 'console.log(roundedResult + 3);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 0.55, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 0.199, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, check if variable has name "roundedResult" and value of rounded variable "result" to 2 decimal places, check if the statement ends with semicolon' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, print roundedResult + 3 with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1ge4' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line1Expected = /var number1 = 0.55;/ line2Expected = /var number2 = 0.199;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'var roundedResult = result.toFixed(2);' line5Expected = 'console.log(parseFloat(roundedResult) + 3);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 0.55, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 0.199, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, check if variable has name "roundedResult" and value of rounded variable "result" to 2 decimal places, check if the statement ends with semicolon' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, parse value of roundedResult and add 3 to the result. Print it with console.log(), check if the statement ends with semicolon' success = true ###################### # Arrays ###################### if exercise.id is '1le1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var numbers = \[ {0,1}\];/ line2Expected = /numbers\.push\(1\);/ line3Expected = /numbers\.push\(2\);/ line4Expected = 'console.log(numbers[0]);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "numbers" and is array, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, add value 1 to variable numbers with method push(), check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, add value 2 to variable numbers with method push(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print value 1 from array numbers with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1le2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var bands = \[ {0,1}['"]Metallica['"], ["']Iron Maiden["'] {0,1}\];/ line2Expected = /bands\.push\(["']AC\/DC["']\);/ line3Expected = 'console.log(bands[0]);' line4Expected = 'console.log(bands[2]);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "bands" and is array and you have space after comas, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, add value \'AC/DC\' to array bands with method push(), check if the statement ends with semicolon' if line3Expected != line3 return TAPi18n.__ 'Error on line 3, print the first item from array bands with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print the last item from array bands with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1le3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line1Expected = /var numbers = \[ {0,1}5, 8, 3\.3 {0,1}\];/ line2Expected = 'console.log(numbers[0] + numbers[1] + numbers[2]);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "numbers" and you have space after comas, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, first add number with index 0, then 1, then 2, check if you have space before and after + operator, check if the statement ends with semicolon' success = true ###################### # Conditions ###################### if exercise.id is '1me1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var fruit = ['"]banana['"];/ line2Expected = /if \( {0,1}fruit ={2,3} ['"]banana['"] {0,1}\) {/ line3Expected = /console\.log\(['"]variable fruit has value banana['"]\);/ line4Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "fruit" and value \'banana\', check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition which compares variable fruit with value \'banana\', do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'variable fruit has value banana\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' #line 1 if CodeChecker.hasIndentation(lines[0], 1) return TAPi18n.__ 'Error on line 1, this line should not have indentation!' #line 2 if CodeChecker.hasIndentation(lines[1], 1) return TAPi18n.__ 'Error on line 2, this line should not have indentation!' #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 4 if CodeChecker.hasIndentation(lines[3], 1) return TAPi18n.__ 'Error on line 4, this line should not have indentation!' success = true if exercise.id is '1me2' lines = opts.code.split('\n') #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 5 unless CodeChecker.hasIndentation(lines[4]) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line6 = $.trim(lines[5]) line1Expected = /var isHappy = true;/ #if (isHappy) { #or #if (isHappy == true) { line2Expected = /if \( {0,1}isHappy {0,1}(={2,3}){0,1} {0,1}(true){0,1} {0,1}\) {/ line3Expected = /console\.log\(['"]He is happy['"]\);/ line4Expected = '} else {' line5Expected = /console\.log\(['"]He is not happy['"]\);/ line6Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "isHappy" and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable isHappy, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'He is happy\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, you do not have correct else block, check how it is written in theory' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, print \'He is not happy\' with console.log(), check if the statement ends with semicolon' if line6 != line6Expected return TAPi18n.__ 'Error on line 6, close if condition with }' #line 1 if CodeChecker.hasIndentation(lines[0], 1) return TAPi18n.__ 'Error on line 1, this line should not have indentation!' #line 2 if CodeChecker.hasIndentation(lines[1], 1) return TAPi18n.__ 'Error on line 2, this line should not have indentation!' #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 4 if CodeChecker.hasIndentation(lines[3], 1) return TAPi18n.__ 'Error on line 4, this line should not have indentation!' #line 5 unless CodeChecker.hasIndentation(lines[4]) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' #line 6 if CodeChecker.hasIndentation(lines[5], 1) return TAPi18n.__ 'Error on line 6, this line should not have indentation!' success = true if exercise.id is '1me3' lines = opts.code.split('\n') #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 5 unless CodeChecker.hasIndentation(lines[4]) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' #line 7 unless CodeChecker.hasIndentation(lines[6]) return TAPi18n.__ 'Error on line 7, you are missing indentation - tabulator or 2 spaces' line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line6 = $.trim(lines[5]) line7 = $.trim(lines[6]) line8 = $.trim(lines[7]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 5 unless CodeChecker.hasIndentation(lines[4]) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' #line 7 unless CodeChecker.hasIndentation(lines[6]) return TAPi18n.__ 'Error on line 7, you are missing indentation - tabulator or 2 spaces' line1Expected = /var name = ['"]Josh['"];/ line2Expected = /if \( {0,1}name ={2,3} ['"]Peter['"] {0,1}\) {/ line3Expected = /console\.log\(['"]Hello Peter['"]\);/ line4Expected = /} else if \( {0,1}name ={2,3} ['"]John['"] {0,1}\) {/ line5Expected = /console\.log\(['"]Hello John['"]\);/ line6Expected = '} else {' line7Expected = /console\.log\(['"]Hello stranger['"]\);/ line8Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name <i>name</i> and value <b>\'Josh\'</b>, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition which compares variable name with value \'Peter\', do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'Hello Peter\' with console.log(), check if the statement ends with semicolon' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, you do not have correct else if block, check how it is written in theory' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, print \'Hello John\' with console.log(), check if the statement ends with semicolon' if line6 != line6Expected return TAPi18n.__ 'Error on line 6, you do not have correct else block, check how it is written in theory' if !line7Expected.test(line7) return TAPi18n.__ "Error on line 7, print 'Hello stranger' with console.log(), check if the statement ends with semicolon" if line8 != line8Expected return TAPi18n.__ 'Error on line 8, close if condition with }' success = true ###################### # Logical operators ###################### if exercise.id is '1ne1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var isHappy = true;/ line2Expected = /if \( {0,1}!isHappy {0,1}\) {/ line3Expected = /console\.log\(['"]He is unhappy['"]\);/ line4Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name isHappy and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable isHappy and negation operator, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'He is unhappy\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true if exercise.id is '1ne2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) #line 4 unless CodeChecker.hasIndentation(lines[3]) return TAPi18n.__ 'Error on line 4, you are missing indentation - tabulator or 2 spaces' line1Expected = /var isHappy = true;/ line2Expected = /var isHuman = true;/ line3Expected = /if \( {0,1}isHappy && isHuman {0,1}\) {/ line4Expected = /console\.log\(['"]Hello happy human['"]\);/ line5Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name isHappy and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name isHuman and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, write condition with variables isHappy and isHuman using operator &&, do you have space after if?' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, print \'Hello happy human\' with console.log(), check if the statement ends with semicolon' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, close if condition with }' success = true if exercise.id is '1ne3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) #line 4 unless CodeChecker.hasIndentation(lines[3]) return TAPi18n.__ 'Error on line 4, you are missing indentation - tabulator or 2 spaces' line1Expected = /var isHappy = true;/ line2Expected = /var isHuman = false;/ line3Expected = /if \( {0,1}isHappy \|\| isHuman {0,1}\) {/ line4Expected = /console\.log\(['"]You are happy or you are a human['"]\);/ line5Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name isHappy and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name isHuman and value false, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, write condition with variables isHappy and isHuman using operator ||, do you have space after if?' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, print \'You are happy or you are a human\' with console.log(), check if the statement ends with semicolon' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, close if condition with }' success = true ###################### # Truthy and valsey ###################### if exercise.id is '1oe1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var truthy = (true|["'].{1,}["']|[1-9][0-9]*|\{ {0,1}\}|\[ {0,1}\]);/ line2Expected = /if \( {0,1}truthy {0,1}(== true){0,1}\) {/ line3Expected = /console\.log\(['"]hello truthy['"]\);/ line4Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name truthy and truthy value, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable truthy, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'hello truthy\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true if exercise.id is '1oe2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var falsey = (false|["']["']|0|null|undefined|NaN);/ line2Expected = /if \( {0,1}falsey {0,1}(== false){0,1}\) {/ line3Expected = /console\.log\(['"]hello falsey['"]\);/ line4Expected = '}' if !(line1 is 'var falsey;' or line1Expected.test(line1)) return TAPi18n.__ 'Error on line 1, check if variable has name falsey and falsey value, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable falsey, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'hello falsey\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true if exercise.id is '1oe3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var falsey = (false|["']["']|0|null|undefined|NaN);/ line2Expected = /if \( {0,1}!falsey {0,1}\) {/ line3Expected = /console\.log\(['"]hello negated falsey['"]\);/ line4Expected = '}' if !(line1 is 'var falsey;' or line1Expected.test(line1)) return TAPi18n.__ 'Error on line 1, check if variable has name falsey and falsey value, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable falsey, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'hello falsey\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true ###################### # Loops - for ###################### if exercise.id is '1pe1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) #line 2 unless CodeChecker.hasIndentation(lines[1]) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /for \(var i = 0; i (<= 4|< 5); i\+\+\) {/ line2Expected = 'console.log(i);' line3Expected = '}' unless /i (<= 4|< 5)/.test(line1) return TAPi18n.__ 'Error on line 1, bad condition, the code will not run 5x' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if you have space after for keyword (for (..) {)' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print value of variable i with console.log, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' success = true if exercise.id is '1pe2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) #line 2 unless CodeChecker.hasIndentation(lines[1]) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /for \(var i = 5; i (>= 1|> 0); i--\) {/ line2Expected = 'console.log(i);' line3Expected = '}' unless /var i/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable does not have name i' unless /var i = 5/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable i has to have value 5' unless /i (>= 1|> 0)/.test(line1) return TAPi18n.__ 'Error on line 1, bad condition, the code will not run 5x' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if you have space after for keyword (for (..) {)' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print value of variable i with console.log, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' success = true if exercise.id is '1pe3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) #line 2 unless CodeChecker.hasIndentation(lines[1]) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /for \(var i = 0; i (<= 21|<= 20|< 21|< 22); (i \+= 2|i = i \+ 2)\) {/ line2Expected = 'console.log(i);' line3Expected = '}' unless /var i/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable does not have name i' unless /var i = 0/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable i has to have value 0' unless /i (<= 21|<= 20|< 21|< 22)/.test(line1) return TAPi18n.__ 'Error on line 1, bad condition, the loop will not end at 20' unless /(i \+= 2|i = i \+ 2)/.test(line1) return TAPi18n.__ 'Error on line 1, bad iteration step, you need to increment i by 2' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if you have space after for keyword (for (..) {)' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print value of variable i with console.log, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' success = true if exercise.id is '1pe4' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) #line 2 unless CodeChecker.hasIndentation(lines[1]) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /for \(var i = 1; i (<= 19|<= 20|< 20|< 21); (i \+= 2|i = i \+ 2)\) {/ line2Expected = 'console.log(i);' line3Expected = '}' unless /var i/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable does not have name i' unless /var i = 1/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable i has to have value 1' unless /i (<= 19|<= 20|< 20|< 21)/.test(line1) return TAPi18n.__ 'Error on line 1, bad condition, the loop will not end at 19' unless /(i \+= 2|i = i \+ 2)/.test(line1) return TAPi18n.__ 'Error on line 1, bad iteration step, you need to increment i by 2' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if you have space after for keyword (for (..) {)' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print value of variable i with console.log, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' success = true if exercise.id is '1pe5' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var bands = \[ {0,1}['"]Metallica['"], ['"]AC\/DC['"], ['"]Iron Maiden['"] {0,1}\]/ line2Expected = /for \(var i = 0; i (<= bands\.length - 1|< bands\.length); i\+\+\) {/ line3Expected = /console\.log\(bands\[i\]\);/ line4Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, read assignment for line 1 and try again. Do you have space and comma between array items? check if the statement ends with semicolon' unless /var i/.test(line2) return TAPi18n.__ 'Error on line 2, iteration variable does not have name i' unless /var i = 0/.test(line2) return TAPi18n.__ 'Error on line 2, iteration variable i has to have value 0' unless /i (<= bands\.length - 1|< bands\.length)/.test(line2) return TAPi18n.__ 'Error on line 2, bad condition, the loop will not end at last array item' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, bad for loop. Read assignment for line 2 and try again.' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print items from array bands with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true ###################### # Functions ###################### if exercise.id is '1qe1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = lines[1] line3 = lines[2] line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /function printNameAndAge\(name, age\) {/ line2Expected = /console\.log\(['"]Hi ['"] \+ name\);/ line3Expected = /console\.log\(['"]You are ['"] \+ age \+ ['"] years old['"]\);/ line4Expected = '}' line5Expected = /printNameAndAge\(["']Tom['"], 28\);/ unless /name/.test(line1) return TAPi18n.__ 'Error on line 1, parameter "name" is missing' unless /age/.test(line1) return TAPi18n.__ 'Error on line 1, parameter "age" is missing' unless /printNameAndAge/.test(line1) return TAPi18n.__ 'Error on line 1, function does not have name printNameAndAge' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if your code is according to conventions' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, read assignment for line 2 and try again, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, read assignment for line 3 and try again, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, read assignment for line 5 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1qe2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = lines[1] line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /function multiply\(a, b\) {/ line2Expected = /return a \* b;/ line3Expected = '}' line4Expected = /console.log\( {0,1}multiply\(5, 2\) {0,1}\);/ if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, define function with name multiply and parameters a and b' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, return a * b from function multiply, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, read assignment for line 4 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1qe3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = lines[1] line3 = lines[2] line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line6 = $.trim(lines[5]) unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3, 4) return TAPi18n.__ 'Error on line 3, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(lines[3]) return TAPi18n.__ 'Error on line 4, you are missing indentation - tabulator or 2 spaces' line1Expected = /function printArray\(arr\) {/ line2Expected = /for \(var i = 0; (i < arr\.length|i <= arr\.length - 1); i\+\+\) {/ line3Expected = /console\.log\( {0,1}arr\[i\]\ {0,1}\);/ line4Expected = '}' line5Expected = '}' line6Expected = /printArray\(\[5, 10, 15\]\);/ unless /printArray/.test(line1) return TAPi18n.__ 'Error on line 1, function does not have name printArray' unless /var i/.test(line2) return TAPi18n.__ 'Error on line 2, iteration variable must have name i' unless /var i = 0/.test(line2) return TAPi18n.__ 'Error on line 2, iteration variable must have value 0, check if your code is according to conventions' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if your code is according to conventions' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, define for loop, check if your code is according to conventions, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print item from array with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close loop with }' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, close function with }' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, call function printArray with parameter [5, 10, 15], check if the statement ends with semicolon' success = true ###################### # Objects ###################### if exercise.id is '1re1' lines = opts.code.split('\n') line1 = $.trim(lines[0]); line2 = lines[1]; line3 = lines[2] line4 = lines[3]; line5 = lines[4]; line6 = lines[5] line7 = lines[6]; line8 = lines[7]; line9 = lines[8] line10 = lines[9]; line11 = lines[10]; line12 = lines[11] line13 = lines[12] line1Expected = /var car = {/ line2Expected = /name: ["'].+['"],/ line3Expected = /speed: \d+,/ line4Expected = /accelerate: function\(\) {/ line5Expected = /(this\.speed\+\+|\+\+this\.speed|this\.speed = this\.speed \+ 1|this\.speed = 1 \+ this\.speed|this\.speed \+= 1);/ line6Expected = /},/ line7Expected = /toString: function\(\) {/ line8Expected = /return ["']Car ["'] \+ this\.name \+ ["'] has speed ['"] \+ this\.speed;/ line9Expected = /}/ line10Expected = /};/ line11Expected = /console\.log\( {0,1}car\.toString\(\) {0,1}\);/ line12Expected = /car\.accelerate\(\);/ line13Expected = /console\.log\( {0,1}car\.toString\(\) {0,1}\);/ unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line4) return TAPi18n.__ 'Error on line 4, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line5, 4) return TAPi18n.__ 'Error on line 5, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(line6) return TAPi18n.__ 'Error on line 6, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line7) return TAPi18n.__ 'Error on line 8, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line8) return TAPi18n.__ 'Error on line 8, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(line9) return TAPi18n.__ 'Error on line 9, you are missing indentation - tabulator or 2 spaces' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name car' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if property has name <i>name</i> and its value is string, are you missing comma?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if property has name <i>speed</i> and its value is integer, are you missing comma?' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, check if method has name <i>accelerate</i>' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, are you sure you are increasing speed property? check if the statement ends with semicolon' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, close <i>accelerate</i> method with },' if !line7Expected.test(line7) return TAPi18n.__ 'Error on line 7, check if method has name <i>toString</i>' if !line8Expected.test(line8) return TAPi18n.__ 'Error on line 8, read what <i>toString</i> should return and try again, check if the statement ends with semicolon' if !line9Expected.test(line9) return TAPi18n.__ 'Error on line 9, close <i>toString</i> method with }' if !line10Expected.test(line10) return TAPi18n.__ 'Error on line 10, close object with };, check if the statement ends with semicolon' if !line11Expected.test(line11) return TAPi18n.__ 'Error on line 11, read assignment for line 11 and try again, check if the statement ends with semicolon' if !line12Expected.test(line12) return TAPi18n.__ 'Error on line 12, read assignment for line 12 and try again, check if the statement ends with semicolon' if !line13Expected.test(line13) return TAPi18n.__ 'Error on line 13, read assignment for line 13 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1re2' lines = opts.code.split('\n') line1 = $.trim(lines[0]); line2 = lines[1]; line3 = lines[2] line4 = lines[3]; line5 = lines[4]; line6 = lines[5] line1Expected = /var person = {/ line2Expected = /name: ["'].+['"]/ line3Expected = /};/ line4Expected = /console\.log\(person\.name\);/ line5Expected = /person\.name = ["'].+['"];/ line6Expected = /console\.log\(person\.name\);/ unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name person' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if property has name <i>name</i> and its value is string, are you missing comma?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, close object with };' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, read assignment for line 4 and try again, check if the statement ends with semicolon' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, read assignment for line 5 and try again, check if the statement ends with semicolon' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, read assignment for line 6 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1re3' lines = opts.code.split('\n') line1 = $.trim(lines[0]); line2 = lines[1]; line3 = lines[2] line4 = lines[3]; line5 = lines[4]; line6 = lines[5] line7 = lines[6]; line8 = lines[7]; line1Expected = /var dog = {/ line2Expected = /name: ["'].+['"],/ line3Expected = /bark: function\(\) {/ line4Expected = /console\.log\(["']wof wof["']\);/ line5Expected = /}/ line6Expected = /};/ line7Expected = /console\.log\(dog\.name\);/ line8Expected = /dog\.bark\(\);/ unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line4, 4) return TAPi18n.__ 'Error on line 4, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(line5) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name dog' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if property has name <i>name</i> and its value is string, are you missing comma?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, define method with name <i>bark</i>' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, print "wof wof" with console.log(), check if the statement ends with semicolon' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, close method with }' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, close object with };' if !line7Expected.test(line7) return TAPi18n.__ 'Error on line 7, print name of the dog with console.log()' if !line8Expected.test(line8) return TAPi18n.__ 'Error on line 8, call method bark(), check if the statement ends with semicolon' success = true if exercise.id is '1re4' lines = opts.code.split('\n') line1 = $.trim(lines[0]); line2 = lines[1]; line3 = lines[2] line4 = lines[3]; line5 = lines[4]; line6 = lines[5] line7 = lines[6]; line8 = lines[7]; line9 = lines[8] line1Expected = /function Dog\(name\) {/ line2Expected = /this\.name = name;/ line3Expected = /this\.bark = function\(\) {/ line4Expected = /console\.log\(["']wof wof["']\);/ line5Expected = /};/ line6Expected = /}/ #accepts new Dog(), new Dog(''), new Dog('asdf...') line7Expected = /var dog = new Dog\((["'].*['"]){0,1}\);/ line8Expected = /console\.log\(dog\.name\);/ line9Expected = /dog\.bark\(\);/ unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line4, 4) return TAPi18n.__ 'Error on line 4, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(line5) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if function has name <i>Dog</i>. Check if it\'s written according to conventions.' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if property has name <i>name</i> and its value is parameter <i>name</i>, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, define method with name <i>bark</i>' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, print "wof wof" with console.log(), check if the statement ends with semicolon' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, close method with };' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, close object definition with }' if !line7Expected.test(line7) return TAPi18n.__ 'Error on line 7, read assignment for line 7 and try again' if !line8Expected.test(line8) return TAPi18n.__ 'Error on line 8, print name of the dog with console.log()' if !line9Expected.test(line9) return TAPi18n.__ 'Error on line 9, call method bark(), check if the statement ends with semicolon' success = true unless resultMsg or success resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' return resultMsg || success
57840
class @JSExercise ### # @param opts Object # lesson # exercise # code # @returns true on success, string message on failure ### @checkExercise: (opts) -> opts.code = $.trim(opts.code) exercise = opts.exercise lesson = opts.lesson success = false resultMsg = '' ###################### # Expressions ###################### if exercise.id is '1ce1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line1Expected = /console\.log\( {0,1}\({0,1} {0,1}1 \+ 2 {0,1}\){0,1} < 4 {0,1}\);/ if line1Expected.test(line1) success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1ce2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line1Expected = /console\.log\( {0,1}\({0,1} {0,1}2 \+ 3 {0,1}\){0,1} > 5 {0,1}\);/ if line1Expected.test(line1) success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1ce3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line1Expected = /console\.log\( {0,1}\({0,1}5 \+ 2 {0,1}\){0,1} <= \({0,1} {0,1}14 \/ 2 {0,1}\){0,1} {0,1}\);/ if line1Expected.test(line1) success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1ce4' lines = opts.code.split('\n') line1 = $.trim(lines[0]) #console.log(9 - 3 >= 2 * 3); #console.log((9 - 3) >= (2 * 3)); line1Expected = /console\.log\( {0,1}\({0,1} {0,1}9 \- 3 {0,1}\){0,1} >= \({0,1} {0,1}2 \* 3 {0,1}\){0,1} {0,1}\);/ if line1Expected.test(line1) success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' ############# # Arithmetic operators ############# if exercise.id is '1ie1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = /var i = 5;/ line2Expected = /(i\+\+;|\+\+i;)/ line3Expected = /console\.log\(i\);/ if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if the variable name is <i>i</i> and value is 5, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if you increment variable <i>i</i> with operator ++, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, read assignment for line 3 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1ie2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = /var i = 5;/ line2Expected = /(i--;|--i;)/ line3Expected = /console\.log\(i\);/ if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if the variable name is <i>i</i> and value is 5, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if you decrement variable <i>i</i> with operator --, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, read assignment for line 3 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1ie3' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('%') result = numbers[0] % numbers[1] if result is 2 success = true else return resultMsg = TAPi18n.__ "Expected result is 2 but your result is #{result}" ####################### # comparision operators ####################### if exercise.id is '1se1' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('<') result = parseInt(numbers[0]) < parseInt(numbers[1]) if result success = true else if result is false return TAPi18n.__ 'Result is false, it should be true' else return TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1se2' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('<=') result = parseInt(numbers[0]) <= parseInt(numbers[1]) if result success = true else if result is false return TAPi18n.__ 'Result is false, it should be true' else return TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1se3' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('>=') result = parseInt(numbers[0]) >= parseInt(numbers[1]) if result success = true else if result is false return TAPi18n.__ 'Result is false, it should be true' else return TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1se4' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('==') type1 = typeof numbers[0] if isNaN(parseInt(numbers[0])) return TAPi18n.__ "First argument should be number. #{type1} given" if numbers[1].indexOf("'") is -1 and numbers[1].indexOf('"') is -1 return TAPi18n.__ "Second argument should be string. Something like '2' or \"2\"" #strip quotes numbers[1] = numbers[1].replace(/[\'\"]/g, '') #use JS operator == result = `$.trim(numbers[0]) == $.trim(numbers[1])` if result success = true else if result is false return TAPi18n.__ 'Result is false, it should be true' else return TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' ###################### # Assignment operators ###################### if exercise.id is '1je1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line1Expected = 'var number = 1;' line2Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number", check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print variable number with console.log(), check if the statement ends with semicolon' if line1 is line1Expected and line2 is line2Expected success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1je2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = 'var number = 2;' line2Expected = 'number += 5;' line3Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number" and value 2, check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, add number 5 to variable number using operator +=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable number with console.log(), check if the statement ends with semicolon' if line1 is line1Expected and line2 is line2Expected and line3 is line3Expected success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1je3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = 'var number = 3;' line2Expected = 'number -= 1;' line3Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number" and value 3, check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, subtract number 1 from variable number using operator -=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable number with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1je4' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = 'var number = 4;' line2Expected = 'number *= 2;' line3Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number" and value 4, check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, multiply variable number by 2 using operator *=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable number with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1je5' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = 'var number = 5;' line2Expected = 'number /= 2;' line3Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number" and value 4, check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, divide variable number by 2 using operator /=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable number with console.log(), check if the statement ends with semicolon' success = true ###################### # Assignment operators ###################### if exercise.id is '1ke1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = /var someText = ['"]Lorem ipsum['"];/ line2Expected = /someText \+= ['"] dolor sit amet['"];/ line3Expected = 'console.log(someText);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "someText" and value "Lorem ipsum", check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, add text " dolor sit amet" to variable someText using operator +=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable someText with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1ke2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var fruit1 = ['"]apple['"];/ line2Expected = /var fruit2 = ['"]banana['"];/ line3Expected = /var appleAndBanana = fruit1 \+ ['"] and ['"] \+ fruit2;/ line4Expected = 'console.log(appleAndBanana);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "fruit1" and value "apple", check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "fruit2" and value "banana", check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, read assignment on Line 3 and try again.' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print variable appleAndBanana with console.log(), check if the statement ends with semicolon' success = true ###################### # Integer variables ###################### if exercise.id is '1fe1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var number1 = 45;/ line2Expected = /var number2 = 100;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'console.log(result);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 45, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 100, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print variable result with console.log(), check if the statement ends with semicolon' success = true ###################### # Float variables ###################### if exercise.id is '1ge1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var number1 = 0.55;/ line2Expected = /var number2 = 0.199;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'console.log(result);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 0.55, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 0.199, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print variable result with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1ge2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var number1 = 0.55;/ line2Expected = /var number2 = 0.199;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'console.log(result.toFixed(2));' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 0.55, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 0.199, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, round variable result to 2 decimal places and print it with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1ge3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line1Expected = /var number1 = 0.55;/ line2Expected = /var number2 = 0.199;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'var roundedResult = result.toFixed(2);' line5Expected = 'console.log(roundedResult + 3);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 0.55, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 0.199, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, check if variable has name "roundedResult" and value of rounded variable "result" to 2 decimal places, check if the statement ends with semicolon' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, print roundedResult + 3 with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1ge4' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line1Expected = /var number1 = 0.55;/ line2Expected = /var number2 = 0.199;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'var roundedResult = result.toFixed(2);' line5Expected = 'console.log(parseFloat(roundedResult) + 3);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 0.55, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 0.199, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, check if variable has name "roundedResult" and value of rounded variable "result" to 2 decimal places, check if the statement ends with semicolon' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, parse value of roundedResult and add 3 to the result. Print it with console.log(), check if the statement ends with semicolon' success = true ###################### # Arrays ###################### if exercise.id is '1le1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var numbers = \[ {0,1}\];/ line2Expected = /numbers\.push\(1\);/ line3Expected = /numbers\.push\(2\);/ line4Expected = 'console.log(numbers[0]);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "numbers" and is array, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, add value 1 to variable numbers with method push(), check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, add value 2 to variable numbers with method push(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print value 1 from array numbers with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1le2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var bands = \[ {0,1}['"]Metallica['"], ["']Iron Maiden["'] {0,1}\];/ line2Expected = /bands\.push\(["']AC\/DC["']\);/ line3Expected = 'console.log(bands[0]);' line4Expected = 'console.log(bands[2]);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "bands" and is array and you have space after comas, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, add value \'AC/DC\' to array bands with method push(), check if the statement ends with semicolon' if line3Expected != line3 return TAPi18n.__ 'Error on line 3, print the first item from array bands with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print the last item from array bands with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1le3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line1Expected = /var numbers = \[ {0,1}5, 8, 3\.3 {0,1}\];/ line2Expected = 'console.log(numbers[0] + numbers[1] + numbers[2]);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "numbers" and you have space after comas, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, first add number with index 0, then 1, then 2, check if you have space before and after + operator, check if the statement ends with semicolon' success = true ###################### # Conditions ###################### if exercise.id is '1me1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var fruit = ['"]banana['"];/ line2Expected = /if \( {0,1}fruit ={2,3} ['"]banana['"] {0,1}\) {/ line3Expected = /console\.log\(['"]variable fruit has value banana['"]\);/ line4Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "fruit" and value \'banana\', check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition which compares variable fruit with value \'banana\', do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'variable fruit has value banana\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' #line 1 if CodeChecker.hasIndentation(lines[0], 1) return TAPi18n.__ 'Error on line 1, this line should not have indentation!' #line 2 if CodeChecker.hasIndentation(lines[1], 1) return TAPi18n.__ 'Error on line 2, this line should not have indentation!' #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 4 if CodeChecker.hasIndentation(lines[3], 1) return TAPi18n.__ 'Error on line 4, this line should not have indentation!' success = true if exercise.id is '1me2' lines = opts.code.split('\n') #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 5 unless CodeChecker.hasIndentation(lines[4]) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line6 = $.trim(lines[5]) line1Expected = /var isHappy = true;/ #if (isHappy) { #or #if (isHappy == true) { line2Expected = /if \( {0,1}isHappy {0,1}(={2,3}){0,1} {0,1}(true){0,1} {0,1}\) {/ line3Expected = /console\.log\(['"]He is happy['"]\);/ line4Expected = '} else {' line5Expected = /console\.log\(['"]He is not happy['"]\);/ line6Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "isHappy" and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable isHappy, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'He is happy\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, you do not have correct else block, check how it is written in theory' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, print \'He is not happy\' with console.log(), check if the statement ends with semicolon' if line6 != line6Expected return TAPi18n.__ 'Error on line 6, close if condition with }' #line 1 if CodeChecker.hasIndentation(lines[0], 1) return TAPi18n.__ 'Error on line 1, this line should not have indentation!' #line 2 if CodeChecker.hasIndentation(lines[1], 1) return TAPi18n.__ 'Error on line 2, this line should not have indentation!' #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 4 if CodeChecker.hasIndentation(lines[3], 1) return TAPi18n.__ 'Error on line 4, this line should not have indentation!' #line 5 unless CodeChecker.hasIndentation(lines[4]) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' #line 6 if CodeChecker.hasIndentation(lines[5], 1) return TAPi18n.__ 'Error on line 6, this line should not have indentation!' success = true if exercise.id is '1me3' lines = opts.code.split('\n') #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 5 unless CodeChecker.hasIndentation(lines[4]) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' #line 7 unless CodeChecker.hasIndentation(lines[6]) return TAPi18n.__ 'Error on line 7, you are missing indentation - tabulator or 2 spaces' line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line6 = $.trim(lines[5]) line7 = $.trim(lines[6]) line8 = $.trim(lines[7]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 5 unless CodeChecker.hasIndentation(lines[4]) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' #line 7 unless CodeChecker.hasIndentation(lines[6]) return TAPi18n.__ 'Error on line 7, you are missing indentation - tabulator or 2 spaces' line1Expected = /var name = ['"]<NAME>['"];/ line2Expected = /if \( {0,1}name ={2,3} ['"]<NAME>['"] {0,1}\) {/ line3Expected = /console\.log\(['"]Hello <NAME>['"]\);/ line4Expected = /} else if \( {0,1}name ={2,3} ['"]<NAME>['"] {0,1}\) {/ line5Expected = /console\.log\(['"]Hello <NAME>['"]\);/ line6Expected = '} else {' line7Expected = /console\.log\(['"]Hello stranger['"]\);/ line8Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name <i>name</i> and value <b>\'<NAME>\'</b>, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition which compares variable name with value \'<NAME>\', do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'Hello <NAME>\' with console.log(), check if the statement ends with semicolon' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, you do not have correct else if block, check how it is written in theory' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, print \'Hello <NAME>\' with console.log(), check if the statement ends with semicolon' if line6 != line6Expected return TAPi18n.__ 'Error on line 6, you do not have correct else block, check how it is written in theory' if !line7Expected.test(line7) return TAPi18n.__ "Error on line 7, print 'Hello <NAME>' with console.log(), check if the statement ends with semicolon" if line8 != line8Expected return TAPi18n.__ 'Error on line 8, close if condition with }' success = true ###################### # Logical operators ###################### if exercise.id is '1ne1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var isHappy = true;/ line2Expected = /if \( {0,1}!isHappy {0,1}\) {/ line3Expected = /console\.log\(['"]He is unhappy['"]\);/ line4Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name isHappy and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable isHappy and negation operator, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'He is unhappy\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true if exercise.id is '1ne2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) #line 4 unless CodeChecker.hasIndentation(lines[3]) return TAPi18n.__ 'Error on line 4, you are missing indentation - tabulator or 2 spaces' line1Expected = /var isHappy = true;/ line2Expected = /var isHuman = true;/ line3Expected = /if \( {0,1}isHappy && isHuman {0,1}\) {/ line4Expected = /console\.log\(['"]Hello happy human['"]\);/ line5Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name isHappy and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name isHuman and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, write condition with variables isHappy and isHuman using operator &&, do you have space after if?' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, print \'Hello happy human\' with console.log(), check if the statement ends with semicolon' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, close if condition with }' success = true if exercise.id is '1ne3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) #line 4 unless CodeChecker.hasIndentation(lines[3]) return TAPi18n.__ 'Error on line 4, you are missing indentation - tabulator or 2 spaces' line1Expected = /var isHappy = true;/ line2Expected = /var isHuman = false;/ line3Expected = /if \( {0,1}isHappy \|\| isHuman {0,1}\) {/ line4Expected = /console\.log\(['"]You are happy or you are a human['"]\);/ line5Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name isHappy and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name isHuman and value false, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, write condition with variables isHappy and isHuman using operator ||, do you have space after if?' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, print \'You are happy or you are a human\' with console.log(), check if the statement ends with semicolon' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, close if condition with }' success = true ###################### # Truthy and valsey ###################### if exercise.id is '1oe1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var truthy = (true|["'].{1,}["']|[1-9][0-9]*|\{ {0,1}\}|\[ {0,1}\]);/ line2Expected = /if \( {0,1}truthy {0,1}(== true){0,1}\) {/ line3Expected = /console\.log\(['"]hello truthy['"]\);/ line4Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name truthy and truthy value, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable truthy, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'hello truthy\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true if exercise.id is '1oe2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var falsey = (false|["']["']|0|null|undefined|NaN);/ line2Expected = /if \( {0,1}falsey {0,1}(== false){0,1}\) {/ line3Expected = /console\.log\(['"]hello falsey['"]\);/ line4Expected = '}' if !(line1 is 'var falsey;' or line1Expected.test(line1)) return TAPi18n.__ 'Error on line 1, check if variable has name falsey and falsey value, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable falsey, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'hello falsey\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true if exercise.id is '1oe3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var falsey = (false|["']["']|0|null|undefined|NaN);/ line2Expected = /if \( {0,1}!falsey {0,1}\) {/ line3Expected = /console\.log\(['"]hello negated falsey['"]\);/ line4Expected = '}' if !(line1 is 'var falsey;' or line1Expected.test(line1)) return TAPi18n.__ 'Error on line 1, check if variable has name falsey and falsey value, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable falsey, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'hello falsey\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true ###################### # Loops - for ###################### if exercise.id is '1pe1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) #line 2 unless CodeChecker.hasIndentation(lines[1]) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /for \(var i = 0; i (<= 4|< 5); i\+\+\) {/ line2Expected = 'console.log(i);' line3Expected = '}' unless /i (<= 4|< 5)/.test(line1) return TAPi18n.__ 'Error on line 1, bad condition, the code will not run 5x' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if you have space after for keyword (for (..) {)' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print value of variable i with console.log, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' success = true if exercise.id is '1pe2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) #line 2 unless CodeChecker.hasIndentation(lines[1]) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /for \(var i = 5; i (>= 1|> 0); i--\) {/ line2Expected = 'console.log(i);' line3Expected = '}' unless /var i/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable does not have name i' unless /var i = 5/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable i has to have value 5' unless /i (>= 1|> 0)/.test(line1) return TAPi18n.__ 'Error on line 1, bad condition, the code will not run 5x' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if you have space after for keyword (for (..) {)' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print value of variable i with console.log, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' success = true if exercise.id is '1pe3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) #line 2 unless CodeChecker.hasIndentation(lines[1]) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /for \(var i = 0; i (<= 21|<= 20|< 21|< 22); (i \+= 2|i = i \+ 2)\) {/ line2Expected = 'console.log(i);' line3Expected = '}' unless /var i/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable does not have name i' unless /var i = 0/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable i has to have value 0' unless /i (<= 21|<= 20|< 21|< 22)/.test(line1) return TAPi18n.__ 'Error on line 1, bad condition, the loop will not end at 20' unless /(i \+= 2|i = i \+ 2)/.test(line1) return TAPi18n.__ 'Error on line 1, bad iteration step, you need to increment i by 2' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if you have space after for keyword (for (..) {)' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print value of variable i with console.log, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' success = true if exercise.id is '1pe4' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) #line 2 unless CodeChecker.hasIndentation(lines[1]) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /for \(var i = 1; i (<= 19|<= 20|< 20|< 21); (i \+= 2|i = i \+ 2)\) {/ line2Expected = 'console.log(i);' line3Expected = '}' unless /var i/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable does not have name i' unless /var i = 1/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable i has to have value 1' unless /i (<= 19|<= 20|< 20|< 21)/.test(line1) return TAPi18n.__ 'Error on line 1, bad condition, the loop will not end at 19' unless /(i \+= 2|i = i \+ 2)/.test(line1) return TAPi18n.__ 'Error on line 1, bad iteration step, you need to increment i by 2' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if you have space after for keyword (for (..) {)' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print value of variable i with console.log, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' success = true if exercise.id is '1pe5' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var bands = \[ {0,1}['"]Metallica['"], ['"]AC\/DC['"], ['"]Iron Maiden['"] {0,1}\]/ line2Expected = /for \(var i = 0; i (<= bands\.length - 1|< bands\.length); i\+\+\) {/ line3Expected = /console\.log\(bands\[i\]\);/ line4Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, read assignment for line 1 and try again. Do you have space and comma between array items? check if the statement ends with semicolon' unless /var i/.test(line2) return TAPi18n.__ 'Error on line 2, iteration variable does not have name i' unless /var i = 0/.test(line2) return TAPi18n.__ 'Error on line 2, iteration variable i has to have value 0' unless /i (<= bands\.length - 1|< bands\.length)/.test(line2) return TAPi18n.__ 'Error on line 2, bad condition, the loop will not end at last array item' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, bad for loop. Read assignment for line 2 and try again.' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print items from array bands with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true ###################### # Functions ###################### if exercise.id is '1qe1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = lines[1] line3 = lines[2] line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /function printNameAndAge\(name, age\) {/ line2Expected = /console\.log\(['"]Hi ['"] \+ name\);/ line3Expected = /console\.log\(['"]You are ['"] \+ age \+ ['"] years old['"]\);/ line4Expected = '}' line5Expected = /printNameAndAge\(["']<NAME>['"], 28\);/ unless /name/.test(line1) return TAPi18n.__ 'Error on line 1, parameter "name" is missing' unless /age/.test(line1) return TAPi18n.__ 'Error on line 1, parameter "age" is missing' unless /printNameAndAge/.test(line1) return TAPi18n.__ 'Error on line 1, function does not have name printNameAndAge' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if your code is according to conventions' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, read assignment for line 2 and try again, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, read assignment for line 3 and try again, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, read assignment for line 5 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1qe2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = lines[1] line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /function multiply\(a, b\) {/ line2Expected = /return a \* b;/ line3Expected = '}' line4Expected = /console.log\( {0,1}multiply\(5, 2\) {0,1}\);/ if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, define function with name multiply and parameters a and b' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, return a * b from function multiply, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, read assignment for line 4 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1qe3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = lines[1] line3 = lines[2] line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line6 = $.trim(lines[5]) unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3, 4) return TAPi18n.__ 'Error on line 3, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(lines[3]) return TAPi18n.__ 'Error on line 4, you are missing indentation - tabulator or 2 spaces' line1Expected = /function printArray\(arr\) {/ line2Expected = /for \(var i = 0; (i < arr\.length|i <= arr\.length - 1); i\+\+\) {/ line3Expected = /console\.log\( {0,1}arr\[i\]\ {0,1}\);/ line4Expected = '}' line5Expected = '}' line6Expected = /printArray\(\[5, 10, 15\]\);/ unless /printArray/.test(line1) return TAPi18n.__ 'Error on line 1, function does not have name printArray' unless /var i/.test(line2) return TAPi18n.__ 'Error on line 2, iteration variable must have name i' unless /var i = 0/.test(line2) return TAPi18n.__ 'Error on line 2, iteration variable must have value 0, check if your code is according to conventions' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if your code is according to conventions' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, define for loop, check if your code is according to conventions, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print item from array with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close loop with }' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, close function with }' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, call function printArray with parameter [5, 10, 15], check if the statement ends with semicolon' success = true ###################### # Objects ###################### if exercise.id is '1re1' lines = opts.code.split('\n') line1 = $.trim(lines[0]); line2 = lines[1]; line3 = lines[2] line4 = lines[3]; line5 = lines[4]; line6 = lines[5] line7 = lines[6]; line8 = lines[7]; line9 = lines[8] line10 = lines[9]; line11 = lines[10]; line12 = lines[11] line13 = lines[12] line1Expected = /var car = {/ line2Expected = /name: ["'].+['"],/ line3Expected = /speed: \d+,/ line4Expected = /accelerate: function\(\) {/ line5Expected = /(this\.speed\+\+|\+\+this\.speed|this\.speed = this\.speed \+ 1|this\.speed = 1 \+ this\.speed|this\.speed \+= 1);/ line6Expected = /},/ line7Expected = /toString: function\(\) {/ line8Expected = /return ["']Car ["'] \+ this\.name \+ ["'] has speed ['"] \+ this\.speed;/ line9Expected = /}/ line10Expected = /};/ line11Expected = /console\.log\( {0,1}car\.toString\(\) {0,1}\);/ line12Expected = /car\.accelerate\(\);/ line13Expected = /console\.log\( {0,1}car\.toString\(\) {0,1}\);/ unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line4) return TAPi18n.__ 'Error on line 4, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line5, 4) return TAPi18n.__ 'Error on line 5, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(line6) return TAPi18n.__ 'Error on line 6, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line7) return TAPi18n.__ 'Error on line 8, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line8) return TAPi18n.__ 'Error on line 8, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(line9) return TAPi18n.__ 'Error on line 9, you are missing indentation - tabulator or 2 spaces' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name car' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if property has name <i>name</i> and its value is string, are you missing comma?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if property has name <i>speed</i> and its value is integer, are you missing comma?' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, check if method has name <i>accelerate</i>' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, are you sure you are increasing speed property? check if the statement ends with semicolon' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, close <i>accelerate</i> method with },' if !line7Expected.test(line7) return TAPi18n.__ 'Error on line 7, check if method has name <i>toString</i>' if !line8Expected.test(line8) return TAPi18n.__ 'Error on line 8, read what <i>toString</i> should return and try again, check if the statement ends with semicolon' if !line9Expected.test(line9) return TAPi18n.__ 'Error on line 9, close <i>toString</i> method with }' if !line10Expected.test(line10) return TAPi18n.__ 'Error on line 10, close object with };, check if the statement ends with semicolon' if !line11Expected.test(line11) return TAPi18n.__ 'Error on line 11, read assignment for line 11 and try again, check if the statement ends with semicolon' if !line12Expected.test(line12) return TAPi18n.__ 'Error on line 12, read assignment for line 12 and try again, check if the statement ends with semicolon' if !line13Expected.test(line13) return TAPi18n.__ 'Error on line 13, read assignment for line 13 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1re2' lines = opts.code.split('\n') line1 = $.trim(lines[0]); line2 = lines[1]; line3 = lines[2] line4 = lines[3]; line5 = lines[4]; line6 = lines[5] line1Expected = /var person = {/ line2Expected = /name: ["'].+['"]/ line3Expected = /};/ line4Expected = /console\.log\(person\.name\);/ line5Expected = /person\.name = ["'].+['"];/ line6Expected = /console\.log\(person\.name\);/ unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name person' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if property has name <i>name</i> and its value is string, are you missing comma?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, close object with };' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, read assignment for line 4 and try again, check if the statement ends with semicolon' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, read assignment for line 5 and try again, check if the statement ends with semicolon' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, read assignment for line 6 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1re3' lines = opts.code.split('\n') line1 = $.trim(lines[0]); line2 = lines[1]; line3 = lines[2] line4 = lines[3]; line5 = lines[4]; line6 = lines[5] line7 = lines[6]; line8 = lines[7]; line1Expected = /var dog = {/ line2Expected = /name: ["'].+['"],/ line3Expected = /bark: function\(\) {/ line4Expected = /console\.log\(["']wof wof["']\);/ line5Expected = /}/ line6Expected = /};/ line7Expected = /console\.log\(dog\.name\);/ line8Expected = /dog\.bark\(\);/ unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line4, 4) return TAPi18n.__ 'Error on line 4, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(line5) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name dog' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if property has name <i>name</i> and its value is string, are you missing comma?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, define method with name <i>bark</i>' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, print "wof wof" with console.log(), check if the statement ends with semicolon' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, close method with }' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, close object with };' if !line7Expected.test(line7) return TAPi18n.__ 'Error on line 7, print name of the dog with console.log()' if !line8Expected.test(line8) return TAPi18n.__ 'Error on line 8, call method bark(), check if the statement ends with semicolon' success = true if exercise.id is '1re4' lines = opts.code.split('\n') line1 = $.trim(lines[0]); line2 = lines[1]; line3 = lines[2] line4 = lines[3]; line5 = lines[4]; line6 = lines[5] line7 = lines[6]; line8 = lines[7]; line9 = lines[8] line1Expected = /function Dog\(name\) {/ line2Expected = /this\.name = name;/ line3Expected = /this\.bark = function\(\) {/ line4Expected = /console\.log\(["']wof wof["']\);/ line5Expected = /};/ line6Expected = /}/ #accepts new Dog(), new Dog(''), new Dog('asdf...') line7Expected = /var dog = new Dog\((["'].*['"]){0,1}\);/ line8Expected = /console\.log\(dog\.name\);/ line9Expected = /dog\.bark\(\);/ unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line4, 4) return TAPi18n.__ 'Error on line 4, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(line5) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if function has name <i>Dog</i>. Check if it\'s written according to conventions.' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if property has name <i>name</i> and its value is parameter <i>name</i>, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, define method with name <i>bark</i>' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, print "wof wof" with console.log(), check if the statement ends with semicolon' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, close method with };' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, close object definition with }' if !line7Expected.test(line7) return TAPi18n.__ 'Error on line 7, read assignment for line 7 and try again' if !line8Expected.test(line8) return TAPi18n.__ 'Error on line 8, print name of the dog with console.log()' if !line9Expected.test(line9) return TAPi18n.__ 'Error on line 9, call method bark(), check if the statement ends with semicolon' success = true unless resultMsg or success resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' return resultMsg || success
true
class @JSExercise ### # @param opts Object # lesson # exercise # code # @returns true on success, string message on failure ### @checkExercise: (opts) -> opts.code = $.trim(opts.code) exercise = opts.exercise lesson = opts.lesson success = false resultMsg = '' ###################### # Expressions ###################### if exercise.id is '1ce1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line1Expected = /console\.log\( {0,1}\({0,1} {0,1}1 \+ 2 {0,1}\){0,1} < 4 {0,1}\);/ if line1Expected.test(line1) success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1ce2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line1Expected = /console\.log\( {0,1}\({0,1} {0,1}2 \+ 3 {0,1}\){0,1} > 5 {0,1}\);/ if line1Expected.test(line1) success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1ce3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line1Expected = /console\.log\( {0,1}\({0,1}5 \+ 2 {0,1}\){0,1} <= \({0,1} {0,1}14 \/ 2 {0,1}\){0,1} {0,1}\);/ if line1Expected.test(line1) success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1ce4' lines = opts.code.split('\n') line1 = $.trim(lines[0]) #console.log(9 - 3 >= 2 * 3); #console.log((9 - 3) >= (2 * 3)); line1Expected = /console\.log\( {0,1}\({0,1} {0,1}9 \- 3 {0,1}\){0,1} >= \({0,1} {0,1}2 \* 3 {0,1}\){0,1} {0,1}\);/ if line1Expected.test(line1) success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' ############# # Arithmetic operators ############# if exercise.id is '1ie1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = /var i = 5;/ line2Expected = /(i\+\+;|\+\+i;)/ line3Expected = /console\.log\(i\);/ if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if the variable name is <i>i</i> and value is 5, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if you increment variable <i>i</i> with operator ++, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, read assignment for line 3 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1ie2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = /var i = 5;/ line2Expected = /(i--;|--i;)/ line3Expected = /console\.log\(i\);/ if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if the variable name is <i>i</i> and value is 5, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if you decrement variable <i>i</i> with operator --, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, read assignment for line 3 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1ie3' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('%') result = numbers[0] % numbers[1] if result is 2 success = true else return resultMsg = TAPi18n.__ "Expected result is 2 but your result is #{result}" ####################### # comparision operators ####################### if exercise.id is '1se1' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('<') result = parseInt(numbers[0]) < parseInt(numbers[1]) if result success = true else if result is false return TAPi18n.__ 'Result is false, it should be true' else return TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1se2' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('<=') result = parseInt(numbers[0]) <= parseInt(numbers[1]) if result success = true else if result is false return TAPi18n.__ 'Result is false, it should be true' else return TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1se3' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('>=') result = parseInt(numbers[0]) >= parseInt(numbers[1]) if result success = true else if result is false return TAPi18n.__ 'Result is false, it should be true' else return TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1se4' #"x % y" expression = extractSubstring('(', ')', $.trim(opts.code)) #['x', 'y'] numbers = expression.split('==') type1 = typeof numbers[0] if isNaN(parseInt(numbers[0])) return TAPi18n.__ "First argument should be number. #{type1} given" if numbers[1].indexOf("'") is -1 and numbers[1].indexOf('"') is -1 return TAPi18n.__ "Second argument should be string. Something like '2' or \"2\"" #strip quotes numbers[1] = numbers[1].replace(/[\'\"]/g, '') #use JS operator == result = `$.trim(numbers[0]) == $.trim(numbers[1])` if result success = true else if result is false return TAPi18n.__ 'Result is false, it should be true' else return TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' ###################### # Assignment operators ###################### if exercise.id is '1je1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line1Expected = 'var number = 1;' line2Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number", check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print variable number with console.log(), check if the statement ends with semicolon' if line1 is line1Expected and line2 is line2Expected success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1je2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = 'var number = 2;' line2Expected = 'number += 5;' line3Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number" and value 2, check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, add number 5 to variable number using operator +=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable number with console.log(), check if the statement ends with semicolon' if line1 is line1Expected and line2 is line2Expected and line3 is line3Expected success = true else return resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' if exercise.id is '1je3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = 'var number = 3;' line2Expected = 'number -= 1;' line3Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number" and value 3, check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, subtract number 1 from variable number using operator -=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable number with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1je4' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = 'var number = 4;' line2Expected = 'number *= 2;' line3Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number" and value 4, check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, multiply variable number by 2 using operator *=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable number with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1je5' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = 'var number = 5;' line2Expected = 'number /= 2;' line3Expected = 'console.log(number);' if line1 != line1Expected return TAPi18n.__ 'Error on line 1, check if variable has name "number" and value 4, check spaces before and after assignment operator, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, divide variable number by 2 using operator /=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable number with console.log(), check if the statement ends with semicolon' success = true ###################### # Assignment operators ###################### if exercise.id is '1ke1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line1Expected = /var someText = ['"]Lorem ipsum['"];/ line2Expected = /someText \+= ['"] dolor sit amet['"];/ line3Expected = 'console.log(someText);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "someText" and value "Lorem ipsum", check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, add text " dolor sit amet" to variable someText using operator +=, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, print variable someText with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1ke2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var fruit1 = ['"]apple['"];/ line2Expected = /var fruit2 = ['"]banana['"];/ line3Expected = /var appleAndBanana = fruit1 \+ ['"] and ['"] \+ fruit2;/ line4Expected = 'console.log(appleAndBanana);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "fruit1" and value "apple", check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "fruit2" and value "banana", check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, read assignment on Line 3 and try again.' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print variable appleAndBanana with console.log(), check if the statement ends with semicolon' success = true ###################### # Integer variables ###################### if exercise.id is '1fe1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var number1 = 45;/ line2Expected = /var number2 = 100;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'console.log(result);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 45, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 100, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print variable result with console.log(), check if the statement ends with semicolon' success = true ###################### # Float variables ###################### if exercise.id is '1ge1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var number1 = 0.55;/ line2Expected = /var number2 = 0.199;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'console.log(result);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 0.55, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 0.199, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print variable result with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1ge2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var number1 = 0.55;/ line2Expected = /var number2 = 0.199;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'console.log(result.toFixed(2));' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 0.55, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 0.199, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, round variable result to 2 decimal places and print it with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1ge3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line1Expected = /var number1 = 0.55;/ line2Expected = /var number2 = 0.199;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'var roundedResult = result.toFixed(2);' line5Expected = 'console.log(roundedResult + 3);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 0.55, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 0.199, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, check if variable has name "roundedResult" and value of rounded variable "result" to 2 decimal places, check if the statement ends with semicolon' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, print roundedResult + 3 with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1ge4' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line1Expected = /var number1 = 0.55;/ line2Expected = /var number2 = 0.199;/ line3Expected = /var result = number1 \+ number2;/ line4Expected = 'var roundedResult = result.toFixed(2);' line5Expected = 'console.log(parseFloat(roundedResult) + 3);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "number1" and value 0.55, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name "number2" and value 0.199, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if variable has name "result" and value number1 + number2, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, check if variable has name "roundedResult" and value of rounded variable "result" to 2 decimal places, check if the statement ends with semicolon' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, parse value of roundedResult and add 3 to the result. Print it with console.log(), check if the statement ends with semicolon' success = true ###################### # Arrays ###################### if exercise.id is '1le1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var numbers = \[ {0,1}\];/ line2Expected = /numbers\.push\(1\);/ line3Expected = /numbers\.push\(2\);/ line4Expected = 'console.log(numbers[0]);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "numbers" and is array, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, add value 1 to variable numbers with method push(), check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, add value 2 to variable numbers with method push(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print value 1 from array numbers with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1le2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var bands = \[ {0,1}['"]Metallica['"], ["']Iron Maiden["'] {0,1}\];/ line2Expected = /bands\.push\(["']AC\/DC["']\);/ line3Expected = 'console.log(bands[0]);' line4Expected = 'console.log(bands[2]);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "bands" and is array and you have space after comas, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, add value \'AC/DC\' to array bands with method push(), check if the statement ends with semicolon' if line3Expected != line3 return TAPi18n.__ 'Error on line 3, print the first item from array bands with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, print the last item from array bands with console.log(), check if the statement ends with semicolon' success = true if exercise.id is '1le3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line1Expected = /var numbers = \[ {0,1}5, 8, 3\.3 {0,1}\];/ line2Expected = 'console.log(numbers[0] + numbers[1] + numbers[2]);' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "numbers" and you have space after comas, check if the statement ends with semicolon' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, first add number with index 0, then 1, then 2, check if you have space before and after + operator, check if the statement ends with semicolon' success = true ###################### # Conditions ###################### if exercise.id is '1me1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line1Expected = /var fruit = ['"]banana['"];/ line2Expected = /if \( {0,1}fruit ={2,3} ['"]banana['"] {0,1}\) {/ line3Expected = /console\.log\(['"]variable fruit has value banana['"]\);/ line4Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "fruit" and value \'banana\', check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition which compares variable fruit with value \'banana\', do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'variable fruit has value banana\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' #line 1 if CodeChecker.hasIndentation(lines[0], 1) return TAPi18n.__ 'Error on line 1, this line should not have indentation!' #line 2 if CodeChecker.hasIndentation(lines[1], 1) return TAPi18n.__ 'Error on line 2, this line should not have indentation!' #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 4 if CodeChecker.hasIndentation(lines[3], 1) return TAPi18n.__ 'Error on line 4, this line should not have indentation!' success = true if exercise.id is '1me2' lines = opts.code.split('\n') #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 5 unless CodeChecker.hasIndentation(lines[4]) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line6 = $.trim(lines[5]) line1Expected = /var isHappy = true;/ #if (isHappy) { #or #if (isHappy == true) { line2Expected = /if \( {0,1}isHappy {0,1}(={2,3}){0,1} {0,1}(true){0,1} {0,1}\) {/ line3Expected = /console\.log\(['"]He is happy['"]\);/ line4Expected = '} else {' line5Expected = /console\.log\(['"]He is not happy['"]\);/ line6Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name "isHappy" and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable isHappy, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'He is happy\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, you do not have correct else block, check how it is written in theory' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, print \'He is not happy\' with console.log(), check if the statement ends with semicolon' if line6 != line6Expected return TAPi18n.__ 'Error on line 6, close if condition with }' #line 1 if CodeChecker.hasIndentation(lines[0], 1) return TAPi18n.__ 'Error on line 1, this line should not have indentation!' #line 2 if CodeChecker.hasIndentation(lines[1], 1) return TAPi18n.__ 'Error on line 2, this line should not have indentation!' #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 4 if CodeChecker.hasIndentation(lines[3], 1) return TAPi18n.__ 'Error on line 4, this line should not have indentation!' #line 5 unless CodeChecker.hasIndentation(lines[4]) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' #line 6 if CodeChecker.hasIndentation(lines[5], 1) return TAPi18n.__ 'Error on line 6, this line should not have indentation!' success = true if exercise.id is '1me3' lines = opts.code.split('\n') #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 5 unless CodeChecker.hasIndentation(lines[4]) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' #line 7 unless CodeChecker.hasIndentation(lines[6]) return TAPi18n.__ 'Error on line 7, you are missing indentation - tabulator or 2 spaces' line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line6 = $.trim(lines[5]) line7 = $.trim(lines[6]) line8 = $.trim(lines[7]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' #line 5 unless CodeChecker.hasIndentation(lines[4]) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' #line 7 unless CodeChecker.hasIndentation(lines[6]) return TAPi18n.__ 'Error on line 7, you are missing indentation - tabulator or 2 spaces' line1Expected = /var name = ['"]PI:NAME:<NAME>END_PI['"];/ line2Expected = /if \( {0,1}name ={2,3} ['"]PI:NAME:<NAME>END_PI['"] {0,1}\) {/ line3Expected = /console\.log\(['"]Hello PI:NAME:<NAME>END_PI['"]\);/ line4Expected = /} else if \( {0,1}name ={2,3} ['"]PI:NAME:<NAME>END_PI['"] {0,1}\) {/ line5Expected = /console\.log\(['"]Hello PI:NAME:<NAME>END_PI['"]\);/ line6Expected = '} else {' line7Expected = /console\.log\(['"]Hello stranger['"]\);/ line8Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name <i>name</i> and value <b>\'PI:NAME:<NAME>END_PI\'</b>, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition which compares variable name with value \'PI:NAME:<NAME>END_PI\', do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'Hello PI:NAME:<NAME>END_PI\' with console.log(), check if the statement ends with semicolon' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, you do not have correct else if block, check how it is written in theory' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, print \'Hello PI:NAME:<NAME>END_PI\' with console.log(), check if the statement ends with semicolon' if line6 != line6Expected return TAPi18n.__ 'Error on line 6, you do not have correct else block, check how it is written in theory' if !line7Expected.test(line7) return TAPi18n.__ "Error on line 7, print 'Hello PI:NAME:<NAME>END_PI' with console.log(), check if the statement ends with semicolon" if line8 != line8Expected return TAPi18n.__ 'Error on line 8, close if condition with }' success = true ###################### # Logical operators ###################### if exercise.id is '1ne1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var isHappy = true;/ line2Expected = /if \( {0,1}!isHappy {0,1}\) {/ line3Expected = /console\.log\(['"]He is unhappy['"]\);/ line4Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name isHappy and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable isHappy and negation operator, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'He is unhappy\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true if exercise.id is '1ne2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) #line 4 unless CodeChecker.hasIndentation(lines[3]) return TAPi18n.__ 'Error on line 4, you are missing indentation - tabulator or 2 spaces' line1Expected = /var isHappy = true;/ line2Expected = /var isHuman = true;/ line3Expected = /if \( {0,1}isHappy && isHuman {0,1}\) {/ line4Expected = /console\.log\(['"]Hello happy human['"]\);/ line5Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name isHappy and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name isHuman and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, write condition with variables isHappy and isHuman using operator &&, do you have space after if?' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, print \'Hello happy human\' with console.log(), check if the statement ends with semicolon' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, close if condition with }' success = true if exercise.id is '1ne3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) #line 4 unless CodeChecker.hasIndentation(lines[3]) return TAPi18n.__ 'Error on line 4, you are missing indentation - tabulator or 2 spaces' line1Expected = /var isHappy = true;/ line2Expected = /var isHuman = false;/ line3Expected = /if \( {0,1}isHappy \|\| isHuman {0,1}\) {/ line4Expected = /console\.log\(['"]You are happy or you are a human['"]\);/ line5Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name isHappy and value true, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if variable has name isHuman and value false, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, write condition with variables isHappy and isHuman using operator ||, do you have space after if?' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, print \'You are happy or you are a human\' with console.log(), check if the statement ends with semicolon' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, close if condition with }' success = true ###################### # Truthy and valsey ###################### if exercise.id is '1oe1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var truthy = (true|["'].{1,}["']|[1-9][0-9]*|\{ {0,1}\}|\[ {0,1}\]);/ line2Expected = /if \( {0,1}truthy {0,1}(== true){0,1}\) {/ line3Expected = /console\.log\(['"]hello truthy['"]\);/ line4Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name truthy and truthy value, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable truthy, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'hello truthy\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true if exercise.id is '1oe2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var falsey = (false|["']["']|0|null|undefined|NaN);/ line2Expected = /if \( {0,1}falsey {0,1}(== false){0,1}\) {/ line3Expected = /console\.log\(['"]hello falsey['"]\);/ line4Expected = '}' if !(line1 is 'var falsey;' or line1Expected.test(line1)) return TAPi18n.__ 'Error on line 1, check if variable has name falsey and falsey value, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable falsey, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'hello falsey\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true if exercise.id is '1oe3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var falsey = (false|["']["']|0|null|undefined|NaN);/ line2Expected = /if \( {0,1}!falsey {0,1}\) {/ line3Expected = /console\.log\(['"]hello negated falsey['"]\);/ line4Expected = '}' if !(line1 is 'var falsey;' or line1Expected.test(line1)) return TAPi18n.__ 'Error on line 1, check if variable has name falsey and falsey value, check spaces before and after assignment operator, check if the statement ends with semicolon' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, write condition using variable falsey, do you have space after if?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print \'hello falsey\' with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true ###################### # Loops - for ###################### if exercise.id is '1pe1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) #line 2 unless CodeChecker.hasIndentation(lines[1]) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /for \(var i = 0; i (<= 4|< 5); i\+\+\) {/ line2Expected = 'console.log(i);' line3Expected = '}' unless /i (<= 4|< 5)/.test(line1) return TAPi18n.__ 'Error on line 1, bad condition, the code will not run 5x' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if you have space after for keyword (for (..) {)' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print value of variable i with console.log, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' success = true if exercise.id is '1pe2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) #line 2 unless CodeChecker.hasIndentation(lines[1]) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /for \(var i = 5; i (>= 1|> 0); i--\) {/ line2Expected = 'console.log(i);' line3Expected = '}' unless /var i/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable does not have name i' unless /var i = 5/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable i has to have value 5' unless /i (>= 1|> 0)/.test(line1) return TAPi18n.__ 'Error on line 1, bad condition, the code will not run 5x' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if you have space after for keyword (for (..) {)' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print value of variable i with console.log, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' success = true if exercise.id is '1pe3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) #line 2 unless CodeChecker.hasIndentation(lines[1]) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /for \(var i = 0; i (<= 21|<= 20|< 21|< 22); (i \+= 2|i = i \+ 2)\) {/ line2Expected = 'console.log(i);' line3Expected = '}' unless /var i/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable does not have name i' unless /var i = 0/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable i has to have value 0' unless /i (<= 21|<= 20|< 21|< 22)/.test(line1) return TAPi18n.__ 'Error on line 1, bad condition, the loop will not end at 20' unless /(i \+= 2|i = i \+ 2)/.test(line1) return TAPi18n.__ 'Error on line 1, bad iteration step, you need to increment i by 2' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if you have space after for keyword (for (..) {)' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print value of variable i with console.log, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' success = true if exercise.id is '1pe4' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) #line 2 unless CodeChecker.hasIndentation(lines[1]) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /for \(var i = 1; i (<= 19|<= 20|< 20|< 21); (i \+= 2|i = i \+ 2)\) {/ line2Expected = 'console.log(i);' line3Expected = '}' unless /var i/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable does not have name i' unless /var i = 1/.test(line1) return TAPi18n.__ 'Error on line 1, iteration variable i has to have value 1' unless /i (<= 19|<= 20|< 20|< 21)/.test(line1) return TAPi18n.__ 'Error on line 1, bad condition, the loop will not end at 19' unless /(i \+= 2|i = i \+ 2)/.test(line1) return TAPi18n.__ 'Error on line 1, bad iteration step, you need to increment i by 2' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if you have space after for keyword (for (..) {)' if line2 != line2Expected return TAPi18n.__ 'Error on line 2, print value of variable i with console.log, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' success = true if exercise.id is '1pe5' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = $.trim(lines[1]) line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) #line 3 unless CodeChecker.hasIndentation(lines[2]) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /var bands = \[ {0,1}['"]Metallica['"], ['"]AC\/DC['"], ['"]Iron Maiden['"] {0,1}\]/ line2Expected = /for \(var i = 0; i (<= bands\.length - 1|< bands\.length); i\+\+\) {/ line3Expected = /console\.log\(bands\[i\]\);/ line4Expected = '}' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, read assignment for line 1 and try again. Do you have space and comma between array items? check if the statement ends with semicolon' unless /var i/.test(line2) return TAPi18n.__ 'Error on line 2, iteration variable does not have name i' unless /var i = 0/.test(line2) return TAPi18n.__ 'Error on line 2, iteration variable i has to have value 0' unless /i (<= bands\.length - 1|< bands\.length)/.test(line2) return TAPi18n.__ 'Error on line 2, bad condition, the loop will not end at last array item' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, bad for loop. Read assignment for line 2 and try again.' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print items from array bands with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' success = true ###################### # Functions ###################### if exercise.id is '1qe1' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = lines[1] line3 = lines[2] line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' line1Expected = /function printNameAndAge\(name, age\) {/ line2Expected = /console\.log\(['"]Hi ['"] \+ name\);/ line3Expected = /console\.log\(['"]You are ['"] \+ age \+ ['"] years old['"]\);/ line4Expected = '}' line5Expected = /printNameAndAge\(["']PI:NAME:<NAME>END_PI['"], 28\);/ unless /name/.test(line1) return TAPi18n.__ 'Error on line 1, parameter "name" is missing' unless /age/.test(line1) return TAPi18n.__ 'Error on line 1, parameter "age" is missing' unless /printNameAndAge/.test(line1) return TAPi18n.__ 'Error on line 1, function does not have name printNameAndAge' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if your code is according to conventions' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, read assignment for line 2 and try again, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, read assignment for line 3 and try again, check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close if condition with }' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, read assignment for line 5 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1qe2' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = lines[1] line3 = $.trim(lines[2]) line4 = $.trim(lines[3]) unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' line1Expected = /function multiply\(a, b\) {/ line2Expected = /return a \* b;/ line3Expected = '}' line4Expected = /console.log\( {0,1}multiply\(5, 2\) {0,1}\);/ if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, define function with name multiply and parameters a and b' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, return a * b from function multiply, check if the statement ends with semicolon' if line3 != line3Expected return TAPi18n.__ 'Error on line 3, close if condition with }' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, read assignment for line 4 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1qe3' lines = opts.code.split('\n') line1 = $.trim(lines[0]) line2 = lines[1] line3 = lines[2] line4 = $.trim(lines[3]) line5 = $.trim(lines[4]) line6 = $.trim(lines[5]) unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3, 4) return TAPi18n.__ 'Error on line 3, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(lines[3]) return TAPi18n.__ 'Error on line 4, you are missing indentation - tabulator or 2 spaces' line1Expected = /function printArray\(arr\) {/ line2Expected = /for \(var i = 0; (i < arr\.length|i <= arr\.length - 1); i\+\+\) {/ line3Expected = /console\.log\( {0,1}arr\[i\]\ {0,1}\);/ line4Expected = '}' line5Expected = '}' line6Expected = /printArray\(\[5, 10, 15\]\);/ unless /printArray/.test(line1) return TAPi18n.__ 'Error on line 1, function does not have name printArray' unless /var i/.test(line2) return TAPi18n.__ 'Error on line 2, iteration variable must have name i' unless /var i = 0/.test(line2) return TAPi18n.__ 'Error on line 2, iteration variable must have value 0, check if your code is according to conventions' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if your code is according to conventions' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, define for loop, check if your code is according to conventions, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, print item from array with console.log(), check if the statement ends with semicolon' if line4 != line4Expected return TAPi18n.__ 'Error on line 4, close loop with }' if line5 != line5Expected return TAPi18n.__ 'Error on line 5, close function with }' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, call function printArray with parameter [5, 10, 15], check if the statement ends with semicolon' success = true ###################### # Objects ###################### if exercise.id is '1re1' lines = opts.code.split('\n') line1 = $.trim(lines[0]); line2 = lines[1]; line3 = lines[2] line4 = lines[3]; line5 = lines[4]; line6 = lines[5] line7 = lines[6]; line8 = lines[7]; line9 = lines[8] line10 = lines[9]; line11 = lines[10]; line12 = lines[11] line13 = lines[12] line1Expected = /var car = {/ line2Expected = /name: ["'].+['"],/ line3Expected = /speed: \d+,/ line4Expected = /accelerate: function\(\) {/ line5Expected = /(this\.speed\+\+|\+\+this\.speed|this\.speed = this\.speed \+ 1|this\.speed = 1 \+ this\.speed|this\.speed \+= 1);/ line6Expected = /},/ line7Expected = /toString: function\(\) {/ line8Expected = /return ["']Car ["'] \+ this\.name \+ ["'] has speed ['"] \+ this\.speed;/ line9Expected = /}/ line10Expected = /};/ line11Expected = /console\.log\( {0,1}car\.toString\(\) {0,1}\);/ line12Expected = /car\.accelerate\(\);/ line13Expected = /console\.log\( {0,1}car\.toString\(\) {0,1}\);/ unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line4) return TAPi18n.__ 'Error on line 4, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line5, 4) return TAPi18n.__ 'Error on line 5, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(line6) return TAPi18n.__ 'Error on line 6, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line7) return TAPi18n.__ 'Error on line 8, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line8) return TAPi18n.__ 'Error on line 8, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(line9) return TAPi18n.__ 'Error on line 9, you are missing indentation - tabulator or 2 spaces' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name car' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if property has name <i>name</i> and its value is string, are you missing comma?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, check if property has name <i>speed</i> and its value is integer, are you missing comma?' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, check if method has name <i>accelerate</i>' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, are you sure you are increasing speed property? check if the statement ends with semicolon' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, close <i>accelerate</i> method with },' if !line7Expected.test(line7) return TAPi18n.__ 'Error on line 7, check if method has name <i>toString</i>' if !line8Expected.test(line8) return TAPi18n.__ 'Error on line 8, read what <i>toString</i> should return and try again, check if the statement ends with semicolon' if !line9Expected.test(line9) return TAPi18n.__ 'Error on line 9, close <i>toString</i> method with }' if !line10Expected.test(line10) return TAPi18n.__ 'Error on line 10, close object with };, check if the statement ends with semicolon' if !line11Expected.test(line11) return TAPi18n.__ 'Error on line 11, read assignment for line 11 and try again, check if the statement ends with semicolon' if !line12Expected.test(line12) return TAPi18n.__ 'Error on line 12, read assignment for line 12 and try again, check if the statement ends with semicolon' if !line13Expected.test(line13) return TAPi18n.__ 'Error on line 13, read assignment for line 13 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1re2' lines = opts.code.split('\n') line1 = $.trim(lines[0]); line2 = lines[1]; line3 = lines[2] line4 = lines[3]; line5 = lines[4]; line6 = lines[5] line1Expected = /var person = {/ line2Expected = /name: ["'].+['"]/ line3Expected = /};/ line4Expected = /console\.log\(person\.name\);/ line5Expected = /person\.name = ["'].+['"];/ line6Expected = /console\.log\(person\.name\);/ unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name person' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if property has name <i>name</i> and its value is string, are you missing comma?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, close object with };' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, read assignment for line 4 and try again, check if the statement ends with semicolon' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, read assignment for line 5 and try again, check if the statement ends with semicolon' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, read assignment for line 6 and try again, check if the statement ends with semicolon' success = true if exercise.id is '1re3' lines = opts.code.split('\n') line1 = $.trim(lines[0]); line2 = lines[1]; line3 = lines[2] line4 = lines[3]; line5 = lines[4]; line6 = lines[5] line7 = lines[6]; line8 = lines[7]; line1Expected = /var dog = {/ line2Expected = /name: ["'].+['"],/ line3Expected = /bark: function\(\) {/ line4Expected = /console\.log\(["']wof wof["']\);/ line5Expected = /}/ line6Expected = /};/ line7Expected = /console\.log\(dog\.name\);/ line8Expected = /dog\.bark\(\);/ unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line4, 4) return TAPi18n.__ 'Error on line 4, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(line5) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if variable has name dog' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if property has name <i>name</i> and its value is string, are you missing comma?' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, define method with name <i>bark</i>' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, print "wof wof" with console.log(), check if the statement ends with semicolon' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, close method with }' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, close object with };' if !line7Expected.test(line7) return TAPi18n.__ 'Error on line 7, print name of the dog with console.log()' if !line8Expected.test(line8) return TAPi18n.__ 'Error on line 8, call method bark(), check if the statement ends with semicolon' success = true if exercise.id is '1re4' lines = opts.code.split('\n') line1 = $.trim(lines[0]); line2 = lines[1]; line3 = lines[2] line4 = lines[3]; line5 = lines[4]; line6 = lines[5] line7 = lines[6]; line8 = lines[7]; line9 = lines[8] line1Expected = /function Dog\(name\) {/ line2Expected = /this\.name = name;/ line3Expected = /this\.bark = function\(\) {/ line4Expected = /console\.log\(["']wof wof["']\);/ line5Expected = /};/ line6Expected = /}/ #accepts new Dog(), new Dog(''), new Dog('asdf...') line7Expected = /var dog = new Dog\((["'].*['"]){0,1}\);/ line8Expected = /console\.log\(dog\.name\);/ line9Expected = /dog\.bark\(\);/ unless CodeChecker.hasIndentation(line2) return TAPi18n.__ 'Error on line 2, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line3) return TAPi18n.__ 'Error on line 3, you are missing indentation - tabulator or 2 spaces' unless CodeChecker.hasIndentation(line4, 4) return TAPi18n.__ 'Error on line 4, you are missing indentation - 2x tabulator or 4 spaces' unless CodeChecker.hasIndentation(line5) return TAPi18n.__ 'Error on line 5, you are missing indentation - tabulator or 2 spaces' if !line1Expected.test(line1) return TAPi18n.__ 'Error on line 1, check if function has name <i>Dog</i>. Check if it\'s written according to conventions.' if !line2Expected.test(line2) return TAPi18n.__ 'Error on line 2, check if property has name <i>name</i> and its value is parameter <i>name</i>, check if the statement ends with semicolon' if !line3Expected.test(line3) return TAPi18n.__ 'Error on line 3, define method with name <i>bark</i>' if !line4Expected.test(line4) return TAPi18n.__ 'Error on line 4, print "wof wof" with console.log(), check if the statement ends with semicolon' if !line5Expected.test(line5) return TAPi18n.__ 'Error on line 5, close method with };' if !line6Expected.test(line6) return TAPi18n.__ 'Error on line 6, close object definition with }' if !line7Expected.test(line7) return TAPi18n.__ 'Error on line 7, read assignment for line 7 and try again' if !line8Expected.test(line8) return TAPi18n.__ 'Error on line 8, print name of the dog with console.log()' if !line9Expected.test(line9) return TAPi18n.__ 'Error on line 9, call method bark(), check if the statement ends with semicolon' success = true unless resultMsg or success resultMsg = TAPi18n.__ 'Read assignment and try again, you can ask for help if you are lost' return resultMsg || success
[ { "context": "Select Box Enhancer for jQuery and Prototype\n// by Patrick Filler for Harvest, http://getharvest.com\n//\n// Version ", "end": 291, "score": 0.999852180480957, "start": 277, "tag": "NAME", "value": "Patrick Filler" }, { "context": "g.version %>\n// Full source at https://github.com/harvesthq/chosen\n// Copyright (c) 2011 Harvest http://getha", "end": 406, "score": 0.9936432838439941, "start": 397, "tag": "USERNAME", "value": "harvesthq" }, { "context": "etharvest.com\n\n// MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md\n// This file is gen", "end": 511, "score": 0.9817917346954346, "start": 502, "tag": "USERNAME", "value": "harvesthq" }, { "context": "2013 by Harvest | MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md */\\n\"\n\n concat:\n", "end": 737, "score": 0.9958510398864746, "start": 728, "tag": "USERNAME", "value": "harvesthq" } ]
Gruntfile.coffee
michaelBenin/chosen
1
module.exports = (grunt) -> version = -> grunt.file.readJSON("package.json").version version_tag = -> "v#{version()}" grunt.initConfig pkg: grunt.file.readJSON("package.json") comments: """ // Chosen, a Select Box Enhancer for jQuery and Prototype // by Patrick Filler for Harvest, http://getharvest.com // // Version <%= pkg.version %> // Full source at https://github.com/harvesthq/chosen // Copyright (c) 2011 Harvest http://getharvest.com // MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md // This file is generated by `grunt build`, do not edit it by hand.\n """ minified_comments: "/* Chosen #{version_tag()} | (c) 2011-2013 by Harvest | MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md */\n" concat: options: banner: "<%= comments %>" jquery: src: ["public/chosen.jquery.js"] dest: "public/chosen.jquery.js" proto: src: ["public/chosen.proto.js"] dest: "public/chosen.proto.js" coffee: compile: files: 'public/chosen.jquery.js': ['coffee/lib/select-parser.coffee', 'coffee/lib/abstract-chosen.coffee', 'coffee/chosen.jquery.coffee'] 'public/chosen.proto.js': ['coffee/lib/select-parser.coffee', 'coffee/lib/abstract-chosen.coffee', 'coffee/chosen.proto.coffee'] uglify: options: mangle: except: ['jQuery', 'AbstractChosen', 'Chosen', 'SelectParser'] banner: "<%= minified_comments %>" minified_chosen_js: files: 'public/chosen.jquery.min.js': ['public/chosen.jquery.js'] 'public/chosen.proto.min.js': ['public/chosen.proto.js'] cssmin: minified_chosen_css: src: 'public/chosen.css' dest: 'public/chosen.min.css' watch: scripts: files: ['coffee/**/*.coffee'] tasks: ['build'] copy: dist: files: [ { cwd: "public", src: ["index.html", "index.proto.html", "chosen.jquery.js", "chosen.jquery.min.js", "chosen.proto.js", "chosen.proto.min.js", "chosen.css", "chosen-sprite.png", "chosen-sprite@2x.png"], dest: "dist/", expand: true, flatten: true, filter: 'isFile' } { src: ["public/docsupport/**"], dest: "dist/docsupport/", expand: true, flatten: true, filter: 'isFile' } ] clean: dist: ["dist/"] chosen_zip: ["chosen.zip"] build_gh_pages: gh_pages: {} dom_munger: download_links: src: 'public/index.html' options: callback: ($) -> $("#latest_version").attr("href", version_url()).text("Stable Version (#{version_tag()})") zip: chosen: cwd: 'public/' src: ['public/**/*'] dest: 'chosen.zip' grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.loadNpmTasks 'grunt-contrib-uglify' grunt.loadNpmTasks 'grunt-contrib-concat' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-contrib-copy' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-contrib-cssmin' grunt.loadNpmTasks 'grunt-build-gh-pages' grunt.loadNpmTasks 'grunt-zip' grunt.loadNpmTasks 'grunt-dom-munger' grunt.registerTask 'default', ['build'] grunt.registerTask 'build', ['coffee', 'concat', 'uglify', 'cssmin'] grunt.registerTask 'gh_pages', ['copy:dist', 'build_gh_pages:gh_pages'] grunt.registerTask 'prep_release', ['build','zip:chosen','package_jquery'] grunt.registerTask 'package_jquery', 'Generate a jquery.json manifest file from package.json', () -> src = "package.json" dest = "chosen.jquery.json" pkg = grunt.file.readJSON(src) json1 = "name": pkg.name "description": pkg.description "version": version() "licenses": pkg.licenses json2 = pkg.jqueryJSON json1[key] = json2[key] for key of json2 json1.author.name = pkg.author grunt.file.write('chosen.jquery.json', JSON.stringify(json1, null, 2))
136714
module.exports = (grunt) -> version = -> grunt.file.readJSON("package.json").version version_tag = -> "v#{version()}" grunt.initConfig pkg: grunt.file.readJSON("package.json") comments: """ // Chosen, a Select Box Enhancer for jQuery and Prototype // by <NAME> for Harvest, http://getharvest.com // // Version <%= pkg.version %> // Full source at https://github.com/harvesthq/chosen // Copyright (c) 2011 Harvest http://getharvest.com // MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md // This file is generated by `grunt build`, do not edit it by hand.\n """ minified_comments: "/* Chosen #{version_tag()} | (c) 2011-2013 by Harvest | MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md */\n" concat: options: banner: "<%= comments %>" jquery: src: ["public/chosen.jquery.js"] dest: "public/chosen.jquery.js" proto: src: ["public/chosen.proto.js"] dest: "public/chosen.proto.js" coffee: compile: files: 'public/chosen.jquery.js': ['coffee/lib/select-parser.coffee', 'coffee/lib/abstract-chosen.coffee', 'coffee/chosen.jquery.coffee'] 'public/chosen.proto.js': ['coffee/lib/select-parser.coffee', 'coffee/lib/abstract-chosen.coffee', 'coffee/chosen.proto.coffee'] uglify: options: mangle: except: ['jQuery', 'AbstractChosen', 'Chosen', 'SelectParser'] banner: "<%= minified_comments %>" minified_chosen_js: files: 'public/chosen.jquery.min.js': ['public/chosen.jquery.js'] 'public/chosen.proto.min.js': ['public/chosen.proto.js'] cssmin: minified_chosen_css: src: 'public/chosen.css' dest: 'public/chosen.min.css' watch: scripts: files: ['coffee/**/*.coffee'] tasks: ['build'] copy: dist: files: [ { cwd: "public", src: ["index.html", "index.proto.html", "chosen.jquery.js", "chosen.jquery.min.js", "chosen.proto.js", "chosen.proto.min.js", "chosen.css", "chosen-sprite.png", "chosen-sprite@2x.png"], dest: "dist/", expand: true, flatten: true, filter: 'isFile' } { src: ["public/docsupport/**"], dest: "dist/docsupport/", expand: true, flatten: true, filter: 'isFile' } ] clean: dist: ["dist/"] chosen_zip: ["chosen.zip"] build_gh_pages: gh_pages: {} dom_munger: download_links: src: 'public/index.html' options: callback: ($) -> $("#latest_version").attr("href", version_url()).text("Stable Version (#{version_tag()})") zip: chosen: cwd: 'public/' src: ['public/**/*'] dest: 'chosen.zip' grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.loadNpmTasks 'grunt-contrib-uglify' grunt.loadNpmTasks 'grunt-contrib-concat' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-contrib-copy' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-contrib-cssmin' grunt.loadNpmTasks 'grunt-build-gh-pages' grunt.loadNpmTasks 'grunt-zip' grunt.loadNpmTasks 'grunt-dom-munger' grunt.registerTask 'default', ['build'] grunt.registerTask 'build', ['coffee', 'concat', 'uglify', 'cssmin'] grunt.registerTask 'gh_pages', ['copy:dist', 'build_gh_pages:gh_pages'] grunt.registerTask 'prep_release', ['build','zip:chosen','package_jquery'] grunt.registerTask 'package_jquery', 'Generate a jquery.json manifest file from package.json', () -> src = "package.json" dest = "chosen.jquery.json" pkg = grunt.file.readJSON(src) json1 = "name": pkg.name "description": pkg.description "version": version() "licenses": pkg.licenses json2 = pkg.jqueryJSON json1[key] = json2[key] for key of json2 json1.author.name = pkg.author grunt.file.write('chosen.jquery.json', JSON.stringify(json1, null, 2))
true
module.exports = (grunt) -> version = -> grunt.file.readJSON("package.json").version version_tag = -> "v#{version()}" grunt.initConfig pkg: grunt.file.readJSON("package.json") comments: """ // Chosen, a Select Box Enhancer for jQuery and Prototype // by PI:NAME:<NAME>END_PI for Harvest, http://getharvest.com // // Version <%= pkg.version %> // Full source at https://github.com/harvesthq/chosen // Copyright (c) 2011 Harvest http://getharvest.com // MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md // This file is generated by `grunt build`, do not edit it by hand.\n """ minified_comments: "/* Chosen #{version_tag()} | (c) 2011-2013 by Harvest | MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md */\n" concat: options: banner: "<%= comments %>" jquery: src: ["public/chosen.jquery.js"] dest: "public/chosen.jquery.js" proto: src: ["public/chosen.proto.js"] dest: "public/chosen.proto.js" coffee: compile: files: 'public/chosen.jquery.js': ['coffee/lib/select-parser.coffee', 'coffee/lib/abstract-chosen.coffee', 'coffee/chosen.jquery.coffee'] 'public/chosen.proto.js': ['coffee/lib/select-parser.coffee', 'coffee/lib/abstract-chosen.coffee', 'coffee/chosen.proto.coffee'] uglify: options: mangle: except: ['jQuery', 'AbstractChosen', 'Chosen', 'SelectParser'] banner: "<%= minified_comments %>" minified_chosen_js: files: 'public/chosen.jquery.min.js': ['public/chosen.jquery.js'] 'public/chosen.proto.min.js': ['public/chosen.proto.js'] cssmin: minified_chosen_css: src: 'public/chosen.css' dest: 'public/chosen.min.css' watch: scripts: files: ['coffee/**/*.coffee'] tasks: ['build'] copy: dist: files: [ { cwd: "public", src: ["index.html", "index.proto.html", "chosen.jquery.js", "chosen.jquery.min.js", "chosen.proto.js", "chosen.proto.min.js", "chosen.css", "chosen-sprite.png", "chosen-sprite@2x.png"], dest: "dist/", expand: true, flatten: true, filter: 'isFile' } { src: ["public/docsupport/**"], dest: "dist/docsupport/", expand: true, flatten: true, filter: 'isFile' } ] clean: dist: ["dist/"] chosen_zip: ["chosen.zip"] build_gh_pages: gh_pages: {} dom_munger: download_links: src: 'public/index.html' options: callback: ($) -> $("#latest_version").attr("href", version_url()).text("Stable Version (#{version_tag()})") zip: chosen: cwd: 'public/' src: ['public/**/*'] dest: 'chosen.zip' grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.loadNpmTasks 'grunt-contrib-uglify' grunt.loadNpmTasks 'grunt-contrib-concat' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-contrib-copy' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-contrib-cssmin' grunt.loadNpmTasks 'grunt-build-gh-pages' grunt.loadNpmTasks 'grunt-zip' grunt.loadNpmTasks 'grunt-dom-munger' grunt.registerTask 'default', ['build'] grunt.registerTask 'build', ['coffee', 'concat', 'uglify', 'cssmin'] grunt.registerTask 'gh_pages', ['copy:dist', 'build_gh_pages:gh_pages'] grunt.registerTask 'prep_release', ['build','zip:chosen','package_jquery'] grunt.registerTask 'package_jquery', 'Generate a jquery.json manifest file from package.json', () -> src = "package.json" dest = "chosen.jquery.json" pkg = grunt.file.readJSON(src) json1 = "name": pkg.name "description": pkg.description "version": version() "licenses": pkg.licenses json2 = pkg.jqueryJSON json1[key] = json2[key] for key of json2 json1.author.name = pkg.author grunt.file.write('chosen.jquery.json', JSON.stringify(json1, null, 2))
[ { "context": "tps://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyD2ZjTQxVfi34-TMKjB5WYK3U8K6y-IQH0\", initTextOptions)\n\n\t\t\tif R.offline then return\n\t", "end": 278, "score": 0.9997163414955139, "start": 239, "tag": "KEY", "value": "AIzaSyD2ZjTQxVfi34-TMKjB5WYK3U8K6y-IQH0" }, { "context": "tps://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyBVfBj_ugQO_w0AK1x9F6yiXByhcNgjQZU\", @initTextOptions)\n\t\t\tjqxhr.done (json)=>\n\t\t\t\tco", "end": 440, "score": 0.9997294545173645, "start": 401, "tag": "KEY", "value": "AIzaSyBVfBj_ugQO_w0AK1x9F6yiXByhcNgjQZU" } ]
coffee/Utils/FontManager.coffee
arthursw/comme-un-dessein-client
0
define ['paper', 'R', 'Utils/Utils'], (P, R, Utils) -> class FontManager constructor: ()-> @availableFonts = [] @usedFonts = [] jQuery.support.cors = true # $.getJSON("https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyD2ZjTQxVfi34-TMKjB5WYK3U8K6y-IQH0", initTextOptions) if R.offline then return jqxhr = $.getJSON("https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyBVfBj_ugQO_w0AK1x9F6yiXByhcNgjQZU", @initTextOptions) jqxhr.done (json)=> console.log 'done' @initializeTextOptions(json) return jqxhr.fail (jqxhr, textStatus, error)-> err = textStatus + ", " + error console.log 'failed: ' + err return jqxhr.always (jqxhr, textStatus, error)-> err = textStatus + ", " + error console.log 'always: ' + err return return # add font to the page: # - check if the font is already loaded, and with which effect # - load web font from google font if needed addFont: (fontFamily, effect)-> if not fontFamily? then return fontFamilyURL = fontFamily.split(" ").join("+") # update @usedFonts, check if the font is already fontAlreadyUsed = false for font in @usedFonts if font.family == fontFamilyURL # if font.subsets.indexOf(subset) == -1 and subset != 'latin' # font.subsets.push(subset) # if font.styles.indexOf(style) == -1 # font.styles.push(style) if font.effects.indexOf(effect) == -1 and effect? font.effects.push(effect) fontAlreadyUsed = true break if not fontAlreadyUsed # if the font is not already used (loaded): load the font with the effect # subsets = [subset] # if subset!='latin' # subsets.push('latin') effects = [] if effect? effects.push(effect) if not fontFamilyURL or fontFamilyURL == '' console.log 'ERROR: font family URL is null or empty' @usedFonts.push( family: fontFamilyURL, effects: effects ) return # todo: use google web api to update text font on load callback # fonts could have multiple effects at once, but the gui does not allow this yet # since having multiple effects would not be of great use # must be improved!! loadFonts: ()=> $('head').remove("link.fonts") for font in @usedFonts newFont = font.family # if font.styles.length>0 # newFont += ":" # for style in font.styles # newFont += style + ',' # newFont = newFont.slice(0,-1) # if font.subsets.length>0 # newFont += "&subset=" # for subset in font.subsets # newFont += subset + ',' # newFont = newFont.slice(0,-1) if $('head').find('link[data-font-family="' + font.family + '"]').length==0 if font.effects.length>0 and not (font.effects.length == 1 and font.effects[0] == 'none') newFont += "&effect=" for effect, i in font.effects newFont += effect + '|' newFont = newFont.slice(0,-1) if R.offline then continue fontLink = $('<link class="fonts" data-font-family="' + font.family + '" rel="stylesheet" type="text/css">') fontLink.attr('href', "http://fonts.googleapis.com/css?family=" + newFont) $('head').append(fontLink) return # initialize typeahead font engine to quickly search for a font by typing its first letters initializeTextOptions: (data, textStatus, jqXHR) => # gather all font names fontFamilyNames = [] for item in data.items fontFamilyNames.push({ value: item.family }) # initialize typeahead font engine @typeaheadFontEngine = new Bloodhound({ name: 'Font families', local: fontFamilyNames, datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace }) promise = @typeaheadFontEngine.initialize() @availableFonts = data.items # test # @familyPickerJ = @textOptionsJ.find('#fontFamily') # @familyPickerJ.typeahead( # { hint: true, highlight: true, minLength: 1 }, # { valueKey: 'value', displayKey: 'value', source: typeaheadFontEngine.ttAdapter() } # ) # @fontSubmitJ = @textOptionsJ.find('#fontSubmit') # @fontSubmitJ.click( (event) -> # @setFontStyles() # ) return return FontManager
162979
define ['paper', 'R', 'Utils/Utils'], (P, R, Utils) -> class FontManager constructor: ()-> @availableFonts = [] @usedFonts = [] jQuery.support.cors = true # $.getJSON("https://www.googleapis.com/webfonts/v1/webfonts?key=<KEY>", initTextOptions) if R.offline then return jqxhr = $.getJSON("https://www.googleapis.com/webfonts/v1/webfonts?key=<KEY>", @initTextOptions) jqxhr.done (json)=> console.log 'done' @initializeTextOptions(json) return jqxhr.fail (jqxhr, textStatus, error)-> err = textStatus + ", " + error console.log 'failed: ' + err return jqxhr.always (jqxhr, textStatus, error)-> err = textStatus + ", " + error console.log 'always: ' + err return return # add font to the page: # - check if the font is already loaded, and with which effect # - load web font from google font if needed addFont: (fontFamily, effect)-> if not fontFamily? then return fontFamilyURL = fontFamily.split(" ").join("+") # update @usedFonts, check if the font is already fontAlreadyUsed = false for font in @usedFonts if font.family == fontFamilyURL # if font.subsets.indexOf(subset) == -1 and subset != 'latin' # font.subsets.push(subset) # if font.styles.indexOf(style) == -1 # font.styles.push(style) if font.effects.indexOf(effect) == -1 and effect? font.effects.push(effect) fontAlreadyUsed = true break if not fontAlreadyUsed # if the font is not already used (loaded): load the font with the effect # subsets = [subset] # if subset!='latin' # subsets.push('latin') effects = [] if effect? effects.push(effect) if not fontFamilyURL or fontFamilyURL == '' console.log 'ERROR: font family URL is null or empty' @usedFonts.push( family: fontFamilyURL, effects: effects ) return # todo: use google web api to update text font on load callback # fonts could have multiple effects at once, but the gui does not allow this yet # since having multiple effects would not be of great use # must be improved!! loadFonts: ()=> $('head').remove("link.fonts") for font in @usedFonts newFont = font.family # if font.styles.length>0 # newFont += ":" # for style in font.styles # newFont += style + ',' # newFont = newFont.slice(0,-1) # if font.subsets.length>0 # newFont += "&subset=" # for subset in font.subsets # newFont += subset + ',' # newFont = newFont.slice(0,-1) if $('head').find('link[data-font-family="' + font.family + '"]').length==0 if font.effects.length>0 and not (font.effects.length == 1 and font.effects[0] == 'none') newFont += "&effect=" for effect, i in font.effects newFont += effect + '|' newFont = newFont.slice(0,-1) if R.offline then continue fontLink = $('<link class="fonts" data-font-family="' + font.family + '" rel="stylesheet" type="text/css">') fontLink.attr('href', "http://fonts.googleapis.com/css?family=" + newFont) $('head').append(fontLink) return # initialize typeahead font engine to quickly search for a font by typing its first letters initializeTextOptions: (data, textStatus, jqXHR) => # gather all font names fontFamilyNames = [] for item in data.items fontFamilyNames.push({ value: item.family }) # initialize typeahead font engine @typeaheadFontEngine = new Bloodhound({ name: 'Font families', local: fontFamilyNames, datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace }) promise = @typeaheadFontEngine.initialize() @availableFonts = data.items # test # @familyPickerJ = @textOptionsJ.find('#fontFamily') # @familyPickerJ.typeahead( # { hint: true, highlight: true, minLength: 1 }, # { valueKey: 'value', displayKey: 'value', source: typeaheadFontEngine.ttAdapter() } # ) # @fontSubmitJ = @textOptionsJ.find('#fontSubmit') # @fontSubmitJ.click( (event) -> # @setFontStyles() # ) return return FontManager
true
define ['paper', 'R', 'Utils/Utils'], (P, R, Utils) -> class FontManager constructor: ()-> @availableFonts = [] @usedFonts = [] jQuery.support.cors = true # $.getJSON("https://www.googleapis.com/webfonts/v1/webfonts?key=PI:KEY:<KEY>END_PI", initTextOptions) if R.offline then return jqxhr = $.getJSON("https://www.googleapis.com/webfonts/v1/webfonts?key=PI:KEY:<KEY>END_PI", @initTextOptions) jqxhr.done (json)=> console.log 'done' @initializeTextOptions(json) return jqxhr.fail (jqxhr, textStatus, error)-> err = textStatus + ", " + error console.log 'failed: ' + err return jqxhr.always (jqxhr, textStatus, error)-> err = textStatus + ", " + error console.log 'always: ' + err return return # add font to the page: # - check if the font is already loaded, and with which effect # - load web font from google font if needed addFont: (fontFamily, effect)-> if not fontFamily? then return fontFamilyURL = fontFamily.split(" ").join("+") # update @usedFonts, check if the font is already fontAlreadyUsed = false for font in @usedFonts if font.family == fontFamilyURL # if font.subsets.indexOf(subset) == -1 and subset != 'latin' # font.subsets.push(subset) # if font.styles.indexOf(style) == -1 # font.styles.push(style) if font.effects.indexOf(effect) == -1 and effect? font.effects.push(effect) fontAlreadyUsed = true break if not fontAlreadyUsed # if the font is not already used (loaded): load the font with the effect # subsets = [subset] # if subset!='latin' # subsets.push('latin') effects = [] if effect? effects.push(effect) if not fontFamilyURL or fontFamilyURL == '' console.log 'ERROR: font family URL is null or empty' @usedFonts.push( family: fontFamilyURL, effects: effects ) return # todo: use google web api to update text font on load callback # fonts could have multiple effects at once, but the gui does not allow this yet # since having multiple effects would not be of great use # must be improved!! loadFonts: ()=> $('head').remove("link.fonts") for font in @usedFonts newFont = font.family # if font.styles.length>0 # newFont += ":" # for style in font.styles # newFont += style + ',' # newFont = newFont.slice(0,-1) # if font.subsets.length>0 # newFont += "&subset=" # for subset in font.subsets # newFont += subset + ',' # newFont = newFont.slice(0,-1) if $('head').find('link[data-font-family="' + font.family + '"]').length==0 if font.effects.length>0 and not (font.effects.length == 1 and font.effects[0] == 'none') newFont += "&effect=" for effect, i in font.effects newFont += effect + '|' newFont = newFont.slice(0,-1) if R.offline then continue fontLink = $('<link class="fonts" data-font-family="' + font.family + '" rel="stylesheet" type="text/css">') fontLink.attr('href', "http://fonts.googleapis.com/css?family=" + newFont) $('head').append(fontLink) return # initialize typeahead font engine to quickly search for a font by typing its first letters initializeTextOptions: (data, textStatus, jqXHR) => # gather all font names fontFamilyNames = [] for item in data.items fontFamilyNames.push({ value: item.family }) # initialize typeahead font engine @typeaheadFontEngine = new Bloodhound({ name: 'Font families', local: fontFamilyNames, datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace }) promise = @typeaheadFontEngine.initialize() @availableFonts = data.items # test # @familyPickerJ = @textOptionsJ.find('#fontFamily') # @familyPickerJ.typeahead( # { hint: true, highlight: true, minLength: 1 }, # { valueKey: 'value', displayKey: 'value', source: typeaheadFontEngine.ttAdapter() } # ) # @fontSubmitJ = @textOptionsJ.find('#fontSubmit') # @fontSubmitJ.click( (event) -> # @setFontStyles() # ) return return FontManager
[ { "context": "ib'\n\n\n# connect to db\nmongoose.connect 'mongodb://127.0.0.1:27017/hmrexample'\n\n\n# instantiate server\nserver =", "end": 191, "score": 0.9997273683547974, "start": 182, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": ", \"size\": \"M\" } }\n\n -- customers --\n { \"name\": \"Joe Chicago\", \"email\": \"joey.chitown@server.com\", \"address\": ", "end": 1470, "score": 0.9998842477798462, "start": 1459, "tag": "NAME", "value": "Joe Chicago" }, { "context": "customers --\n { \"name\": \"Joe Chicago\", \"email\": \"joey.chitown@server.com\", \"address\": { \"street\": \"123 N State St\", \"unit\"", "end": 1506, "score": 0.9999279975891113, "start": 1483, "tag": "EMAIL", "value": "joey.chitown@server.com" }, { "context": "e\": \"IL\", \"postal_code\": \"60602\" } }\n { \"name\": \"Jane Chicago\", \"email\": \"jane.chitown@server.com\", \"address\": ", "end": 1651, "score": 0.9998762607574463, "start": 1639, "tag": "NAME", "value": "Jane Chicago" }, { "context": "\"60602\" } }\n { \"name\": \"Jane Chicago\", \"email\": \"jane.chitown@server.com\", \"address\": { \"street\": \"123 N State St\", \"unit\"", "end": 1687, "score": 0.9999278783798218, "start": 1664, "tag": "EMAIL", "value": "jane.chitown@server.com" }, { "context": "will change with your testing **\n { \"customer\": \"534c8e46aa65b5a70810bf05\", \"products\": [\"534c8e12aa65b5a70810bf03\", \"534c8", "end": 1912, "score": 0.994350016117096, "start": 1888, "tag": "KEY", "value": "534c8e46aa65b5a70810bf05" }, { "context": "\", \"534c8e20aa65b5a70810bf04\"] }\n { \"customer\": \"534c8e53aa65b5a70810bf06\", \"products\": [\"534c8ce1250f948008b68cde\"] }\n###\n", "end": 2027, "score": 0.9942970275878906, "start": 2003, "tag": "KEY", "value": "534c8e53aa65b5a70810bf06" } ]
examples/app.coffee
vforgione/hapi-mongoose-resource
2
### entry point of application ### # module imports Hapi = require 'hapi' mongoose = require 'mongoose' Resource = require '../lib' # connect to db mongoose.connect 'mongodb://127.0.0.1:27017/hmrexample' # instantiate server server = new Hapi.createServer 'localhost', 3000, {} # model imports Product = require('./schemas/product').Product Customer = require('./schemas/customer').Customer SalesOrder = require('./schemas/sales-order').SalesOrder # resources ProductResource = new Resource Product, '/products' CustomerResource = new Resource Customer, '/customers' SalesOrderResource = new Resource SalesOrder, '/sales-orders', { refs: { customer: CustomerResource, products: ProductResource } } # routing server.route ProductResource.router.routes server.route CustomerResource.router.routes server.route SalesOrderResource.router.routes # main loop server.start -> console.log 'Server listening at ' + server.info.uri ### sample payloads to test: -- products -- { "name": "T Shirt", "number": 12345, "price": 9.99, "description": "It's a T Shirt. Ta da!", "tags": { "color": "Blue", "size": "S", "style": "Girlie" } } { "name": "T Shirt", "number": 12350, "price": 9.99, "description": "It's a T Shirt. Ta da!", "tags": { "color": "Red", "size": "M" } } { "name": "T Shirt", "number": 12351, "price": 9.99, "description": "It's a T Shirt. Ta da!", "tags": { "color": "Green", "size": "M" } } -- customers -- { "name": "Joe Chicago", "email": "joey.chitown@server.com", "address": { "street": "123 N State St", "unit": "321", "city": "Chicago", "state": "IL", "postal_code": "60602" } } { "name": "Jane Chicago", "email": "jane.chitown@server.com", "address": { "street": "123 N State St", "unit": "321", "city": "Chicago", "state": "IL", "postal_code": "60602" } } -- sales orders -- ** ids will change with your testing ** { "customer": "534c8e46aa65b5a70810bf05", "products": ["534c8e12aa65b5a70810bf03", "534c8e20aa65b5a70810bf04"] } { "customer": "534c8e53aa65b5a70810bf06", "products": ["534c8ce1250f948008b68cde"] } ###
2490
### entry point of application ### # module imports Hapi = require 'hapi' mongoose = require 'mongoose' Resource = require '../lib' # connect to db mongoose.connect 'mongodb://127.0.0.1:27017/hmrexample' # instantiate server server = new Hapi.createServer 'localhost', 3000, {} # model imports Product = require('./schemas/product').Product Customer = require('./schemas/customer').Customer SalesOrder = require('./schemas/sales-order').SalesOrder # resources ProductResource = new Resource Product, '/products' CustomerResource = new Resource Customer, '/customers' SalesOrderResource = new Resource SalesOrder, '/sales-orders', { refs: { customer: CustomerResource, products: ProductResource } } # routing server.route ProductResource.router.routes server.route CustomerResource.router.routes server.route SalesOrderResource.router.routes # main loop server.start -> console.log 'Server listening at ' + server.info.uri ### sample payloads to test: -- products -- { "name": "T Shirt", "number": 12345, "price": 9.99, "description": "It's a T Shirt. Ta da!", "tags": { "color": "Blue", "size": "S", "style": "Girlie" } } { "name": "T Shirt", "number": 12350, "price": 9.99, "description": "It's a T Shirt. Ta da!", "tags": { "color": "Red", "size": "M" } } { "name": "T Shirt", "number": 12351, "price": 9.99, "description": "It's a T Shirt. Ta da!", "tags": { "color": "Green", "size": "M" } } -- customers -- { "name": "<NAME>", "email": "<EMAIL>", "address": { "street": "123 N State St", "unit": "321", "city": "Chicago", "state": "IL", "postal_code": "60602" } } { "name": "<NAME>", "email": "<EMAIL>", "address": { "street": "123 N State St", "unit": "321", "city": "Chicago", "state": "IL", "postal_code": "60602" } } -- sales orders -- ** ids will change with your testing ** { "customer": "<KEY>", "products": ["534c8e12aa65b5a70810bf03", "534c8e20aa65b5a70810bf04"] } { "customer": "<KEY>", "products": ["534c8ce1250f948008b68cde"] } ###
true
### entry point of application ### # module imports Hapi = require 'hapi' mongoose = require 'mongoose' Resource = require '../lib' # connect to db mongoose.connect 'mongodb://127.0.0.1:27017/hmrexample' # instantiate server server = new Hapi.createServer 'localhost', 3000, {} # model imports Product = require('./schemas/product').Product Customer = require('./schemas/customer').Customer SalesOrder = require('./schemas/sales-order').SalesOrder # resources ProductResource = new Resource Product, '/products' CustomerResource = new Resource Customer, '/customers' SalesOrderResource = new Resource SalesOrder, '/sales-orders', { refs: { customer: CustomerResource, products: ProductResource } } # routing server.route ProductResource.router.routes server.route CustomerResource.router.routes server.route SalesOrderResource.router.routes # main loop server.start -> console.log 'Server listening at ' + server.info.uri ### sample payloads to test: -- products -- { "name": "T Shirt", "number": 12345, "price": 9.99, "description": "It's a T Shirt. Ta da!", "tags": { "color": "Blue", "size": "S", "style": "Girlie" } } { "name": "T Shirt", "number": 12350, "price": 9.99, "description": "It's a T Shirt. Ta da!", "tags": { "color": "Red", "size": "M" } } { "name": "T Shirt", "number": 12351, "price": 9.99, "description": "It's a T Shirt. Ta da!", "tags": { "color": "Green", "size": "M" } } -- customers -- { "name": "PI:NAME:<NAME>END_PI", "email": "PI:EMAIL:<EMAIL>END_PI", "address": { "street": "123 N State St", "unit": "321", "city": "Chicago", "state": "IL", "postal_code": "60602" } } { "name": "PI:NAME:<NAME>END_PI", "email": "PI:EMAIL:<EMAIL>END_PI", "address": { "street": "123 N State St", "unit": "321", "city": "Chicago", "state": "IL", "postal_code": "60602" } } -- sales orders -- ** ids will change with your testing ** { "customer": "PI:KEY:<KEY>END_PI", "products": ["534c8e12aa65b5a70810bf03", "534c8e20aa65b5a70810bf04"] } { "customer": "PI:KEY:<KEY>END_PI", "products": ["534c8ce1250f948008b68cde"] } ###
[ { "context": "ration: 0\n botPos: [1, 2]\n botMessage: 'testers'\n domHighlight: '#code-area'\n surfaceHi", "end": 1917, "score": 0.8965386152267456, "start": 1910, "tag": "PASSWORD", "value": "testers" } ]
test/app/lib/ScriptManager.spec.coffee
Melondonut/codecombat
1
describe('ScriptManager', -> ScriptManager = require 'lib/scripts/ScriptManager' xit('broadcasts note with event upon hearing from channel', -> note = {channel: 'cnn', event: {1: 1}} noteGroup = {duration: 0, notes: [note]} script = {channel: 'pbs', noteChain: [noteGroup]} sm = new ScriptManager({scripts: [script]}) sm.paused = false gotEvent = {} f = (event) -> gotEvent = event Backbone.Mediator.subscribe('cnn', f, @) Backbone.Mediator.publish('pbs') expect(gotEvent[1]).toBe(note.event[1]) sm.destroy() Backbone.Mediator.unsubscribe('cnn', f, @) ) xit('is silent when script event do not match', -> note = {channel: 'cnn', event: {1: 1}} noteGroup = {duration: 0, notes: [note]} script = channel: 'pbs' eventPrereqs: [ eventProps: 'foo' equalTo: 'bar' ] noteChain: [noteGroup] sm = new ScriptManager([script]) sm.paused = false gotEvent = null f = (event) -> gotEvent = event Backbone.Mediator.subscribe('cnn', f, @) # bunch of mismatches Backbone.Mediator.publish('pbs', {foo: 'rad'}) expect(gotEvent).toBeNull() Backbone.Mediator.publish('pbs', 'bar') Backbone.Mediator.publish('pbs') Backbone.Mediator.publish('pbs', {foo: 'bar'}) expect(gotEvent[1]).toBe(note.event[1]) sm.destroy() Backbone.Mediator.unsubscribe('cnn', f, @) ) xit('makes no subscriptions when something is invalid', -> note = {event: {1: 1}} # channel is required noteGroup = {notes: [note]} script = {channel: 'pbs', noteChain: [noteGroup]} sm = new ScriptManager([script]) expect(sm.subscriptions['pbs']).toBe(undefined) sm.destroy() ) xit('fills out lots of notes based on note group properties', -> note = {channel: 'cnn', event: {1: 1}} noteGroup = duration: 0 botPos: [1, 2] botMessage: 'testers' domHighlight: '#code-area' surfaceHighlights: ['Guy0', 'Guy1'] scrubToTime: 20 notes: [note] script = {channel: 'pbs', noteChain: [noteGroup]} sm = new ScriptManager([script]) sm.paused = false Backbone.Mediator.publish('pbs') expect(sm.lastNoteGroup.notes.length).toBe(7) channels = (note.channel for note in sm.lastNoteGroup.notes) expect(channels).toContain('cnn') expect(channels).toContain('level-bot-move') expect(channels).toContain('level-bot-say') expect(channels).toContain('level-highlight-dom') expect(channels).toContain('level-highlight-sprites') expect(channels).toContain('level-set-time') expect(channels).toContain('level-disable-controls') sm.destroy() ) xit('releases notes based on user confirmation', -> note1 = {channel: 'cnn', event: {1: 1}} note2 = {channel: 'cbs', event: {2: 2}} noteGroup1 = {duration: 0, notes: [note1]} noteGroup2 = {duration: 0, notes: [note2]} script = {channel: 'pbs', noteChain: [noteGroup1, noteGroup2]} sm = new ScriptManager({scripts: [script]}) sm.paused = false gotCnnEvent = null f1 = (event) -> gotCnnEvent = event Backbone.Mediator.subscribe('cnn', f1, @) gotCbsEvent = null f2 = (event) -> gotCbsEvent = event Backbone.Mediator.subscribe('cbs', f2, @) Backbone.Mediator.publish('pbs') expect(gotCnnEvent[1]).toBe(1) expect(gotCbsEvent).toBeNull() expect(sm.scriptInProgress).toBe(true) runs(-> Backbone.Mediator.publish('end-current-script')) f = -> gotCbsEvent? waitsFor(f, 'The next event should have been published', 20) f = -> expect(gotCnnEvent[1]).toBe(1) expect(gotCbsEvent[2]).toBe(2) expect(sm.scriptInProgress).toBe(true) Backbone.Mediator.publish('end-current-script') expect(sm.scriptInProgress).toBe(false) sm.destroy() Backbone.Mediator.unsubscribe('cnn', f1, @) Backbone.Mediator.unsubscribe('cbs', f2, @) runs(f) ) xit('ignores triggers for scripts waiting for other scripts to fire', -> # channel2 won't fire the cbs notification until channel1 does its thing note1 = {channel: 'cnn', event: {1: 1}} note2 = {channel: 'cbs', event: {2: 2}} noteGroup1 = {duration: 0, notes: [note1]} noteGroup2 = {duration: 0, notes: [note2]} script1 = {channel: 'channel1', id: 'channel1Script', noteChain: [noteGroup1]} script2 = {channel: 'channel2', scriptPrereqs: ['channel1Script'], noteChain: [noteGroup2]} sm = new ScriptManager([script1, script2]) sm.paused = false gotCbsEvent = null f = (event) -> gotCbsEvent = event Backbone.Mediator.subscribe('cbs', f, @) Backbone.Mediator.publish('channel2') expect(gotCbsEvent).toBeNull() # channel1 hasn't done its thing yet Backbone.Mediator.publish('channel1') expect(gotCbsEvent).toBeNull() # channel2 needs to be triggered again Backbone.Mediator.publish('channel2') expect(gotCbsEvent).toBeNull() # channel1 is still waiting for user confirmation Backbone.Mediator.publish('end-current-script') expect(gotCbsEvent[1]).toBe(2) # and finally the second script is fired sm.destroy() Backbone.Mediator.unsubscribe('cnn', f, @) ) )
82673
describe('ScriptManager', -> ScriptManager = require 'lib/scripts/ScriptManager' xit('broadcasts note with event upon hearing from channel', -> note = {channel: 'cnn', event: {1: 1}} noteGroup = {duration: 0, notes: [note]} script = {channel: 'pbs', noteChain: [noteGroup]} sm = new ScriptManager({scripts: [script]}) sm.paused = false gotEvent = {} f = (event) -> gotEvent = event Backbone.Mediator.subscribe('cnn', f, @) Backbone.Mediator.publish('pbs') expect(gotEvent[1]).toBe(note.event[1]) sm.destroy() Backbone.Mediator.unsubscribe('cnn', f, @) ) xit('is silent when script event do not match', -> note = {channel: 'cnn', event: {1: 1}} noteGroup = {duration: 0, notes: [note]} script = channel: 'pbs' eventPrereqs: [ eventProps: 'foo' equalTo: 'bar' ] noteChain: [noteGroup] sm = new ScriptManager([script]) sm.paused = false gotEvent = null f = (event) -> gotEvent = event Backbone.Mediator.subscribe('cnn', f, @) # bunch of mismatches Backbone.Mediator.publish('pbs', {foo: 'rad'}) expect(gotEvent).toBeNull() Backbone.Mediator.publish('pbs', 'bar') Backbone.Mediator.publish('pbs') Backbone.Mediator.publish('pbs', {foo: 'bar'}) expect(gotEvent[1]).toBe(note.event[1]) sm.destroy() Backbone.Mediator.unsubscribe('cnn', f, @) ) xit('makes no subscriptions when something is invalid', -> note = {event: {1: 1}} # channel is required noteGroup = {notes: [note]} script = {channel: 'pbs', noteChain: [noteGroup]} sm = new ScriptManager([script]) expect(sm.subscriptions['pbs']).toBe(undefined) sm.destroy() ) xit('fills out lots of notes based on note group properties', -> note = {channel: 'cnn', event: {1: 1}} noteGroup = duration: 0 botPos: [1, 2] botMessage: '<PASSWORD>' domHighlight: '#code-area' surfaceHighlights: ['Guy0', 'Guy1'] scrubToTime: 20 notes: [note] script = {channel: 'pbs', noteChain: [noteGroup]} sm = new ScriptManager([script]) sm.paused = false Backbone.Mediator.publish('pbs') expect(sm.lastNoteGroup.notes.length).toBe(7) channels = (note.channel for note in sm.lastNoteGroup.notes) expect(channels).toContain('cnn') expect(channels).toContain('level-bot-move') expect(channels).toContain('level-bot-say') expect(channels).toContain('level-highlight-dom') expect(channels).toContain('level-highlight-sprites') expect(channels).toContain('level-set-time') expect(channels).toContain('level-disable-controls') sm.destroy() ) xit('releases notes based on user confirmation', -> note1 = {channel: 'cnn', event: {1: 1}} note2 = {channel: 'cbs', event: {2: 2}} noteGroup1 = {duration: 0, notes: [note1]} noteGroup2 = {duration: 0, notes: [note2]} script = {channel: 'pbs', noteChain: [noteGroup1, noteGroup2]} sm = new ScriptManager({scripts: [script]}) sm.paused = false gotCnnEvent = null f1 = (event) -> gotCnnEvent = event Backbone.Mediator.subscribe('cnn', f1, @) gotCbsEvent = null f2 = (event) -> gotCbsEvent = event Backbone.Mediator.subscribe('cbs', f2, @) Backbone.Mediator.publish('pbs') expect(gotCnnEvent[1]).toBe(1) expect(gotCbsEvent).toBeNull() expect(sm.scriptInProgress).toBe(true) runs(-> Backbone.Mediator.publish('end-current-script')) f = -> gotCbsEvent? waitsFor(f, 'The next event should have been published', 20) f = -> expect(gotCnnEvent[1]).toBe(1) expect(gotCbsEvent[2]).toBe(2) expect(sm.scriptInProgress).toBe(true) Backbone.Mediator.publish('end-current-script') expect(sm.scriptInProgress).toBe(false) sm.destroy() Backbone.Mediator.unsubscribe('cnn', f1, @) Backbone.Mediator.unsubscribe('cbs', f2, @) runs(f) ) xit('ignores triggers for scripts waiting for other scripts to fire', -> # channel2 won't fire the cbs notification until channel1 does its thing note1 = {channel: 'cnn', event: {1: 1}} note2 = {channel: 'cbs', event: {2: 2}} noteGroup1 = {duration: 0, notes: [note1]} noteGroup2 = {duration: 0, notes: [note2]} script1 = {channel: 'channel1', id: 'channel1Script', noteChain: [noteGroup1]} script2 = {channel: 'channel2', scriptPrereqs: ['channel1Script'], noteChain: [noteGroup2]} sm = new ScriptManager([script1, script2]) sm.paused = false gotCbsEvent = null f = (event) -> gotCbsEvent = event Backbone.Mediator.subscribe('cbs', f, @) Backbone.Mediator.publish('channel2') expect(gotCbsEvent).toBeNull() # channel1 hasn't done its thing yet Backbone.Mediator.publish('channel1') expect(gotCbsEvent).toBeNull() # channel2 needs to be triggered again Backbone.Mediator.publish('channel2') expect(gotCbsEvent).toBeNull() # channel1 is still waiting for user confirmation Backbone.Mediator.publish('end-current-script') expect(gotCbsEvent[1]).toBe(2) # and finally the second script is fired sm.destroy() Backbone.Mediator.unsubscribe('cnn', f, @) ) )
true
describe('ScriptManager', -> ScriptManager = require 'lib/scripts/ScriptManager' xit('broadcasts note with event upon hearing from channel', -> note = {channel: 'cnn', event: {1: 1}} noteGroup = {duration: 0, notes: [note]} script = {channel: 'pbs', noteChain: [noteGroup]} sm = new ScriptManager({scripts: [script]}) sm.paused = false gotEvent = {} f = (event) -> gotEvent = event Backbone.Mediator.subscribe('cnn', f, @) Backbone.Mediator.publish('pbs') expect(gotEvent[1]).toBe(note.event[1]) sm.destroy() Backbone.Mediator.unsubscribe('cnn', f, @) ) xit('is silent when script event do not match', -> note = {channel: 'cnn', event: {1: 1}} noteGroup = {duration: 0, notes: [note]} script = channel: 'pbs' eventPrereqs: [ eventProps: 'foo' equalTo: 'bar' ] noteChain: [noteGroup] sm = new ScriptManager([script]) sm.paused = false gotEvent = null f = (event) -> gotEvent = event Backbone.Mediator.subscribe('cnn', f, @) # bunch of mismatches Backbone.Mediator.publish('pbs', {foo: 'rad'}) expect(gotEvent).toBeNull() Backbone.Mediator.publish('pbs', 'bar') Backbone.Mediator.publish('pbs') Backbone.Mediator.publish('pbs', {foo: 'bar'}) expect(gotEvent[1]).toBe(note.event[1]) sm.destroy() Backbone.Mediator.unsubscribe('cnn', f, @) ) xit('makes no subscriptions when something is invalid', -> note = {event: {1: 1}} # channel is required noteGroup = {notes: [note]} script = {channel: 'pbs', noteChain: [noteGroup]} sm = new ScriptManager([script]) expect(sm.subscriptions['pbs']).toBe(undefined) sm.destroy() ) xit('fills out lots of notes based on note group properties', -> note = {channel: 'cnn', event: {1: 1}} noteGroup = duration: 0 botPos: [1, 2] botMessage: 'PI:PASSWORD:<PASSWORD>END_PI' domHighlight: '#code-area' surfaceHighlights: ['Guy0', 'Guy1'] scrubToTime: 20 notes: [note] script = {channel: 'pbs', noteChain: [noteGroup]} sm = new ScriptManager([script]) sm.paused = false Backbone.Mediator.publish('pbs') expect(sm.lastNoteGroup.notes.length).toBe(7) channels = (note.channel for note in sm.lastNoteGroup.notes) expect(channels).toContain('cnn') expect(channels).toContain('level-bot-move') expect(channels).toContain('level-bot-say') expect(channels).toContain('level-highlight-dom') expect(channels).toContain('level-highlight-sprites') expect(channels).toContain('level-set-time') expect(channels).toContain('level-disable-controls') sm.destroy() ) xit('releases notes based on user confirmation', -> note1 = {channel: 'cnn', event: {1: 1}} note2 = {channel: 'cbs', event: {2: 2}} noteGroup1 = {duration: 0, notes: [note1]} noteGroup2 = {duration: 0, notes: [note2]} script = {channel: 'pbs', noteChain: [noteGroup1, noteGroup2]} sm = new ScriptManager({scripts: [script]}) sm.paused = false gotCnnEvent = null f1 = (event) -> gotCnnEvent = event Backbone.Mediator.subscribe('cnn', f1, @) gotCbsEvent = null f2 = (event) -> gotCbsEvent = event Backbone.Mediator.subscribe('cbs', f2, @) Backbone.Mediator.publish('pbs') expect(gotCnnEvent[1]).toBe(1) expect(gotCbsEvent).toBeNull() expect(sm.scriptInProgress).toBe(true) runs(-> Backbone.Mediator.publish('end-current-script')) f = -> gotCbsEvent? waitsFor(f, 'The next event should have been published', 20) f = -> expect(gotCnnEvent[1]).toBe(1) expect(gotCbsEvent[2]).toBe(2) expect(sm.scriptInProgress).toBe(true) Backbone.Mediator.publish('end-current-script') expect(sm.scriptInProgress).toBe(false) sm.destroy() Backbone.Mediator.unsubscribe('cnn', f1, @) Backbone.Mediator.unsubscribe('cbs', f2, @) runs(f) ) xit('ignores triggers for scripts waiting for other scripts to fire', -> # channel2 won't fire the cbs notification until channel1 does its thing note1 = {channel: 'cnn', event: {1: 1}} note2 = {channel: 'cbs', event: {2: 2}} noteGroup1 = {duration: 0, notes: [note1]} noteGroup2 = {duration: 0, notes: [note2]} script1 = {channel: 'channel1', id: 'channel1Script', noteChain: [noteGroup1]} script2 = {channel: 'channel2', scriptPrereqs: ['channel1Script'], noteChain: [noteGroup2]} sm = new ScriptManager([script1, script2]) sm.paused = false gotCbsEvent = null f = (event) -> gotCbsEvent = event Backbone.Mediator.subscribe('cbs', f, @) Backbone.Mediator.publish('channel2') expect(gotCbsEvent).toBeNull() # channel1 hasn't done its thing yet Backbone.Mediator.publish('channel1') expect(gotCbsEvent).toBeNull() # channel2 needs to be triggered again Backbone.Mediator.publish('channel2') expect(gotCbsEvent).toBeNull() # channel1 is still waiting for user confirmation Backbone.Mediator.publish('end-current-script') expect(gotCbsEvent[1]).toBe(2) # and finally the second script is fired sm.destroy() Backbone.Mediator.unsubscribe('cnn', f, @) ) )
[ { "context": "estAddObj = (list) ->\n\n testObj =\n name: 'test'\n\n list.addObjectToCache(testObj, 1)\n expec", "end": 479, "score": 0.9979172348976135, "start": 475, "tag": "NAME", "value": "test" }, { "context": "trieveObj = (list) ->\n\n testObj =\n name: 'test'\n\n list.addObjectToCache(testObj, 1)\n objGo", "end": 799, "score": 0.9983338117599487, "start": 795, "tag": "NAME", "value": "test" } ]
src/glados/static/coffee/tests/PaginatedCollections/PaginatedCollectionsCacheTest.coffee
BNext-IQT/glados-frontend-chembl-main-interface
33
describe "Paginated Collections Cache", -> #------------------------------------------------------------------------------------------------------------------- # Generic test functions #------------------------------------------------------------------------------------------------------------------- ES_COL_TYPE = 'ES' WS_COL_TYPE = 'WS' testInitCache = (list) -> expect(list.getMeta('cache')?).toBe(true) testAddObj = (list) -> testObj = name: 'test' list.addObjectToCache(testObj, 1) expect(list.getMeta('cache')[1].name).toBe('test') testResetCache = (list) -> list.resetCache() expect(list.getMeta('cache')?).toBe(true) expect(Object.keys(list.getMeta('cache')).length).toBe(0) testRetrieveObj = (list) -> testObj = name: 'test' list.addObjectToCache(testObj, 1) objGot = list.getObjectInCache(1) expect(objGot.name).toBe(testObj.name) testRetrieveObjs = (list) -> #------------------------------------- # No Objects in Cache #------------------------------------- startingPosition = 0 endPosition = 10 objsGot = list.getObjectsInCache(startingPosition, endPosition) expect(objsGot.length).toBe(0) #------------------------------------- # AddTestObjs #------------------------------------- numTestObjects = 10 testObjs = [] for i in [0..numTestObjects-1] newObj = name: i list.addObjectToCache(newObj, i) testObjs.push newObj #------------------------------------- # Start > End #------------------------------------- startingPosition = 1 endPosition = 0 objsGot = list.getObjectsInCache(startingPosition, endPosition) expect(objsGot.length).toBe(0) #------------------------------------- # Start == End #------------------------------------- startingPosition = 0 endPosition = 0 objsGot = list.getObjectsInCache(startingPosition, endPosition) expect(objsGot[startingPosition].name).toBe(testObjs[startingPosition].name) #------------------------------------- # Start < End #------------------------------------- startingPosition = 0 endPosition = testObjs.length - 1 objsGot = list.getObjectsInCache(startingPosition, endPosition) for i in [0..testObjs.length-1] expect(objsGot[i].name).toBe(testObjs[i].name) testGetObjectsFromPage = (list) -> #------------------------------------- # No Objects in Cache #------------------------------------- pageNum = 1 objsGot = list.getObjectsInCacheFromPage(pageNum) expect(objsGot.length).toBe(0) #------------------------------------- # AddTestObjs #------------------------------------- numTestObjects = 90 testObjs = [] for i in [0..numTestObjects-1] newObj = name: i list.addObjectToCache(newObj, i) testObjs.push newObj #------------------------------------- # Page in cache #------------------------------------- pageNum = 1 pageSize = list.getMeta('page_size') objsGot = list.getObjectsInCacheFromPage(pageNum) for i in [0..pageSize-1] expect(objsGot[i].name).toBe(testObjs[i].name) #------------------------------------- # Page not in cache at all #------------------------------------- pageNum = 20 objsGot = list.getObjectsInCacheFromPage(pageNum) expect(objsGot?).toBe(false) #------------------------------------- # Page part in cache #------------------------------------- limitPageNum = Math.floor(numTestObjects / pageSize) + 1 objsGot = list.getObjectsInCacheFromPage(limitPageNum) expect(objsGot?).toBe(false) #------------------------------------- # Last page #------------------------------------- totalPages = list.getMeta('total_pages') totalMaxItems = pageSize * totalPages itemsToRemoveInLastPage = Math.ceil(pageSize / 2) itemsToCreate = totalMaxItems - itemsToRemoveInLastPage numTestObjects = itemsToCreate testObjs = [] for i in [0..numTestObjects-1] newObj = name: i list.addObjectToCache(newObj, i) testObjs.push newObj objsGot = list.getObjectsInCacheFromPage(totalPages) pageStartingPosition = pageSize * (totalPages - 1) for i in [0..objsGot.length-1] expect(objsGot[i].name).toBe(testObjs[i + pageStartingPosition].name) testAddsFromPage = (list) -> #------------------------------------- # Page with one item #------------------------------------- pageSize = 1 objects = [] for i in [0..pageSize-1] objects.push name: i list.addObjectsToCacheFromPage(objects, 1) cache = list.getMeta('cache') expect(cache[0].name).toBe(objects[0].name) list.resetCache() #------------------------------------- # Page with multiple items #------------------------------------- pageSize = list.getMeta('page_size') objects = [] for i in [0..pageSize-1] objects.push name: i for pageNum in [1..10] list.addObjectsToCacheFromPage(objects, pageNum) cache = list.getMeta('cache') startingPosition = objects.length * (pageNum - 1) for i in [0..objects.length-1] expectedPosition = startingPosition + i expect(cache[expectedPosition].name).toBe(i) testAddsItemsAfterParse = (list, dataToParse, colType) -> list.reset(list.parse(dataToParse)) testDataToParse1 = dataToParse.es_response if colType == WS_COL_TYPE objsInData = testDataToParse1.molecules else if colType == ES_COL_TYPE objsInData = testDataToParse1.hits.hits modelsInCache = list.getObjectsInCacheFromPage 1 for i in [0..modelsInCache.length-1] idGot = modelsInCache[i].get('molecule_chembl_id') if colType == WS_COL_TYPE idInData = objsInData[i]['molecule_chembl_id'] else if colType == ES_COL_TYPE idInData = objsInData[i]._source['molecule_chembl_id'] expect(idGot).toBe(idInData) #------------------------------------------------------------------------------------------------------------------- # Specific descriptions #------------------------------------------------------------------------------------------------------------------- describe 'Collection with no caching', -> list = undefined beforeAll -> list = glados.models.paginatedCollections.PaginatedCollectionFactory.getNewTargetComponentsList() it "does not initialise cache", -> expect(list.getMeta('cache')?).toBe(false) describe 'ES Collections', -> list = undefined testDataToParse = undefined beforeAll (done) -> list = glados.models.paginatedCollections.PaginatedCollectionFactory.getNewESResultsListFor( glados.models.paginatedCollections.Settings.ES_INDEXES.COMPOUND ) list.setMeta('total_pages', 10) dataURL = glados.Settings.STATIC_URL + 'testData/ESCollectionTestData1.json' $.get dataURL, (testData) -> testDataToParse = testData done() beforeEach -> list.resetCache() it "initializes cache", -> testInitCache(list) it 'adds an object to cache', -> testAddObj(list) it 'resets cache', -> testResetCache(list) it 'retrieves one object', -> testRetrieveObj(list) it 'adds objects from received pages', -> testAddsFromPage(list) it 'gets objects from a given page', -> testGetObjectsFromPage(list) it 'adds items to cache after parse', -> testAddsItemsAfterParse(list, testDataToParse, ES_COL_TYPE)
69075
describe "Paginated Collections Cache", -> #------------------------------------------------------------------------------------------------------------------- # Generic test functions #------------------------------------------------------------------------------------------------------------------- ES_COL_TYPE = 'ES' WS_COL_TYPE = 'WS' testInitCache = (list) -> expect(list.getMeta('cache')?).toBe(true) testAddObj = (list) -> testObj = name: '<NAME>' list.addObjectToCache(testObj, 1) expect(list.getMeta('cache')[1].name).toBe('test') testResetCache = (list) -> list.resetCache() expect(list.getMeta('cache')?).toBe(true) expect(Object.keys(list.getMeta('cache')).length).toBe(0) testRetrieveObj = (list) -> testObj = name: '<NAME>' list.addObjectToCache(testObj, 1) objGot = list.getObjectInCache(1) expect(objGot.name).toBe(testObj.name) testRetrieveObjs = (list) -> #------------------------------------- # No Objects in Cache #------------------------------------- startingPosition = 0 endPosition = 10 objsGot = list.getObjectsInCache(startingPosition, endPosition) expect(objsGot.length).toBe(0) #------------------------------------- # AddTestObjs #------------------------------------- numTestObjects = 10 testObjs = [] for i in [0..numTestObjects-1] newObj = name: i list.addObjectToCache(newObj, i) testObjs.push newObj #------------------------------------- # Start > End #------------------------------------- startingPosition = 1 endPosition = 0 objsGot = list.getObjectsInCache(startingPosition, endPosition) expect(objsGot.length).toBe(0) #------------------------------------- # Start == End #------------------------------------- startingPosition = 0 endPosition = 0 objsGot = list.getObjectsInCache(startingPosition, endPosition) expect(objsGot[startingPosition].name).toBe(testObjs[startingPosition].name) #------------------------------------- # Start < End #------------------------------------- startingPosition = 0 endPosition = testObjs.length - 1 objsGot = list.getObjectsInCache(startingPosition, endPosition) for i in [0..testObjs.length-1] expect(objsGot[i].name).toBe(testObjs[i].name) testGetObjectsFromPage = (list) -> #------------------------------------- # No Objects in Cache #------------------------------------- pageNum = 1 objsGot = list.getObjectsInCacheFromPage(pageNum) expect(objsGot.length).toBe(0) #------------------------------------- # AddTestObjs #------------------------------------- numTestObjects = 90 testObjs = [] for i in [0..numTestObjects-1] newObj = name: i list.addObjectToCache(newObj, i) testObjs.push newObj #------------------------------------- # Page in cache #------------------------------------- pageNum = 1 pageSize = list.getMeta('page_size') objsGot = list.getObjectsInCacheFromPage(pageNum) for i in [0..pageSize-1] expect(objsGot[i].name).toBe(testObjs[i].name) #------------------------------------- # Page not in cache at all #------------------------------------- pageNum = 20 objsGot = list.getObjectsInCacheFromPage(pageNum) expect(objsGot?).toBe(false) #------------------------------------- # Page part in cache #------------------------------------- limitPageNum = Math.floor(numTestObjects / pageSize) + 1 objsGot = list.getObjectsInCacheFromPage(limitPageNum) expect(objsGot?).toBe(false) #------------------------------------- # Last page #------------------------------------- totalPages = list.getMeta('total_pages') totalMaxItems = pageSize * totalPages itemsToRemoveInLastPage = Math.ceil(pageSize / 2) itemsToCreate = totalMaxItems - itemsToRemoveInLastPage numTestObjects = itemsToCreate testObjs = [] for i in [0..numTestObjects-1] newObj = name: i list.addObjectToCache(newObj, i) testObjs.push newObj objsGot = list.getObjectsInCacheFromPage(totalPages) pageStartingPosition = pageSize * (totalPages - 1) for i in [0..objsGot.length-1] expect(objsGot[i].name).toBe(testObjs[i + pageStartingPosition].name) testAddsFromPage = (list) -> #------------------------------------- # Page with one item #------------------------------------- pageSize = 1 objects = [] for i in [0..pageSize-1] objects.push name: i list.addObjectsToCacheFromPage(objects, 1) cache = list.getMeta('cache') expect(cache[0].name).toBe(objects[0].name) list.resetCache() #------------------------------------- # Page with multiple items #------------------------------------- pageSize = list.getMeta('page_size') objects = [] for i in [0..pageSize-1] objects.push name: i for pageNum in [1..10] list.addObjectsToCacheFromPage(objects, pageNum) cache = list.getMeta('cache') startingPosition = objects.length * (pageNum - 1) for i in [0..objects.length-1] expectedPosition = startingPosition + i expect(cache[expectedPosition].name).toBe(i) testAddsItemsAfterParse = (list, dataToParse, colType) -> list.reset(list.parse(dataToParse)) testDataToParse1 = dataToParse.es_response if colType == WS_COL_TYPE objsInData = testDataToParse1.molecules else if colType == ES_COL_TYPE objsInData = testDataToParse1.hits.hits modelsInCache = list.getObjectsInCacheFromPage 1 for i in [0..modelsInCache.length-1] idGot = modelsInCache[i].get('molecule_chembl_id') if colType == WS_COL_TYPE idInData = objsInData[i]['molecule_chembl_id'] else if colType == ES_COL_TYPE idInData = objsInData[i]._source['molecule_chembl_id'] expect(idGot).toBe(idInData) #------------------------------------------------------------------------------------------------------------------- # Specific descriptions #------------------------------------------------------------------------------------------------------------------- describe 'Collection with no caching', -> list = undefined beforeAll -> list = glados.models.paginatedCollections.PaginatedCollectionFactory.getNewTargetComponentsList() it "does not initialise cache", -> expect(list.getMeta('cache')?).toBe(false) describe 'ES Collections', -> list = undefined testDataToParse = undefined beforeAll (done) -> list = glados.models.paginatedCollections.PaginatedCollectionFactory.getNewESResultsListFor( glados.models.paginatedCollections.Settings.ES_INDEXES.COMPOUND ) list.setMeta('total_pages', 10) dataURL = glados.Settings.STATIC_URL + 'testData/ESCollectionTestData1.json' $.get dataURL, (testData) -> testDataToParse = testData done() beforeEach -> list.resetCache() it "initializes cache", -> testInitCache(list) it 'adds an object to cache', -> testAddObj(list) it 'resets cache', -> testResetCache(list) it 'retrieves one object', -> testRetrieveObj(list) it 'adds objects from received pages', -> testAddsFromPage(list) it 'gets objects from a given page', -> testGetObjectsFromPage(list) it 'adds items to cache after parse', -> testAddsItemsAfterParse(list, testDataToParse, ES_COL_TYPE)
true
describe "Paginated Collections Cache", -> #------------------------------------------------------------------------------------------------------------------- # Generic test functions #------------------------------------------------------------------------------------------------------------------- ES_COL_TYPE = 'ES' WS_COL_TYPE = 'WS' testInitCache = (list) -> expect(list.getMeta('cache')?).toBe(true) testAddObj = (list) -> testObj = name: 'PI:NAME:<NAME>END_PI' list.addObjectToCache(testObj, 1) expect(list.getMeta('cache')[1].name).toBe('test') testResetCache = (list) -> list.resetCache() expect(list.getMeta('cache')?).toBe(true) expect(Object.keys(list.getMeta('cache')).length).toBe(0) testRetrieveObj = (list) -> testObj = name: 'PI:NAME:<NAME>END_PI' list.addObjectToCache(testObj, 1) objGot = list.getObjectInCache(1) expect(objGot.name).toBe(testObj.name) testRetrieveObjs = (list) -> #------------------------------------- # No Objects in Cache #------------------------------------- startingPosition = 0 endPosition = 10 objsGot = list.getObjectsInCache(startingPosition, endPosition) expect(objsGot.length).toBe(0) #------------------------------------- # AddTestObjs #------------------------------------- numTestObjects = 10 testObjs = [] for i in [0..numTestObjects-1] newObj = name: i list.addObjectToCache(newObj, i) testObjs.push newObj #------------------------------------- # Start > End #------------------------------------- startingPosition = 1 endPosition = 0 objsGot = list.getObjectsInCache(startingPosition, endPosition) expect(objsGot.length).toBe(0) #------------------------------------- # Start == End #------------------------------------- startingPosition = 0 endPosition = 0 objsGot = list.getObjectsInCache(startingPosition, endPosition) expect(objsGot[startingPosition].name).toBe(testObjs[startingPosition].name) #------------------------------------- # Start < End #------------------------------------- startingPosition = 0 endPosition = testObjs.length - 1 objsGot = list.getObjectsInCache(startingPosition, endPosition) for i in [0..testObjs.length-1] expect(objsGot[i].name).toBe(testObjs[i].name) testGetObjectsFromPage = (list) -> #------------------------------------- # No Objects in Cache #------------------------------------- pageNum = 1 objsGot = list.getObjectsInCacheFromPage(pageNum) expect(objsGot.length).toBe(0) #------------------------------------- # AddTestObjs #------------------------------------- numTestObjects = 90 testObjs = [] for i in [0..numTestObjects-1] newObj = name: i list.addObjectToCache(newObj, i) testObjs.push newObj #------------------------------------- # Page in cache #------------------------------------- pageNum = 1 pageSize = list.getMeta('page_size') objsGot = list.getObjectsInCacheFromPage(pageNum) for i in [0..pageSize-1] expect(objsGot[i].name).toBe(testObjs[i].name) #------------------------------------- # Page not in cache at all #------------------------------------- pageNum = 20 objsGot = list.getObjectsInCacheFromPage(pageNum) expect(objsGot?).toBe(false) #------------------------------------- # Page part in cache #------------------------------------- limitPageNum = Math.floor(numTestObjects / pageSize) + 1 objsGot = list.getObjectsInCacheFromPage(limitPageNum) expect(objsGot?).toBe(false) #------------------------------------- # Last page #------------------------------------- totalPages = list.getMeta('total_pages') totalMaxItems = pageSize * totalPages itemsToRemoveInLastPage = Math.ceil(pageSize / 2) itemsToCreate = totalMaxItems - itemsToRemoveInLastPage numTestObjects = itemsToCreate testObjs = [] for i in [0..numTestObjects-1] newObj = name: i list.addObjectToCache(newObj, i) testObjs.push newObj objsGot = list.getObjectsInCacheFromPage(totalPages) pageStartingPosition = pageSize * (totalPages - 1) for i in [0..objsGot.length-1] expect(objsGot[i].name).toBe(testObjs[i + pageStartingPosition].name) testAddsFromPage = (list) -> #------------------------------------- # Page with one item #------------------------------------- pageSize = 1 objects = [] for i in [0..pageSize-1] objects.push name: i list.addObjectsToCacheFromPage(objects, 1) cache = list.getMeta('cache') expect(cache[0].name).toBe(objects[0].name) list.resetCache() #------------------------------------- # Page with multiple items #------------------------------------- pageSize = list.getMeta('page_size') objects = [] for i in [0..pageSize-1] objects.push name: i for pageNum in [1..10] list.addObjectsToCacheFromPage(objects, pageNum) cache = list.getMeta('cache') startingPosition = objects.length * (pageNum - 1) for i in [0..objects.length-1] expectedPosition = startingPosition + i expect(cache[expectedPosition].name).toBe(i) testAddsItemsAfterParse = (list, dataToParse, colType) -> list.reset(list.parse(dataToParse)) testDataToParse1 = dataToParse.es_response if colType == WS_COL_TYPE objsInData = testDataToParse1.molecules else if colType == ES_COL_TYPE objsInData = testDataToParse1.hits.hits modelsInCache = list.getObjectsInCacheFromPage 1 for i in [0..modelsInCache.length-1] idGot = modelsInCache[i].get('molecule_chembl_id') if colType == WS_COL_TYPE idInData = objsInData[i]['molecule_chembl_id'] else if colType == ES_COL_TYPE idInData = objsInData[i]._source['molecule_chembl_id'] expect(idGot).toBe(idInData) #------------------------------------------------------------------------------------------------------------------- # Specific descriptions #------------------------------------------------------------------------------------------------------------------- describe 'Collection with no caching', -> list = undefined beforeAll -> list = glados.models.paginatedCollections.PaginatedCollectionFactory.getNewTargetComponentsList() it "does not initialise cache", -> expect(list.getMeta('cache')?).toBe(false) describe 'ES Collections', -> list = undefined testDataToParse = undefined beforeAll (done) -> list = glados.models.paginatedCollections.PaginatedCollectionFactory.getNewESResultsListFor( glados.models.paginatedCollections.Settings.ES_INDEXES.COMPOUND ) list.setMeta('total_pages', 10) dataURL = glados.Settings.STATIC_URL + 'testData/ESCollectionTestData1.json' $.get dataURL, (testData) -> testDataToParse = testData done() beforeEach -> list.resetCache() it "initializes cache", -> testInitCache(list) it 'adds an object to cache', -> testAddObj(list) it 'resets cache', -> testResetCache(list) it 'retrieves one object', -> testRetrieveObj(list) it 'adds objects from received pages', -> testAddsFromPage(list) it 'gets objects from a given page', -> testGetObjectsFromPage(list) it 'adds items to cache after parse', -> testAddsItemsAfterParse(list, testDataToParse, ES_COL_TYPE)
[ { "context": ">\n <tr>\n <td rowspan=\"2\">1</td>\n <td>Mark</td>\n <td>Otto</td>\n <td>@mdo</td>\n ", "end": 704, "score": 0.9991576671600342, "start": 700, "tag": "NAME", "value": "Mark" }, { "context": " rowspan=\"2\">1</td>\n <td>Mark</td>\n <td>Otto</td>\n <td>@mdo</td>\n </tr>\n <tr>\n ", "end": 724, "score": 0.9964768290519714, "start": 720, "tag": "NAME", "value": "Otto" }, { "context": " <td>Mark</td>\n <td>Otto</td>\n <td>@mdo</td>\n </tr>\n <tr>\n <td>Mark</td>\n ", "end": 744, "score": 0.8703486323356628, "start": 741, "tag": "USERNAME", "value": "mdo" }, { "context": "\n <td>@mdo</td>\n </tr>\n <tr>\n <td>Mark</td>\n <td>Otto</td>\n <td>@TwBootstrap</", "end": 783, "score": 0.9986642599105835, "start": 779, "tag": "NAME", "value": "Mark" }, { "context": "\n </tr>\n <tr>\n <td>Mark</td>\n <td>Otto</td>\n <td>@TwBootstrap</td>\n </tr>\n <t", "end": 803, "score": 0.9919052124023438, "start": 799, "tag": "NAME", "value": "Otto" }, { "context": " <td>Mark</td>\n <td>Otto</td>\n <td>@TwBootstrap</td>\n </tr>\n <tr>\n <td>2</td>\n <t", "end": 831, "score": 0.8975703716278076, "start": 820, "tag": "USERNAME", "value": "TwBootstrap" }, { "context": "td>\n </tr>\n <tr>\n <td>2</td>\n <td>Jacob</td>\n <td>Thornton</td>\n <td>@fat</td>\n", "end": 888, "score": 0.9976931810379028, "start": 883, "tag": "NAME", "value": "Jacob" }, { "context": ">\n <td>2</td>\n <td>Jacob</td>\n <td>Thornton</td>\n <td>@fat</td>\n </tr>\n <tr>\n ", "end": 912, "score": 0.7442024946212769, "start": 904, "tag": "NAME", "value": "Thornton" }, { "context": "<td>Jacob</td>\n <td>Thornton</td>\n <td>@fat</td>\n </tr>\n <tr>\n <td>3</td>\n <t", "end": 932, "score": 0.4257759749889374, "start": 929, "tag": "USERNAME", "value": "fat" }, { "context": ">\n <tr>\n <td>3</td>\n <td colspan=\"2\">Larry the Bird</td>\n <td>@twitter</td>\n </tr>\n </tbody>", "end": 1010, "score": 0.8842310905456543, "start": 996, "tag": "NAME", "value": "Larry the Bird" } ]
snippets/html-table.cson
liuin/liuin-snp
0
'.text.html, .source.js, .source.css': 'html-table//表格': 'prefix' : "html-table" 'body':""" <style type="text/css"> .table-bordered {border: 1px solid #ddd;border-collapse: collapse;border-left: 0;-webkit-border-radius: 4px;-moz-border-radius: 4px;border-radius: 4px;border-top:0;border-spacing: 0;} .table-bordered td, .table-bordered th {padding: 8px;line-height: 20px;text-align: left;vertical-align: top;border: 1px solid #ddd;} </style> <!-- start table --> <table class="table-bordered"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <td rowspan="2">1</td> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <td>Mark</td> <td>Otto</td> <td>@TwBootstrap</td> </tr> <tr> <td>2</td> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <td>3</td> <td colspan="2">Larry the Bird</td> <td>@twitter</td> </tr> </tbody> </table> <!-- end table --> """
4525
'.text.html, .source.js, .source.css': 'html-table//表格': 'prefix' : "html-table" 'body':""" <style type="text/css"> .table-bordered {border: 1px solid #ddd;border-collapse: collapse;border-left: 0;-webkit-border-radius: 4px;-moz-border-radius: 4px;border-radius: 4px;border-top:0;border-spacing: 0;} .table-bordered td, .table-bordered th {padding: 8px;line-height: 20px;text-align: left;vertical-align: top;border: 1px solid #ddd;} </style> <!-- start table --> <table class="table-bordered"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <td rowspan="2">1</td> <td><NAME></td> <td><NAME></td> <td>@mdo</td> </tr> <tr> <td><NAME></td> <td><NAME></td> <td>@TwBootstrap</td> </tr> <tr> <td>2</td> <td><NAME></td> <td><NAME></td> <td>@fat</td> </tr> <tr> <td>3</td> <td colspan="2"><NAME></td> <td>@twitter</td> </tr> </tbody> </table> <!-- end table --> """
true
'.text.html, .source.js, .source.css': 'html-table//表格': 'prefix' : "html-table" 'body':""" <style type="text/css"> .table-bordered {border: 1px solid #ddd;border-collapse: collapse;border-left: 0;-webkit-border-radius: 4px;-moz-border-radius: 4px;border-radius: 4px;border-top:0;border-spacing: 0;} .table-bordered td, .table-bordered th {padding: 8px;line-height: 20px;text-align: left;vertical-align: top;border: 1px solid #ddd;} </style> <!-- start table --> <table class="table-bordered"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> </tr> </thead> <tbody> <tr> <td rowspan="2">1</td> <td>PI:NAME:<NAME>END_PI</td> <td>PI:NAME:<NAME>END_PI</td> <td>@mdo</td> </tr> <tr> <td>PI:NAME:<NAME>END_PI</td> <td>PI:NAME:<NAME>END_PI</td> <td>@TwBootstrap</td> </tr> <tr> <td>2</td> <td>PI:NAME:<NAME>END_PI</td> <td>PI:NAME:<NAME>END_PI</td> <td>@fat</td> </tr> <tr> <td>3</td> <td colspan="2">PI:NAME:<NAME>END_PI</td> <td>@twitter</td> </tr> </tbody> </table> <!-- end table --> """
[ { "context": "st 'pathWithFingerprint', ->\n fingerprint = '67574c7b406bb0064c686db97d00943e'\n expected = \"some/file-#{fingerpr", "end": 643, "score": 0.5152548551559448, "start": 625, "tag": "PASSWORD", "value": "574c7b406bb0064c68" }, { "context": "rint', ->\n fingerprint = '67574c7b406bb0064c686db97d00943e'\n expected = \"some/file-#{fingerprint}.js\"\n\n ", "end": 655, "score": 0.5378583669662476, "start": 644, "tag": "PASSWORD", "value": "db97d00943e" } ]
test/cases/support/server/fileTest.coffee
jivagoalves/tower
1
describe 'Tower.File', -> path = null beforeEach -> path = 'test/example/server.js' test 'stat', (done) -> assert.ok !!Tower.statSync(path) Tower.stat path, (error, stat) => assert.ok !!stat done() test 'fingerprint', -> expected = '67574c7b406bb0064c686db97d00943e' string = Tower.readFileSync(path) assert.equal expected, Tower.fingerprint(string) test 'pathFingerprint', -> expected = '67574c7b406bb0064c686db97d00943e' assert.equal Tower.pathFingerprint("some/file-#{expected}.js"), expected test 'pathWithFingerprint', -> fingerprint = '67574c7b406bb0064c686db97d00943e' expected = "some/file-#{fingerprint}.js" assert.equal Tower.pathWithFingerprint('some/file.js', fingerprint), expected test 'contentType', -> expected = 'application/javascript' assert.equal Tower.contentType(path), expected test 'mtime', (done) -> assert.isTrue Tower.mtimeSync(path) instanceof Date Tower.mtime path, (error, mtime) => assert.isTrue mtime instanceof Date done() test 'size', (done) -> expected = 343 assert.equal Tower.sizeSync(path), expected Tower.size path, (error, size) => assert.equal size, expected done() test 'should find entries in a directory', (done) -> dir = 'test/example/app/controllers/server' expected = [ 'applicationController.coffee', 'attachmentsController.coffee', 'controllerScopesMetadataController.coffee', 'customController.coffee', 'headersController.coffee', 'postsController.coffee', 'sessionsController.coffee', 'testJsonController.coffee', 'testRoutesController.coffee', 'usersController.coffee' ].sort() assert.deepEqual Tower.entriesSync(dir).sort(), expected Tower.entries dir, (error, entries) => assert.deepEqual entries.sort(), expected done() test 'absolutePath', -> expected = Tower.join(process.cwd(), path) assert.equal Tower.absolutePath(path), expected test 'relativePath', -> expected = path assert.equal Tower.relativePath(path), expected test 'extensions', -> expected = ['.js', '.coffee'] assert.deepEqual Tower.extensions('something.js.coffee'), expected test 'glob files', -> dir = 'test/example/app/controllers/server' expected = _.map [ 'applicationController.coffee', 'attachmentsController.coffee', 'controllerScopesMetadataController.coffee', 'customController.coffee', 'headersController.coffee', 'postsController.coffee', 'sessionsController.coffee', 'testJsonController.coffee', 'testRoutesController.coffee', 'usersController.coffee' ].sort(), (i) -> Tower.join(dir, i) assert.deepEqual Tower.files(dir).sort(), expected assert.deepEqual Tower.files([dir]).sort(), expected
92622
describe 'Tower.File', -> path = null beforeEach -> path = 'test/example/server.js' test 'stat', (done) -> assert.ok !!Tower.statSync(path) Tower.stat path, (error, stat) => assert.ok !!stat done() test 'fingerprint', -> expected = '67574c7b406bb0064c686db97d00943e' string = Tower.readFileSync(path) assert.equal expected, Tower.fingerprint(string) test 'pathFingerprint', -> expected = '67574c7b406bb0064c686db97d00943e' assert.equal Tower.pathFingerprint("some/file-#{expected}.js"), expected test 'pathWithFingerprint', -> fingerprint = '67<PASSWORD>6<PASSWORD>' expected = "some/file-#{fingerprint}.js" assert.equal Tower.pathWithFingerprint('some/file.js', fingerprint), expected test 'contentType', -> expected = 'application/javascript' assert.equal Tower.contentType(path), expected test 'mtime', (done) -> assert.isTrue Tower.mtimeSync(path) instanceof Date Tower.mtime path, (error, mtime) => assert.isTrue mtime instanceof Date done() test 'size', (done) -> expected = 343 assert.equal Tower.sizeSync(path), expected Tower.size path, (error, size) => assert.equal size, expected done() test 'should find entries in a directory', (done) -> dir = 'test/example/app/controllers/server' expected = [ 'applicationController.coffee', 'attachmentsController.coffee', 'controllerScopesMetadataController.coffee', 'customController.coffee', 'headersController.coffee', 'postsController.coffee', 'sessionsController.coffee', 'testJsonController.coffee', 'testRoutesController.coffee', 'usersController.coffee' ].sort() assert.deepEqual Tower.entriesSync(dir).sort(), expected Tower.entries dir, (error, entries) => assert.deepEqual entries.sort(), expected done() test 'absolutePath', -> expected = Tower.join(process.cwd(), path) assert.equal Tower.absolutePath(path), expected test 'relativePath', -> expected = path assert.equal Tower.relativePath(path), expected test 'extensions', -> expected = ['.js', '.coffee'] assert.deepEqual Tower.extensions('something.js.coffee'), expected test 'glob files', -> dir = 'test/example/app/controllers/server' expected = _.map [ 'applicationController.coffee', 'attachmentsController.coffee', 'controllerScopesMetadataController.coffee', 'customController.coffee', 'headersController.coffee', 'postsController.coffee', 'sessionsController.coffee', 'testJsonController.coffee', 'testRoutesController.coffee', 'usersController.coffee' ].sort(), (i) -> Tower.join(dir, i) assert.deepEqual Tower.files(dir).sort(), expected assert.deepEqual Tower.files([dir]).sort(), expected
true
describe 'Tower.File', -> path = null beforeEach -> path = 'test/example/server.js' test 'stat', (done) -> assert.ok !!Tower.statSync(path) Tower.stat path, (error, stat) => assert.ok !!stat done() test 'fingerprint', -> expected = '67574c7b406bb0064c686db97d00943e' string = Tower.readFileSync(path) assert.equal expected, Tower.fingerprint(string) test 'pathFingerprint', -> expected = '67574c7b406bb0064c686db97d00943e' assert.equal Tower.pathFingerprint("some/file-#{expected}.js"), expected test 'pathWithFingerprint', -> fingerprint = '67PI:PASSWORD:<PASSWORD>END_PI6PI:PASSWORD:<PASSWORD>END_PI' expected = "some/file-#{fingerprint}.js" assert.equal Tower.pathWithFingerprint('some/file.js', fingerprint), expected test 'contentType', -> expected = 'application/javascript' assert.equal Tower.contentType(path), expected test 'mtime', (done) -> assert.isTrue Tower.mtimeSync(path) instanceof Date Tower.mtime path, (error, mtime) => assert.isTrue mtime instanceof Date done() test 'size', (done) -> expected = 343 assert.equal Tower.sizeSync(path), expected Tower.size path, (error, size) => assert.equal size, expected done() test 'should find entries in a directory', (done) -> dir = 'test/example/app/controllers/server' expected = [ 'applicationController.coffee', 'attachmentsController.coffee', 'controllerScopesMetadataController.coffee', 'customController.coffee', 'headersController.coffee', 'postsController.coffee', 'sessionsController.coffee', 'testJsonController.coffee', 'testRoutesController.coffee', 'usersController.coffee' ].sort() assert.deepEqual Tower.entriesSync(dir).sort(), expected Tower.entries dir, (error, entries) => assert.deepEqual entries.sort(), expected done() test 'absolutePath', -> expected = Tower.join(process.cwd(), path) assert.equal Tower.absolutePath(path), expected test 'relativePath', -> expected = path assert.equal Tower.relativePath(path), expected test 'extensions', -> expected = ['.js', '.coffee'] assert.deepEqual Tower.extensions('something.js.coffee'), expected test 'glob files', -> dir = 'test/example/app/controllers/server' expected = _.map [ 'applicationController.coffee', 'attachmentsController.coffee', 'controllerScopesMetadataController.coffee', 'customController.coffee', 'headersController.coffee', 'postsController.coffee', 'sessionsController.coffee', 'testJsonController.coffee', 'testRoutesController.coffee', 'usersController.coffee' ].sort(), (i) -> Tower.join(dir, i) assert.deepEqual Tower.files(dir).sort(), expected assert.deepEqual Tower.files([dir]).sort(), expected
[ { "context": "9f4a03-086f-4108-a32f-99ed775655c7\",\"spotify_id\":\"6WK9dVrRABMkUXFLNlgWFh\",\n \"nr\":6,\"mast", "end": 4142, "score": 0.6543031334877014, "start": 4141, "tag": "KEY", "value": "6" } ]
spec/javascripts/jquery-music_metadata/track_spec.js.coffee
volontariat/jquery-discography
1
describe 'MusicMetadata.Track', -> beforeEach -> jasmine.Ajax.install() window.alert = jasmine.createSpy() affix '#music_track_page[data-track-id="74"]' jasmine.Ajax.requests.reset() describe '#showMetadata and #showVideos', -> describe 'successful response', -> describe 'successful videos response', -> describe 'with videos', -> it 'adds a breadcrumb with an artist link, release link plus track name and list with 1 video', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.at(0) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') body = """ { "id":74,"mbid":"2b9f4a03-086f-4108-a32f-99ed775655c7","spotify_id":"6WK9dVrRABMkUXFLNlgWFh", "nr":6,"master_track_id":null,"artist_id":1,"artist_name":"Depeche Mode","name":"Enjoy The Silence", "release_id":8,"release_name":"Violator","duration":"06:13","released_at":"1990-02-21T00:00:00Z", "listeners":796647,"plays":5947341,"state":"active" } """ request.respondWith status: 200 responseText: body request = jasmine.Ajax.requests.at(1) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74/videos.json') body = """ [ { "id":1,"status":"Official","artist_id":1,"artist_name":"Depeche Mode","track_id":74, "track_name":"Enjoy The Silence","url":"https://vimeo.com/26842471" } ] """ request.respondWith status: 200 responseText: body expect($('.breadcrumb .music_artist_link:contains("Depeche Mode")').length).toBe(1) expect($('.breadcrumb .music_release_link:contains("Violator")').length).toBe(1) expect($('.breadcrumb .active:contains("Enjoy The Silence")').length).toBe(1) expect($($('#music_videos a')[0]).attr('href')).toBe('https://vimeo.com/26842471') describe 'without tracks', -> it 'it adds an error message as first row of tracks', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.at(0) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') body = """ { "id":74,"mbid":"2b9f4a03-086f-4108-a32f-99ed775655c7","spotify_id":"6WK9dVrRABMkUXFLNlgWFh", "nr":6,"master_track_id":null,"artist_id":1,"artist_name":"Depeche Mode","name":"Enjoy The Silence", "release_id":8,"release_name":"Violator","duration":"06:13","released_at":"1990-02-21T00:00:00Z", "listeners":796647,"plays":5947341,"state":"active" } """ request.respondWith status: 200 responseText: body request = jasmine.Ajax.requests.at(1) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74/videos.json') request.respondWith status: 200 responseText: "[]" expect($('.breadcrumb .music_artist_link:contains("Depeche Mode")').length).toBe(1) expect($('.breadcrumb .music_release_link:contains("Violator")').length).toBe(1) expect($('.breadcrumb .active:contains("Enjoy The Silence")').length).toBe(1) expect($('#music_videos:contains("No videos available!")').length).toBe(1) describe 'faulty videos response', -> it 'it adds an error message as first row of tracks', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.at(0) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') body = """ { "id":74,"mbid":"2b9f4a03-086f-4108-a32f-99ed775655c7","spotify_id":"6WK9dVrRABMkUXFLNlgWFh", "nr":6,"master_track_id":null,"artist_id":1,"artist_name":"Depeche Mode","name":"Enjoy The Silence", "release_id":8,"release_name":"Violator","duration":"06:13","released_at":"1990-02-21T00:00:00Z", "listeners":796647,"plays":5947341,"state":"active" } """ request.respondWith status: 200 responseText: body request = jasmine.Ajax.requests.at(1) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74/videos.json') request.respondWith status: 500 responseText: "[]" expect($('.breadcrumb .music_artist_link:contains("Depeche Mode")').length).toBe(1) expect($('.breadcrumb .music_release_link:contains("Violator")').length).toBe(1) expect($('.breadcrumb .active:contains("Enjoy The Silence")').length).toBe(1) expect($('#music_videos:contains("Failed to load videos!")').length).toBe(1) describe 'faulty response', -> describe 'status is 404', -> it 'alerts an message', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.mostRecent() expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') request.respondWith status: 404 responseText: "{}" expect(window.alert).toHaveBeenCalledWith('Track not found!') describe 'status is other than 404', -> it 'alerts an message', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.mostRecent(0) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') request.respondWith status: 500 responseText: "{}" expect(window.alert).toHaveBeenCalledWith('Failed to load track!')
222806
describe 'MusicMetadata.Track', -> beforeEach -> jasmine.Ajax.install() window.alert = jasmine.createSpy() affix '#music_track_page[data-track-id="74"]' jasmine.Ajax.requests.reset() describe '#showMetadata and #showVideos', -> describe 'successful response', -> describe 'successful videos response', -> describe 'with videos', -> it 'adds a breadcrumb with an artist link, release link plus track name and list with 1 video', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.at(0) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') body = """ { "id":74,"mbid":"2b9f4a03-086f-4108-a32f-99ed775655c7","spotify_id":"6WK9dVrRABMkUXFLNlgWFh", "nr":6,"master_track_id":null,"artist_id":1,"artist_name":"Depeche Mode","name":"Enjoy The Silence", "release_id":8,"release_name":"Violator","duration":"06:13","released_at":"1990-02-21T00:00:00Z", "listeners":796647,"plays":5947341,"state":"active" } """ request.respondWith status: 200 responseText: body request = jasmine.Ajax.requests.at(1) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74/videos.json') body = """ [ { "id":1,"status":"Official","artist_id":1,"artist_name":"Depeche Mode","track_id":74, "track_name":"Enjoy The Silence","url":"https://vimeo.com/26842471" } ] """ request.respondWith status: 200 responseText: body expect($('.breadcrumb .music_artist_link:contains("Depeche Mode")').length).toBe(1) expect($('.breadcrumb .music_release_link:contains("Violator")').length).toBe(1) expect($('.breadcrumb .active:contains("Enjoy The Silence")').length).toBe(1) expect($($('#music_videos a')[0]).attr('href')).toBe('https://vimeo.com/26842471') describe 'without tracks', -> it 'it adds an error message as first row of tracks', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.at(0) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') body = """ { "id":74,"mbid":"2b9f4a03-086f-4108-a32f-99ed775655c7","spotify_id":"6WK9dVrRABMkUXFLNlgWFh", "nr":6,"master_track_id":null,"artist_id":1,"artist_name":"Depeche Mode","name":"Enjoy The Silence", "release_id":8,"release_name":"Violator","duration":"06:13","released_at":"1990-02-21T00:00:00Z", "listeners":796647,"plays":5947341,"state":"active" } """ request.respondWith status: 200 responseText: body request = jasmine.Ajax.requests.at(1) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74/videos.json') request.respondWith status: 200 responseText: "[]" expect($('.breadcrumb .music_artist_link:contains("Depeche Mode")').length).toBe(1) expect($('.breadcrumb .music_release_link:contains("Violator")').length).toBe(1) expect($('.breadcrumb .active:contains("Enjoy The Silence")').length).toBe(1) expect($('#music_videos:contains("No videos available!")').length).toBe(1) describe 'faulty videos response', -> it 'it adds an error message as first row of tracks', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.at(0) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') body = """ { "id":74,"mbid":"2b9f4a03-086f-4108-a32f-99ed775655c7","spotify_id":"<KEY>WK9dVrRABMkUXFLNlgWFh", "nr":6,"master_track_id":null,"artist_id":1,"artist_name":"Depeche Mode","name":"Enjoy The Silence", "release_id":8,"release_name":"Violator","duration":"06:13","released_at":"1990-02-21T00:00:00Z", "listeners":796647,"plays":5947341,"state":"active" } """ request.respondWith status: 200 responseText: body request = jasmine.Ajax.requests.at(1) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74/videos.json') request.respondWith status: 500 responseText: "[]" expect($('.breadcrumb .music_artist_link:contains("Depeche Mode")').length).toBe(1) expect($('.breadcrumb .music_release_link:contains("Violator")').length).toBe(1) expect($('.breadcrumb .active:contains("Enjoy The Silence")').length).toBe(1) expect($('#music_videos:contains("Failed to load videos!")').length).toBe(1) describe 'faulty response', -> describe 'status is 404', -> it 'alerts an message', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.mostRecent() expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') request.respondWith status: 404 responseText: "{}" expect(window.alert).toHaveBeenCalledWith('Track not found!') describe 'status is other than 404', -> it 'alerts an message', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.mostRecent(0) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') request.respondWith status: 500 responseText: "{}" expect(window.alert).toHaveBeenCalledWith('Failed to load track!')
true
describe 'MusicMetadata.Track', -> beforeEach -> jasmine.Ajax.install() window.alert = jasmine.createSpy() affix '#music_track_page[data-track-id="74"]' jasmine.Ajax.requests.reset() describe '#showMetadata and #showVideos', -> describe 'successful response', -> describe 'successful videos response', -> describe 'with videos', -> it 'adds a breadcrumb with an artist link, release link plus track name and list with 1 video', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.at(0) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') body = """ { "id":74,"mbid":"2b9f4a03-086f-4108-a32f-99ed775655c7","spotify_id":"6WK9dVrRABMkUXFLNlgWFh", "nr":6,"master_track_id":null,"artist_id":1,"artist_name":"Depeche Mode","name":"Enjoy The Silence", "release_id":8,"release_name":"Violator","duration":"06:13","released_at":"1990-02-21T00:00:00Z", "listeners":796647,"plays":5947341,"state":"active" } """ request.respondWith status: 200 responseText: body request = jasmine.Ajax.requests.at(1) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74/videos.json') body = """ [ { "id":1,"status":"Official","artist_id":1,"artist_name":"Depeche Mode","track_id":74, "track_name":"Enjoy The Silence","url":"https://vimeo.com/26842471" } ] """ request.respondWith status: 200 responseText: body expect($('.breadcrumb .music_artist_link:contains("Depeche Mode")').length).toBe(1) expect($('.breadcrumb .music_release_link:contains("Violator")').length).toBe(1) expect($('.breadcrumb .active:contains("Enjoy The Silence")').length).toBe(1) expect($($('#music_videos a')[0]).attr('href')).toBe('https://vimeo.com/26842471') describe 'without tracks', -> it 'it adds an error message as first row of tracks', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.at(0) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') body = """ { "id":74,"mbid":"2b9f4a03-086f-4108-a32f-99ed775655c7","spotify_id":"6WK9dVrRABMkUXFLNlgWFh", "nr":6,"master_track_id":null,"artist_id":1,"artist_name":"Depeche Mode","name":"Enjoy The Silence", "release_id":8,"release_name":"Violator","duration":"06:13","released_at":"1990-02-21T00:00:00Z", "listeners":796647,"plays":5947341,"state":"active" } """ request.respondWith status: 200 responseText: body request = jasmine.Ajax.requests.at(1) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74/videos.json') request.respondWith status: 200 responseText: "[]" expect($('.breadcrumb .music_artist_link:contains("Depeche Mode")').length).toBe(1) expect($('.breadcrumb .music_release_link:contains("Violator")').length).toBe(1) expect($('.breadcrumb .active:contains("Enjoy The Silence")').length).toBe(1) expect($('#music_videos:contains("No videos available!")').length).toBe(1) describe 'faulty videos response', -> it 'it adds an error message as first row of tracks', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.at(0) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') body = """ { "id":74,"mbid":"2b9f4a03-086f-4108-a32f-99ed775655c7","spotify_id":"PI:KEY:<KEY>END_PIWK9dVrRABMkUXFLNlgWFh", "nr":6,"master_track_id":null,"artist_id":1,"artist_name":"Depeche Mode","name":"Enjoy The Silence", "release_id":8,"release_name":"Violator","duration":"06:13","released_at":"1990-02-21T00:00:00Z", "listeners":796647,"plays":5947341,"state":"active" } """ request.respondWith status: 200 responseText: body request = jasmine.Ajax.requests.at(1) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74/videos.json') request.respondWith status: 500 responseText: "[]" expect($('.breadcrumb .music_artist_link:contains("Depeche Mode")').length).toBe(1) expect($('.breadcrumb .music_release_link:contains("Violator")').length).toBe(1) expect($('.breadcrumb .active:contains("Enjoy The Silence")').length).toBe(1) expect($('#music_videos:contains("Failed to load videos!")').length).toBe(1) describe 'faulty response', -> describe 'status is 404', -> it 'alerts an message', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.mostRecent() expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') request.respondWith status: 404 responseText: "{}" expect(window.alert).toHaveBeenCalledWith('Track not found!') describe 'status is other than 404', -> it 'alerts an message', -> $('#music_track_page').musicTrack() request = jasmine.Ajax.requests.mostRecent(0) expect(request.url).toBe('http://Volontari.at/api/v1/music/tracks/74.json') request.respondWith status: 500 responseText: "{}" expect(window.alert).toHaveBeenCalledWith('Failed to load track!')
[ { "context": "bject.assign {}, users_fixture.austin, username: 'jeffrey'\n @fetches.first.respond_with\n bo", "end": 719, "score": 0.9996705055236816, "start": 712, "tag": "USERNAME", "value": "jeffrey" }, { "context": "username]'\n @fill_in(input_username).with 'jeffrey'\n expect(@wrapper.vm.username).to.eql 'jef", "end": 3293, "score": 0.9996375441551208, "start": 3286, "tag": "USERNAME", "value": "jeffrey" }, { "context": "rey'\n expect(@wrapper.vm.username).to.eql 'jeffrey'\n @wrapper.first('form').trigger 'submit'\n", "end": 3347, "score": 0.9996686577796936, "start": 3340, "tag": "USERNAME", "value": "jeffrey" }, { "context": "ect(@fetches.first.body).to.eql\n email: 'austin@makes.audio'\n username: 'jeffrey'\n\n form_submis", "end": 3737, "score": 0.9999173283576965, "start": 3719, "tag": "EMAIL", "value": "austin@makes.audio" }, { "context": " email: 'austin@makes.audio'\n username: 'jeffrey'\n\n form_submission_on_success()\n form_s", "end": 3767, "score": 0.9996853470802307, "start": 3760, "tag": "USERNAME", "value": "jeffrey" }, { "context": "[name=email]'\n @fill_in(input_email).with 'austin@bakes.audio'\n expect(@wrapper.vm.email).to.eql 'austin", "end": 4050, "score": 0.9999234080314636, "start": 4032, "tag": "EMAIL", "value": "austin@bakes.audio" }, { "context": ".audio'\n expect(@wrapper.vm.email).to.eql 'austin@bakes.audio'\n @wrapper.first('form').trigger 'submit'\n", "end": 4112, "score": 0.9999228715896606, "start": 4094, "tag": "EMAIL", "value": "austin@bakes.audio" }, { "context": "ect(@fetches.first.body).to.eql\n email: 'austin@bakes.audio'\n username: 'austin'\n\n form_submiss", "end": 4502, "score": 0.9999216198921204, "start": 4484, "tag": "EMAIL", "value": "austin@bakes.audio" }, { "context": " email: 'austin@bakes.audio'\n username: 'austin'\n\n form_submission_on_success()\n form_s", "end": 4531, "score": 0.999366283416748, "start": 4525, "tag": "USERNAME", "value": "austin" }, { "context": "password]'\n @fill_in(input_password).with 'donkey7'\n input_password = @wrapper.first 'input[n", "end": 4815, "score": 0.9991803169250488, "start": 4808, "tag": "PASSWORD", "value": "donkey7" }, { "context": "Password]'\n @fill_in(input_password).with 'apple'\n\n expect(@wrapper.vm.password).to.eql 'do", "end": 4931, "score": 0.9992355108261108, "start": 4926, "tag": "PASSWORD", "value": "apple" }, { "context": "le'\n\n expect(@wrapper.vm.password).to.eql 'donkey7'\n expect(@wrapper.vm.currentPassword).to.e", "end": 4986, "score": 0.9992435574531555, "start": 4979, "tag": "PASSWORD", "value": "donkey7" }, { "context": " expect(@wrapper.vm.currentPassword).to.eql 'apple'\n\n @wrapper.find('form')[1].trigger 'submi", "end": 5045, "score": 0.9993476271629333, "start": 5040, "tag": "PASSWORD", "value": "apple" }, { "context": "(@fetches.first.body).to.eql\n password: 'donkey7'\n currentPassword: 'apple'\n\n descri", "end": 5430, "score": 0.9992097020149231, "start": 5423, "tag": "PASSWORD", "value": "donkey7" }, { "context": " password: 'donkey7'\n currentPassword: 'apple'\n\n describe 'on success', ->\n beforeE", "end": 5465, "score": 0.9993762373924255, "start": 5460, "tag": "PASSWORD", "value": "apple" }, { "context": " @store, propsData:\n user: users_fixture.austin\n email_preferences: email_preferences_fi", "end": 6328, "score": 0.8356468677520752, "start": 6322, "tag": "USERNAME", "value": "austin" }, { "context": "@store, propsData:\n user: users_fixture.austin\n email_preferences: email_preferences_fi", "end": 6659, "score": 0.8972547054290771, "start": 6654, "tag": "USERNAME", "value": "ustin" } ]
ui/src/components/settings/user_form.test.coffee
jozsefsallai/makes.audio
4
import user_form from './user_form' import { mount } from 'avoriaz' import Vue, { nextTick } from 'vue' import Vuex from 'vuex' import sinon from 'sinon' import users_fixture from 'fixtures/users' import email_preferences_fixture from 'fixtures/email_preferences' import Toaster from 'lib/toaster' Vue.use Vuex describe 'user-form', -> beforeEach -> sinon.stub Toaster, 'create' @mutations = set_user: sinon.spy() @store = new Vuex.Store state: {} mutations: @mutations afterEach -> Toaster.create.restore() form_submission_on_success = -> describe 'on success', -> beforeEach (done) -> @new_user = Object.assign {}, users_fixture.austin, username: 'jeffrey' @fetches.first.respond_with body: ok: true user: @new_user setImmediate done it 'should commit to store', -> set_user = @mutations.set_user expect(set_user).to.have.been.calledWith sinon.match.object, @new_user it 'should create toast', -> expect Toaster.create .to.have.been.calledWith 'success', 'You’ve been updated.', 'Great!' it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false form_submission_on_server_error = -> describe 'on server error', -> beforeEach (done) -> @fetches.first.respond_with body: ok: false setImmediate done it 'should not commit to store', -> expect(@mutations.set_user).to.not.have.been.called it 'should create toast', -> expect(Toaster.create).to.have.been .calledWith 'danger', 'Please try again later.', 'Server Error!' it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false form_submission_on_client_error = -> describe 'on client error', -> beforeEach (done) -> @fetches.first.respond_with body: ok: false errors: [( code: 'WRONG_PASSWORD' )] setImmediate done it 'should not commit to store', -> expect(@mutations.set_user).to.not.have.been.called it 'should create toast', -> expect(Toaster.create).to.have.been .calledWith 'warning', 'The current password wasn’t correct.' it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false describe 'loading state', -> beforeEach -> @wrapper = mount user_form, store: @store, propsData: user: users_fixture.austin email_preferences: email_preferences_fixture.verified @wrapper.vm.loading = true nextTick() it 'should disable inputs', -> @wrapper.find('input').forEach (input) -> expect(input.element.getAttribute('disabled')).to.eql 'disabled' @wrapper.find('button').forEach (input) -> expect(input.element.getAttribute('disabled')).to.eql 'disabled' describe 'behavior', -> beforeEach -> @wrapper = mount user_form, store: @store, propsData: user: users_fixture.austin email_preferences: email_preferences_fixture.verified describe 'setting username', -> beforeEach -> input_username = @wrapper.first 'input[name=username]' @fill_in(input_username).with 'jeffrey' expect(@wrapper.vm.username).to.eql 'jeffrey' @wrapper.first('form').trigger 'submit' it 'should be in loading state', -> expect(@wrapper.vm.loading).to.be.true it 'should update record', -> expect(@fetches.first).to.include method: 'PUT' url: '/api/users/me' credentials: 'same-origin' expect(@fetches.first.body).to.eql email: 'austin@makes.audio' username: 'jeffrey' form_submission_on_success() form_submission_on_server_error() form_submission_on_client_error() describe 'setting email', -> beforeEach -> input_email = @wrapper.first 'input[name=email]' @fill_in(input_email).with 'austin@bakes.audio' expect(@wrapper.vm.email).to.eql 'austin@bakes.audio' @wrapper.first('form').trigger 'submit' it 'should be in loading state', -> expect(@wrapper.vm.loading).to.be.true it 'should update record', -> expect(@fetches.first).to.include method: 'PUT' url: '/api/users/me' credentials: 'same-origin' expect(@fetches.first.body).to.eql email: 'austin@bakes.audio' username: 'austin' form_submission_on_success() form_submission_on_server_error() form_submission_on_client_error() describe 'setting password', -> beforeEach -> input_password = @wrapper.first 'input[name=password]' @fill_in(input_password).with 'donkey7' input_password = @wrapper.first 'input[name=currentPassword]' @fill_in(input_password).with 'apple' expect(@wrapper.vm.password).to.eql 'donkey7' expect(@wrapper.vm.currentPassword).to.eql 'apple' @wrapper.find('form')[1].trigger 'submit' it 'should be in loading state', -> expect(@wrapper.vm.loading).to.be.true it 'should update record', -> expect(@fetches.first).to.include method: 'PUT' url: '/api/users/me' credentials: 'same-origin' expect(@fetches.first.body).to.eql password: 'donkey7' currentPassword: 'apple' describe 'on success', -> beforeEach (done) -> @fetches.first.respond_with body: ok: true setImmediate done it 'should create toast', -> expect(Toaster.create).to.have.been.calledWith 'success', 'Done!' it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false it 'should reset inputs', -> expect(@wrapper.find('input[type=password]')[0].value()).to.be.false expect(@wrapper.find('input[type=password]')[1].value()).to.be.false form_submission_on_server_error() form_submission_on_client_error() describe 'resending verification email', -> describe 'when already verified', -> beforeEach -> @wrapper = mount user_form, store: @store, propsData: user: users_fixture.austin email_preferences: email_preferences_fixture.verified it 'should not show link', -> expect(@wrapper.contains('.verify-email-warning a')).to.be.false describe 'when not verified', -> beforeEach -> @wrapper = mount user_form, store: @store, propsData: user: users_fixture.austin email_preferences: email_preferences_fixture.not_verified it 'should show link', -> expect(@wrapper.contains('.verify-email-warning a')).to.be.true describe 'clicking `resend`', -> beforeEach -> @wrapper.first('.verify-email-warning a').trigger 'click' it 'should set loading state', -> expect(@wrapper.vm.loading).to.be.true it 'should make request', -> expect(@fetches.first).to.include url: '/api/users/me/emailPreferences/sendVerificationEmail' method: 'POST' credentials: 'same-origin' describe 'on success', -> beforeEach (done) -> @fetches.first.respond_with body: ok: true setImmediate done it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false it 'should create toast', -> message = 'Please check your email for a verification link.' expect(Toaster.create).to.have.been.calledWith 'success', message describe 'on error', -> beforeEach (done) -> @fetches.first.respond_with body: ok: false setImmediate done it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false it 'should create toast', -> message = 'Something went wrong.' expect(Toaster.create).to.have.been.calledWith 'danger', message
47091
import user_form from './user_form' import { mount } from 'avoriaz' import Vue, { nextTick } from 'vue' import Vuex from 'vuex' import sinon from 'sinon' import users_fixture from 'fixtures/users' import email_preferences_fixture from 'fixtures/email_preferences' import Toaster from 'lib/toaster' Vue.use Vuex describe 'user-form', -> beforeEach -> sinon.stub Toaster, 'create' @mutations = set_user: sinon.spy() @store = new Vuex.Store state: {} mutations: @mutations afterEach -> Toaster.create.restore() form_submission_on_success = -> describe 'on success', -> beforeEach (done) -> @new_user = Object.assign {}, users_fixture.austin, username: 'jeffrey' @fetches.first.respond_with body: ok: true user: @new_user setImmediate done it 'should commit to store', -> set_user = @mutations.set_user expect(set_user).to.have.been.calledWith sinon.match.object, @new_user it 'should create toast', -> expect Toaster.create .to.have.been.calledWith 'success', 'You’ve been updated.', 'Great!' it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false form_submission_on_server_error = -> describe 'on server error', -> beforeEach (done) -> @fetches.first.respond_with body: ok: false setImmediate done it 'should not commit to store', -> expect(@mutations.set_user).to.not.have.been.called it 'should create toast', -> expect(Toaster.create).to.have.been .calledWith 'danger', 'Please try again later.', 'Server Error!' it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false form_submission_on_client_error = -> describe 'on client error', -> beforeEach (done) -> @fetches.first.respond_with body: ok: false errors: [( code: 'WRONG_PASSWORD' )] setImmediate done it 'should not commit to store', -> expect(@mutations.set_user).to.not.have.been.called it 'should create toast', -> expect(Toaster.create).to.have.been .calledWith 'warning', 'The current password wasn’t correct.' it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false describe 'loading state', -> beforeEach -> @wrapper = mount user_form, store: @store, propsData: user: users_fixture.austin email_preferences: email_preferences_fixture.verified @wrapper.vm.loading = true nextTick() it 'should disable inputs', -> @wrapper.find('input').forEach (input) -> expect(input.element.getAttribute('disabled')).to.eql 'disabled' @wrapper.find('button').forEach (input) -> expect(input.element.getAttribute('disabled')).to.eql 'disabled' describe 'behavior', -> beforeEach -> @wrapper = mount user_form, store: @store, propsData: user: users_fixture.austin email_preferences: email_preferences_fixture.verified describe 'setting username', -> beforeEach -> input_username = @wrapper.first 'input[name=username]' @fill_in(input_username).with 'jeffrey' expect(@wrapper.vm.username).to.eql 'jeffrey' @wrapper.first('form').trigger 'submit' it 'should be in loading state', -> expect(@wrapper.vm.loading).to.be.true it 'should update record', -> expect(@fetches.first).to.include method: 'PUT' url: '/api/users/me' credentials: 'same-origin' expect(@fetches.first.body).to.eql email: '<EMAIL>' username: 'jeffrey' form_submission_on_success() form_submission_on_server_error() form_submission_on_client_error() describe 'setting email', -> beforeEach -> input_email = @wrapper.first 'input[name=email]' @fill_in(input_email).with '<EMAIL>' expect(@wrapper.vm.email).to.eql '<EMAIL>' @wrapper.first('form').trigger 'submit' it 'should be in loading state', -> expect(@wrapper.vm.loading).to.be.true it 'should update record', -> expect(@fetches.first).to.include method: 'PUT' url: '/api/users/me' credentials: 'same-origin' expect(@fetches.first.body).to.eql email: '<EMAIL>' username: 'austin' form_submission_on_success() form_submission_on_server_error() form_submission_on_client_error() describe 'setting password', -> beforeEach -> input_password = @wrapper.first 'input[name=password]' @fill_in(input_password).with '<PASSWORD>' input_password = @wrapper.first 'input[name=currentPassword]' @fill_in(input_password).with '<PASSWORD>' expect(@wrapper.vm.password).to.eql '<PASSWORD>' expect(@wrapper.vm.currentPassword).to.eql '<PASSWORD>' @wrapper.find('form')[1].trigger 'submit' it 'should be in loading state', -> expect(@wrapper.vm.loading).to.be.true it 'should update record', -> expect(@fetches.first).to.include method: 'PUT' url: '/api/users/me' credentials: 'same-origin' expect(@fetches.first.body).to.eql password: '<PASSWORD>' currentPassword: '<PASSWORD>' describe 'on success', -> beforeEach (done) -> @fetches.first.respond_with body: ok: true setImmediate done it 'should create toast', -> expect(Toaster.create).to.have.been.calledWith 'success', 'Done!' it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false it 'should reset inputs', -> expect(@wrapper.find('input[type=password]')[0].value()).to.be.false expect(@wrapper.find('input[type=password]')[1].value()).to.be.false form_submission_on_server_error() form_submission_on_client_error() describe 'resending verification email', -> describe 'when already verified', -> beforeEach -> @wrapper = mount user_form, store: @store, propsData: user: users_fixture.austin email_preferences: email_preferences_fixture.verified it 'should not show link', -> expect(@wrapper.contains('.verify-email-warning a')).to.be.false describe 'when not verified', -> beforeEach -> @wrapper = mount user_form, store: @store, propsData: user: users_fixture.austin email_preferences: email_preferences_fixture.not_verified it 'should show link', -> expect(@wrapper.contains('.verify-email-warning a')).to.be.true describe 'clicking `resend`', -> beforeEach -> @wrapper.first('.verify-email-warning a').trigger 'click' it 'should set loading state', -> expect(@wrapper.vm.loading).to.be.true it 'should make request', -> expect(@fetches.first).to.include url: '/api/users/me/emailPreferences/sendVerificationEmail' method: 'POST' credentials: 'same-origin' describe 'on success', -> beforeEach (done) -> @fetches.first.respond_with body: ok: true setImmediate done it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false it 'should create toast', -> message = 'Please check your email for a verification link.' expect(Toaster.create).to.have.been.calledWith 'success', message describe 'on error', -> beforeEach (done) -> @fetches.first.respond_with body: ok: false setImmediate done it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false it 'should create toast', -> message = 'Something went wrong.' expect(Toaster.create).to.have.been.calledWith 'danger', message
true
import user_form from './user_form' import { mount } from 'avoriaz' import Vue, { nextTick } from 'vue' import Vuex from 'vuex' import sinon from 'sinon' import users_fixture from 'fixtures/users' import email_preferences_fixture from 'fixtures/email_preferences' import Toaster from 'lib/toaster' Vue.use Vuex describe 'user-form', -> beforeEach -> sinon.stub Toaster, 'create' @mutations = set_user: sinon.spy() @store = new Vuex.Store state: {} mutations: @mutations afterEach -> Toaster.create.restore() form_submission_on_success = -> describe 'on success', -> beforeEach (done) -> @new_user = Object.assign {}, users_fixture.austin, username: 'jeffrey' @fetches.first.respond_with body: ok: true user: @new_user setImmediate done it 'should commit to store', -> set_user = @mutations.set_user expect(set_user).to.have.been.calledWith sinon.match.object, @new_user it 'should create toast', -> expect Toaster.create .to.have.been.calledWith 'success', 'You’ve been updated.', 'Great!' it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false form_submission_on_server_error = -> describe 'on server error', -> beforeEach (done) -> @fetches.first.respond_with body: ok: false setImmediate done it 'should not commit to store', -> expect(@mutations.set_user).to.not.have.been.called it 'should create toast', -> expect(Toaster.create).to.have.been .calledWith 'danger', 'Please try again later.', 'Server Error!' it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false form_submission_on_client_error = -> describe 'on client error', -> beforeEach (done) -> @fetches.first.respond_with body: ok: false errors: [( code: 'WRONG_PASSWORD' )] setImmediate done it 'should not commit to store', -> expect(@mutations.set_user).to.not.have.been.called it 'should create toast', -> expect(Toaster.create).to.have.been .calledWith 'warning', 'The current password wasn’t correct.' it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false describe 'loading state', -> beforeEach -> @wrapper = mount user_form, store: @store, propsData: user: users_fixture.austin email_preferences: email_preferences_fixture.verified @wrapper.vm.loading = true nextTick() it 'should disable inputs', -> @wrapper.find('input').forEach (input) -> expect(input.element.getAttribute('disabled')).to.eql 'disabled' @wrapper.find('button').forEach (input) -> expect(input.element.getAttribute('disabled')).to.eql 'disabled' describe 'behavior', -> beforeEach -> @wrapper = mount user_form, store: @store, propsData: user: users_fixture.austin email_preferences: email_preferences_fixture.verified describe 'setting username', -> beforeEach -> input_username = @wrapper.first 'input[name=username]' @fill_in(input_username).with 'jeffrey' expect(@wrapper.vm.username).to.eql 'jeffrey' @wrapper.first('form').trigger 'submit' it 'should be in loading state', -> expect(@wrapper.vm.loading).to.be.true it 'should update record', -> expect(@fetches.first).to.include method: 'PUT' url: '/api/users/me' credentials: 'same-origin' expect(@fetches.first.body).to.eql email: 'PI:EMAIL:<EMAIL>END_PI' username: 'jeffrey' form_submission_on_success() form_submission_on_server_error() form_submission_on_client_error() describe 'setting email', -> beforeEach -> input_email = @wrapper.first 'input[name=email]' @fill_in(input_email).with 'PI:EMAIL:<EMAIL>END_PI' expect(@wrapper.vm.email).to.eql 'PI:EMAIL:<EMAIL>END_PI' @wrapper.first('form').trigger 'submit' it 'should be in loading state', -> expect(@wrapper.vm.loading).to.be.true it 'should update record', -> expect(@fetches.first).to.include method: 'PUT' url: '/api/users/me' credentials: 'same-origin' expect(@fetches.first.body).to.eql email: 'PI:EMAIL:<EMAIL>END_PI' username: 'austin' form_submission_on_success() form_submission_on_server_error() form_submission_on_client_error() describe 'setting password', -> beforeEach -> input_password = @wrapper.first 'input[name=password]' @fill_in(input_password).with 'PI:PASSWORD:<PASSWORD>END_PI' input_password = @wrapper.first 'input[name=currentPassword]' @fill_in(input_password).with 'PI:PASSWORD:<PASSWORD>END_PI' expect(@wrapper.vm.password).to.eql 'PI:PASSWORD:<PASSWORD>END_PI' expect(@wrapper.vm.currentPassword).to.eql 'PI:PASSWORD:<PASSWORD>END_PI' @wrapper.find('form')[1].trigger 'submit' it 'should be in loading state', -> expect(@wrapper.vm.loading).to.be.true it 'should update record', -> expect(@fetches.first).to.include method: 'PUT' url: '/api/users/me' credentials: 'same-origin' expect(@fetches.first.body).to.eql password: 'PI:PASSWORD:<PASSWORD>END_PI' currentPassword: 'PI:PASSWORD:<PASSWORD>END_PI' describe 'on success', -> beforeEach (done) -> @fetches.first.respond_with body: ok: true setImmediate done it 'should create toast', -> expect(Toaster.create).to.have.been.calledWith 'success', 'Done!' it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false it 'should reset inputs', -> expect(@wrapper.find('input[type=password]')[0].value()).to.be.false expect(@wrapper.find('input[type=password]')[1].value()).to.be.false form_submission_on_server_error() form_submission_on_client_error() describe 'resending verification email', -> describe 'when already verified', -> beforeEach -> @wrapper = mount user_form, store: @store, propsData: user: users_fixture.austin email_preferences: email_preferences_fixture.verified it 'should not show link', -> expect(@wrapper.contains('.verify-email-warning a')).to.be.false describe 'when not verified', -> beforeEach -> @wrapper = mount user_form, store: @store, propsData: user: users_fixture.austin email_preferences: email_preferences_fixture.not_verified it 'should show link', -> expect(@wrapper.contains('.verify-email-warning a')).to.be.true describe 'clicking `resend`', -> beforeEach -> @wrapper.first('.verify-email-warning a').trigger 'click' it 'should set loading state', -> expect(@wrapper.vm.loading).to.be.true it 'should make request', -> expect(@fetches.first).to.include url: '/api/users/me/emailPreferences/sendVerificationEmail' method: 'POST' credentials: 'same-origin' describe 'on success', -> beforeEach (done) -> @fetches.first.respond_with body: ok: true setImmediate done it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false it 'should create toast', -> message = 'Please check your email for a verification link.' expect(Toaster.create).to.have.been.calledWith 'success', message describe 'on error', -> beforeEach (done) -> @fetches.first.respond_with body: ok: false setImmediate done it 'should clear loading state', -> expect(@wrapper.vm.loading).to.be.false it 'should create toast', -> message = 'Something went wrong.' expect(Toaster.create).to.have.been.calledWith 'danger', message
[ { "context": "\t\t\t\t\te.preventDefault()\n\t\t\t\t\t\tcancelAnimationFrame(@auto_scroll_animation_frame)\n\t\t\t\t\t\t@auto_scroll_animation_frame = requestAnim", "end": 7933, "score": 0.7958123087882996, "start": 7905, "tag": "USERNAME", "value": "@auto_scroll_animation_frame" }, { "context": "mousemove\", onMouseMove\n\t\t\t\t\t\tcancelAnimationFrame(@auto_scroll_animation_frame)\n\t\t\t\t\t\tclearTimeout(@auto_scroll_timeout_id)\n\t\t\t\t", "end": 8238, "score": 0.8128461837768555, "start": 8210, "tag": "USERNAME", "value": "@auto_scroll_animation_frame" }, { "context": "e(@auto_scroll_animation_frame)\n\t\t\t\t\t\tclearTimeout(@auto_scroll_timeout_id)\n\t\t\t\t\t\tunless mouse_moved_timewise\n\t\t\t\t\t\t\teditor.", "end": 8282, "score": 0.9012336730957031, "start": 8259, "tag": "USERNAME", "value": "@auto_scroll_timeout_id" }, { "context": "ditor}\n\t\t\t\t\n\t\t\t\t# E MIDITrack, {\n\t\t\t\t# \tkey: \"midi-test-track\"\n\t\t\t\t# \ttrack: {\n\t\t\t\t# \t\tnotes: [\n\t\t\t\t# \t\t\t{t: 0,", "end": 9466, "score": 0.6763858199119568, "start": 9456, "tag": "KEY", "value": "test-track" } ]
src/components/TracksArea.coffee
1j01/wavey
69
{E, Component} = require "../helpers.coffee" ReactDOM = require "react-dom" InfoBar = require "./InfoBar.coffee" TrackControls = require "./TrackControls.coffee" BeatTrack = require "./BeatTrack.coffee" AudioTrack = require "./AudioTrack.coffee" MIDITrack = require "./MIDITrack.coffee" UnknownTrack = require "./UnknownTrack.coffee" Range = require "../Range.coffee" easing = require "easingjs" module.exports = class TracksArea extends Component constructor: -> super() @y_offset_anims_by_track_id = {} render: -> {tracks, position, position_time, scale, playing, editor} = @props select_at_mouse = (e)=> # TODO: DRY, parts were copy/pasted from onMouseMove track_content_el = e.target.closest(".track-content") track_content_area_el = e.target.closest(".track-content-area") return unless track_content_el? track_el = e.target.closest(".track") position_at = (clientX)=> rect = track_content_el.getBoundingClientRect() (clientX - rect.left + track_content_area_el.scrollLeft) / scale find_track_id = (el)=> track_el = el.closest(".track") track_el.dataset.trackId position = position_at e.clientX track_id = find_track_id e.target editor.select_position position, [track_id] document_is_basically_empty = yes for track in tracks when track.type isnt "beat" document_is_basically_empty = no # TODO: decide if this is the ideal or what (seems pretty decent) document_width_padding = window.innerWidth/2 document_width = Math.max(editor.get_max_length_or_zero() * scale, window.innerWidth) + document_width_padding E ".tracks-area", onMouseDown: (e)=> # TODO: DRY onMouseDowns return if e.isDefaultPrevented() return if e.target.closest("p, button") unless e.button > 0 e.preventDefault() if e.target is ReactDOM.findDOMNode(@) e.preventDefault() editor.deselect() getSelection().removeAllRanges() E ".track-controls-area", key: "track-controls-area" for track in tracks switch track.type when "audio", "midi", "beat" E TrackControls, {key: track.id, track, scale, editor} else # XXX: This is needed for associating the track-controls with the track # Could probably use aria-controls or something instead E ".track-controls.no-track-controls", key: track.id E ".track-content-area", key: "track-content-area" # @TODO: touch support # @TODO: double click to select either to the bounds of adjacent audio clips or everything on the track # @TODO: drag and drop the selection? # @TODO: better overall drag and drop feedback onDragOver: (e)=> e.preventDefault() e.dataTransfer.dropEffect = "copy" unless editor.state.moving_selection editor.setState moving_selection: yes window.addEventListener "dragend", dragEnd = (e)=> window.removeEventListener "dragend", dragEnd editor.setState moving_selection: no editor.save() select_at_mouse e onDragLeave: (e)=> editor.deselect() onDrop: (e)=> return unless e.target.closest(".track-content") e.preventDefault() select_at_mouse e # TODO: add tracks in the order we get them, not by how long each clip takes to load # do it by making loading state placeholder track/clip representations # also DRY with code in AudioEditor for file in e.dataTransfer.files editor.add_clip file, yes onMouseDown: (e)=> # TODO: DRY onMouseDowns # TODO: DRY, parts were copy/pasted into select_at_mouse return unless e.button is 0 track_content_el = e.target.closest(".track-content") track_content_area_el = e.target.closest(".track-content-area") if track_content_el?.closest(".timeline-independent") editor.deselect() getSelection().removeAllRanges() return unless track_content_el unless e.target.closest(".track-controls") e.preventDefault() editor.deselect() getSelection().removeAllRanges() return e.preventDefault() position_at = (clientX)=> rect = track_content_el.getBoundingClientRect() (clientX - rect.left + track_content_area_el.scrollLeft) / scale nearest_track_id_at = (clientY)=> track_els = ReactDOM.findDOMNode(@).querySelectorAll(".track") nearest_track_el = track_els[0] distance = Infinity for track_el in track_els when track_el.dataset.trackId rect = track_el.getBoundingClientRect() _distance = Math.abs(clientY - (rect.top + rect.height / 2)) if _distance < distance nearest_track_el = track_el distance = _distance nearest_track_el.dataset.trackId starting_position = position_at e.clientX starting_track_id = nearest_track_id_at e.clientY editor.setState moving_selection: yes if e.shiftKey editor.select_to starting_position, starting_track_id else editor.select_position starting_position, [starting_track_id] auto_scroll_margin = 30 auto_scroll_max_speed = 20 auto_scroll_container_el = ReactDOM.findDOMNode(@).querySelector(".track-content-area") auto_scroll_container_rect = auto_scroll_container_el.getBoundingClientRect() auto_scroll_rect = left: auto_scroll_container_rect.left top: auto_scroll_container_rect.top width: auto_scroll_container_el.clientWidth height: auto_scroll_container_el.clientHeight right: auto_scroll_container_rect.left + auto_scroll_container_el.clientWidth bottom: auto_scroll_container_rect.top + auto_scroll_container_el.clientHeight mouse_x = e.clientX mouse_y = e.clientY auto_scroll_x = 0 auto_scroll_y = 0 @auto_scroll_animation_frame = -1 @auto_scroll_timeout_id = -1 auto_scroll = => auto_scroll_x = if mouse_x < auto_scroll_rect.left + auto_scroll_margin Math.floor(Math.max(-1, (mouse_x - auto_scroll_rect.left) / auto_scroll_margin - 1) * auto_scroll_max_speed) else if mouse_x > auto_scroll_rect.right - auto_scroll_margin Math.ceil(Math.min(1, (mouse_x - auto_scroll_rect.right) / auto_scroll_margin + 1) * auto_scroll_max_speed) else 0 auto_scroll_y = if mouse_y < auto_scroll_rect.top + auto_scroll_margin Math.floor(Math.max(-1, (mouse_y - auto_scroll_rect.top) / auto_scroll_margin - 1) * auto_scroll_max_speed) else if mouse_y > auto_scroll_rect.bottom - auto_scroll_margin Math.ceil(Math.min(1, (mouse_y - auto_scroll_rect.bottom) / auto_scroll_margin + 1) * auto_scroll_max_speed) else 0 # update the selection while auto-scrolling update_selection() @auto_scroll_timeout_id = setTimeout => auto_scroll_container_el.scrollLeft += auto_scroll_x auto_scroll_container_el.scrollTop += auto_scroll_y @auto_scroll_animation_frame = requestAnimationFrame(auto_scroll) mouse_moved_timewise = no mouse_moved_trackwise = no update_selection = => if Math.abs(position_at(mouse_x) - starting_position) > 5 / scale mouse_moved_timewise = yes if nearest_track_id_at(mouse_y) isnt starting_track_id mouse_moved_trackwise = yes if @props.selection and (mouse_moved_timewise or mouse_moved_trackwise) drag_position = if mouse_moved_timewise then position_at(mouse_x) else starting_position drag_track_id = if mouse_moved_trackwise then nearest_track_id_at(mouse_y) else starting_track_id editor.select_to drag_position, drag_track_id window.addEventListener "mousemove", onMouseMove = (e)=> mouse_x = e.clientX mouse_y = e.clientY update_selection() e.preventDefault() cancelAnimationFrame(@auto_scroll_animation_frame) @auto_scroll_animation_frame = requestAnimationFrame(auto_scroll) window.addEventListener "mouseup", onMouseUp = (e)=> window.removeEventListener "mouseup", onMouseUp window.removeEventListener "mousemove", onMouseMove cancelAnimationFrame(@auto_scroll_animation_frame) clearTimeout(@auto_scroll_timeout_id) unless mouse_moved_timewise editor.seek starting_position editor.setState moving_selection: no editor.save() E ".document-width", key: "document-width" style: width: document_width # NOTE: it apparently needs some height to cause scrolling flex: "0 0 1px" # and we don't want some random extra height somewhere # so we at least try to put it at the bottom order: 100000 if position? E ".position-indicator", key: "position-indicator" ref: "position_indicator" for track in tracks switch track.type when "beat" E BeatTrack, {key: track.id, track, scale, editor, document_width} when "audio" E AudioTrack, { key: track.id, track, scale, editor selection: (@props.selection if @props.selection?.containsTrack track) } when "midi" E MIDITrack, { key: track.id, track, scale, editor selection: (@props.selection if @props.selection?.containsTrack track) } else E UnknownTrack, {key: track.id, track, scale, editor} # E MIDITrack, { # key: "midi-test-track" # track: { # notes: [ # {t: 0, length: 1/4, note: 65} # {t: 1/4, length: 1/4, note: 66} # {t: 2/4, length: 2/4, note: 68} # ] # } # scale, editor # selection: (@props.selection if @props.selection?.containsTrack track) # } if document_is_basically_empty E ".track.getting-started.timeline-independent", {key: "getting-on-track"}, E ".track-content", E "p", "To get started, hit record above or drag and drop to add some tracks." animate: -> {scale} = @props @animation_frame = requestAnimationFrame => @animate() tracks_area_el = ReactDOM.findDOMNode(@) tracks_area_rect = tracks_area_el.getBoundingClientRect() track_content_area_el = tracks_area_el.querySelector(".track-content-area") track_content_area_rect = track_content_area_el.getBoundingClientRect() track_els = tracks_area_el.querySelectorAll(".track") track_controls_els = tracks_area_el.querySelectorAll(".track-controls") for track_controls_el, i in track_controls_els track_el = track_els[i] track_rect = track_el.getBoundingClientRect() track_controls_el.style.top = "#{track_rect.top - tracks_area_rect.top + parseInt(getComputedStyle(track_el).paddingTop)}px" scroll_x = track_content_area_el.scrollLeft for track_el in track_els track_content_el = track_el.querySelector(".track-content > *") y_offset_anims = @y_offset_anims_by_track_id[track_el.dataset.trackId] ? [] new_y_offset_anims = [] y_offset = 0 for anim in y_offset_anims pos = anim.pos() if pos <= 1 y_offset += anim.fn(pos) new_y_offset_anims.push(anim) @y_offset_anims_by_track_id[track_el.dataset.trackId] = new_y_offset_anims track_el.style.transform = "translate(#{scroll_x}px, #{y_offset}px)" unless track_el.classList.contains("timeline-independent") track_content_el.style.transform = "translateX(#{-scroll_x}px)" if @refs.position_indicator any_old_track_content_el = track_el.querySelector(".track-content") any_old_track_content_rect = any_old_track_content_el.getBoundingClientRect() position = @props.position + if @props.playing then actx.currentTime - @props.position_time else 0 x = scale * position + any_old_track_content_rect.left if @props.playing # pagination behavior keep_margin_right = 5 scroll_by = any_old_track_content_rect.width # incremental behavior # keep_margin_right = 5 # scroll_by = 200 # almost-smooth behavior, # but scroll_by is a misnomer here # and even without the setTimeout the position indicator still jiggles # more problematically, if you seek ahead it's confusing # keep_margin_right = 200 # scroll_by = 0 delta_x = x - track_content_area_el.scrollLeft - any_old_track_content_rect.right + keep_margin_right if delta_x > 0 setTimeout -> # do scroll outside of animation loop! # XXX: recalculate delta because it may have changed delta_x = x - track_content_area_el.scrollLeft - any_old_track_content_rect.right + keep_margin_right track_content_area_el.scrollLeft += delta_x + scroll_by @refs.position_indicator.style.left = "#{x - track_content_area_rect.left}px" @refs.position_indicator.style.top = "#{track_content_area_el.scrollTop}px" getSnapshotBeforeUpdate: ()=> # for transitioning track positions # get a baseline for measuring differences in track y positions @last_track_rects = {} for track_current, track_index in @props.tracks track_els = ReactDOM.findDOMNode(@).querySelectorAll(".track") track_el = track_els[track_index] if track_el @last_track_rects[track_current.id] = track_el.getBoundingClientRect() componentDidUpdate: (last_props, last_state)=> # measure differences in track y positions # and queue track transitions track_els = ReactDOM.findDOMNode(@).querySelectorAll(".track") for track_el, track_index in track_els current_rect = track_el.getBoundingClientRect() last_rect = @last_track_rects[track_el.dataset.trackId] if last_rect? do (last_rect, current_rect)=> delta_y = last_rect.top - current_rect.top if delta_y # add a transition transition_seconds = 0.3 start_time = Date.now() y_offset_anims = @y_offset_anims_by_track_id[track_el.dataset.trackId] ?= [] y_offset_anims.push({ pos: -> (Date.now() - start_time) / 1000 / transition_seconds fn: (pos)-> delta_y * easing.easeInOutQuart(1 - pos) }) # update immediately to avoid one-frame artifacts cancelAnimationFrame @animation_frame @animate() componentDidMount: -> @animate() componentWillUnmount: -> cancelAnimationFrame @animation_frame cancelAnimationFrame @auto_scroll_animation_frame
199944
{E, Component} = require "../helpers.coffee" ReactDOM = require "react-dom" InfoBar = require "./InfoBar.coffee" TrackControls = require "./TrackControls.coffee" BeatTrack = require "./BeatTrack.coffee" AudioTrack = require "./AudioTrack.coffee" MIDITrack = require "./MIDITrack.coffee" UnknownTrack = require "./UnknownTrack.coffee" Range = require "../Range.coffee" easing = require "easingjs" module.exports = class TracksArea extends Component constructor: -> super() @y_offset_anims_by_track_id = {} render: -> {tracks, position, position_time, scale, playing, editor} = @props select_at_mouse = (e)=> # TODO: DRY, parts were copy/pasted from onMouseMove track_content_el = e.target.closest(".track-content") track_content_area_el = e.target.closest(".track-content-area") return unless track_content_el? track_el = e.target.closest(".track") position_at = (clientX)=> rect = track_content_el.getBoundingClientRect() (clientX - rect.left + track_content_area_el.scrollLeft) / scale find_track_id = (el)=> track_el = el.closest(".track") track_el.dataset.trackId position = position_at e.clientX track_id = find_track_id e.target editor.select_position position, [track_id] document_is_basically_empty = yes for track in tracks when track.type isnt "beat" document_is_basically_empty = no # TODO: decide if this is the ideal or what (seems pretty decent) document_width_padding = window.innerWidth/2 document_width = Math.max(editor.get_max_length_or_zero() * scale, window.innerWidth) + document_width_padding E ".tracks-area", onMouseDown: (e)=> # TODO: DRY onMouseDowns return if e.isDefaultPrevented() return if e.target.closest("p, button") unless e.button > 0 e.preventDefault() if e.target is ReactDOM.findDOMNode(@) e.preventDefault() editor.deselect() getSelection().removeAllRanges() E ".track-controls-area", key: "track-controls-area" for track in tracks switch track.type when "audio", "midi", "beat" E TrackControls, {key: track.id, track, scale, editor} else # XXX: This is needed for associating the track-controls with the track # Could probably use aria-controls or something instead E ".track-controls.no-track-controls", key: track.id E ".track-content-area", key: "track-content-area" # @TODO: touch support # @TODO: double click to select either to the bounds of adjacent audio clips or everything on the track # @TODO: drag and drop the selection? # @TODO: better overall drag and drop feedback onDragOver: (e)=> e.preventDefault() e.dataTransfer.dropEffect = "copy" unless editor.state.moving_selection editor.setState moving_selection: yes window.addEventListener "dragend", dragEnd = (e)=> window.removeEventListener "dragend", dragEnd editor.setState moving_selection: no editor.save() select_at_mouse e onDragLeave: (e)=> editor.deselect() onDrop: (e)=> return unless e.target.closest(".track-content") e.preventDefault() select_at_mouse e # TODO: add tracks in the order we get them, not by how long each clip takes to load # do it by making loading state placeholder track/clip representations # also DRY with code in AudioEditor for file in e.dataTransfer.files editor.add_clip file, yes onMouseDown: (e)=> # TODO: DRY onMouseDowns # TODO: DRY, parts were copy/pasted into select_at_mouse return unless e.button is 0 track_content_el = e.target.closest(".track-content") track_content_area_el = e.target.closest(".track-content-area") if track_content_el?.closest(".timeline-independent") editor.deselect() getSelection().removeAllRanges() return unless track_content_el unless e.target.closest(".track-controls") e.preventDefault() editor.deselect() getSelection().removeAllRanges() return e.preventDefault() position_at = (clientX)=> rect = track_content_el.getBoundingClientRect() (clientX - rect.left + track_content_area_el.scrollLeft) / scale nearest_track_id_at = (clientY)=> track_els = ReactDOM.findDOMNode(@).querySelectorAll(".track") nearest_track_el = track_els[0] distance = Infinity for track_el in track_els when track_el.dataset.trackId rect = track_el.getBoundingClientRect() _distance = Math.abs(clientY - (rect.top + rect.height / 2)) if _distance < distance nearest_track_el = track_el distance = _distance nearest_track_el.dataset.trackId starting_position = position_at e.clientX starting_track_id = nearest_track_id_at e.clientY editor.setState moving_selection: yes if e.shiftKey editor.select_to starting_position, starting_track_id else editor.select_position starting_position, [starting_track_id] auto_scroll_margin = 30 auto_scroll_max_speed = 20 auto_scroll_container_el = ReactDOM.findDOMNode(@).querySelector(".track-content-area") auto_scroll_container_rect = auto_scroll_container_el.getBoundingClientRect() auto_scroll_rect = left: auto_scroll_container_rect.left top: auto_scroll_container_rect.top width: auto_scroll_container_el.clientWidth height: auto_scroll_container_el.clientHeight right: auto_scroll_container_rect.left + auto_scroll_container_el.clientWidth bottom: auto_scroll_container_rect.top + auto_scroll_container_el.clientHeight mouse_x = e.clientX mouse_y = e.clientY auto_scroll_x = 0 auto_scroll_y = 0 @auto_scroll_animation_frame = -1 @auto_scroll_timeout_id = -1 auto_scroll = => auto_scroll_x = if mouse_x < auto_scroll_rect.left + auto_scroll_margin Math.floor(Math.max(-1, (mouse_x - auto_scroll_rect.left) / auto_scroll_margin - 1) * auto_scroll_max_speed) else if mouse_x > auto_scroll_rect.right - auto_scroll_margin Math.ceil(Math.min(1, (mouse_x - auto_scroll_rect.right) / auto_scroll_margin + 1) * auto_scroll_max_speed) else 0 auto_scroll_y = if mouse_y < auto_scroll_rect.top + auto_scroll_margin Math.floor(Math.max(-1, (mouse_y - auto_scroll_rect.top) / auto_scroll_margin - 1) * auto_scroll_max_speed) else if mouse_y > auto_scroll_rect.bottom - auto_scroll_margin Math.ceil(Math.min(1, (mouse_y - auto_scroll_rect.bottom) / auto_scroll_margin + 1) * auto_scroll_max_speed) else 0 # update the selection while auto-scrolling update_selection() @auto_scroll_timeout_id = setTimeout => auto_scroll_container_el.scrollLeft += auto_scroll_x auto_scroll_container_el.scrollTop += auto_scroll_y @auto_scroll_animation_frame = requestAnimationFrame(auto_scroll) mouse_moved_timewise = no mouse_moved_trackwise = no update_selection = => if Math.abs(position_at(mouse_x) - starting_position) > 5 / scale mouse_moved_timewise = yes if nearest_track_id_at(mouse_y) isnt starting_track_id mouse_moved_trackwise = yes if @props.selection and (mouse_moved_timewise or mouse_moved_trackwise) drag_position = if mouse_moved_timewise then position_at(mouse_x) else starting_position drag_track_id = if mouse_moved_trackwise then nearest_track_id_at(mouse_y) else starting_track_id editor.select_to drag_position, drag_track_id window.addEventListener "mousemove", onMouseMove = (e)=> mouse_x = e.clientX mouse_y = e.clientY update_selection() e.preventDefault() cancelAnimationFrame(@auto_scroll_animation_frame) @auto_scroll_animation_frame = requestAnimationFrame(auto_scroll) window.addEventListener "mouseup", onMouseUp = (e)=> window.removeEventListener "mouseup", onMouseUp window.removeEventListener "mousemove", onMouseMove cancelAnimationFrame(@auto_scroll_animation_frame) clearTimeout(@auto_scroll_timeout_id) unless mouse_moved_timewise editor.seek starting_position editor.setState moving_selection: no editor.save() E ".document-width", key: "document-width" style: width: document_width # NOTE: it apparently needs some height to cause scrolling flex: "0 0 1px" # and we don't want some random extra height somewhere # so we at least try to put it at the bottom order: 100000 if position? E ".position-indicator", key: "position-indicator" ref: "position_indicator" for track in tracks switch track.type when "beat" E BeatTrack, {key: track.id, track, scale, editor, document_width} when "audio" E AudioTrack, { key: track.id, track, scale, editor selection: (@props.selection if @props.selection?.containsTrack track) } when "midi" E MIDITrack, { key: track.id, track, scale, editor selection: (@props.selection if @props.selection?.containsTrack track) } else E UnknownTrack, {key: track.id, track, scale, editor} # E MIDITrack, { # key: "midi-<KEY>" # track: { # notes: [ # {t: 0, length: 1/4, note: 65} # {t: 1/4, length: 1/4, note: 66} # {t: 2/4, length: 2/4, note: 68} # ] # } # scale, editor # selection: (@props.selection if @props.selection?.containsTrack track) # } if document_is_basically_empty E ".track.getting-started.timeline-independent", {key: "getting-on-track"}, E ".track-content", E "p", "To get started, hit record above or drag and drop to add some tracks." animate: -> {scale} = @props @animation_frame = requestAnimationFrame => @animate() tracks_area_el = ReactDOM.findDOMNode(@) tracks_area_rect = tracks_area_el.getBoundingClientRect() track_content_area_el = tracks_area_el.querySelector(".track-content-area") track_content_area_rect = track_content_area_el.getBoundingClientRect() track_els = tracks_area_el.querySelectorAll(".track") track_controls_els = tracks_area_el.querySelectorAll(".track-controls") for track_controls_el, i in track_controls_els track_el = track_els[i] track_rect = track_el.getBoundingClientRect() track_controls_el.style.top = "#{track_rect.top - tracks_area_rect.top + parseInt(getComputedStyle(track_el).paddingTop)}px" scroll_x = track_content_area_el.scrollLeft for track_el in track_els track_content_el = track_el.querySelector(".track-content > *") y_offset_anims = @y_offset_anims_by_track_id[track_el.dataset.trackId] ? [] new_y_offset_anims = [] y_offset = 0 for anim in y_offset_anims pos = anim.pos() if pos <= 1 y_offset += anim.fn(pos) new_y_offset_anims.push(anim) @y_offset_anims_by_track_id[track_el.dataset.trackId] = new_y_offset_anims track_el.style.transform = "translate(#{scroll_x}px, #{y_offset}px)" unless track_el.classList.contains("timeline-independent") track_content_el.style.transform = "translateX(#{-scroll_x}px)" if @refs.position_indicator any_old_track_content_el = track_el.querySelector(".track-content") any_old_track_content_rect = any_old_track_content_el.getBoundingClientRect() position = @props.position + if @props.playing then actx.currentTime - @props.position_time else 0 x = scale * position + any_old_track_content_rect.left if @props.playing # pagination behavior keep_margin_right = 5 scroll_by = any_old_track_content_rect.width # incremental behavior # keep_margin_right = 5 # scroll_by = 200 # almost-smooth behavior, # but scroll_by is a misnomer here # and even without the setTimeout the position indicator still jiggles # more problematically, if you seek ahead it's confusing # keep_margin_right = 200 # scroll_by = 0 delta_x = x - track_content_area_el.scrollLeft - any_old_track_content_rect.right + keep_margin_right if delta_x > 0 setTimeout -> # do scroll outside of animation loop! # XXX: recalculate delta because it may have changed delta_x = x - track_content_area_el.scrollLeft - any_old_track_content_rect.right + keep_margin_right track_content_area_el.scrollLeft += delta_x + scroll_by @refs.position_indicator.style.left = "#{x - track_content_area_rect.left}px" @refs.position_indicator.style.top = "#{track_content_area_el.scrollTop}px" getSnapshotBeforeUpdate: ()=> # for transitioning track positions # get a baseline for measuring differences in track y positions @last_track_rects = {} for track_current, track_index in @props.tracks track_els = ReactDOM.findDOMNode(@).querySelectorAll(".track") track_el = track_els[track_index] if track_el @last_track_rects[track_current.id] = track_el.getBoundingClientRect() componentDidUpdate: (last_props, last_state)=> # measure differences in track y positions # and queue track transitions track_els = ReactDOM.findDOMNode(@).querySelectorAll(".track") for track_el, track_index in track_els current_rect = track_el.getBoundingClientRect() last_rect = @last_track_rects[track_el.dataset.trackId] if last_rect? do (last_rect, current_rect)=> delta_y = last_rect.top - current_rect.top if delta_y # add a transition transition_seconds = 0.3 start_time = Date.now() y_offset_anims = @y_offset_anims_by_track_id[track_el.dataset.trackId] ?= [] y_offset_anims.push({ pos: -> (Date.now() - start_time) / 1000 / transition_seconds fn: (pos)-> delta_y * easing.easeInOutQuart(1 - pos) }) # update immediately to avoid one-frame artifacts cancelAnimationFrame @animation_frame @animate() componentDidMount: -> @animate() componentWillUnmount: -> cancelAnimationFrame @animation_frame cancelAnimationFrame @auto_scroll_animation_frame
true
{E, Component} = require "../helpers.coffee" ReactDOM = require "react-dom" InfoBar = require "./InfoBar.coffee" TrackControls = require "./TrackControls.coffee" BeatTrack = require "./BeatTrack.coffee" AudioTrack = require "./AudioTrack.coffee" MIDITrack = require "./MIDITrack.coffee" UnknownTrack = require "./UnknownTrack.coffee" Range = require "../Range.coffee" easing = require "easingjs" module.exports = class TracksArea extends Component constructor: -> super() @y_offset_anims_by_track_id = {} render: -> {tracks, position, position_time, scale, playing, editor} = @props select_at_mouse = (e)=> # TODO: DRY, parts were copy/pasted from onMouseMove track_content_el = e.target.closest(".track-content") track_content_area_el = e.target.closest(".track-content-area") return unless track_content_el? track_el = e.target.closest(".track") position_at = (clientX)=> rect = track_content_el.getBoundingClientRect() (clientX - rect.left + track_content_area_el.scrollLeft) / scale find_track_id = (el)=> track_el = el.closest(".track") track_el.dataset.trackId position = position_at e.clientX track_id = find_track_id e.target editor.select_position position, [track_id] document_is_basically_empty = yes for track in tracks when track.type isnt "beat" document_is_basically_empty = no # TODO: decide if this is the ideal or what (seems pretty decent) document_width_padding = window.innerWidth/2 document_width = Math.max(editor.get_max_length_or_zero() * scale, window.innerWidth) + document_width_padding E ".tracks-area", onMouseDown: (e)=> # TODO: DRY onMouseDowns return if e.isDefaultPrevented() return if e.target.closest("p, button") unless e.button > 0 e.preventDefault() if e.target is ReactDOM.findDOMNode(@) e.preventDefault() editor.deselect() getSelection().removeAllRanges() E ".track-controls-area", key: "track-controls-area" for track in tracks switch track.type when "audio", "midi", "beat" E TrackControls, {key: track.id, track, scale, editor} else # XXX: This is needed for associating the track-controls with the track # Could probably use aria-controls or something instead E ".track-controls.no-track-controls", key: track.id E ".track-content-area", key: "track-content-area" # @TODO: touch support # @TODO: double click to select either to the bounds of adjacent audio clips or everything on the track # @TODO: drag and drop the selection? # @TODO: better overall drag and drop feedback onDragOver: (e)=> e.preventDefault() e.dataTransfer.dropEffect = "copy" unless editor.state.moving_selection editor.setState moving_selection: yes window.addEventListener "dragend", dragEnd = (e)=> window.removeEventListener "dragend", dragEnd editor.setState moving_selection: no editor.save() select_at_mouse e onDragLeave: (e)=> editor.deselect() onDrop: (e)=> return unless e.target.closest(".track-content") e.preventDefault() select_at_mouse e # TODO: add tracks in the order we get them, not by how long each clip takes to load # do it by making loading state placeholder track/clip representations # also DRY with code in AudioEditor for file in e.dataTransfer.files editor.add_clip file, yes onMouseDown: (e)=> # TODO: DRY onMouseDowns # TODO: DRY, parts were copy/pasted into select_at_mouse return unless e.button is 0 track_content_el = e.target.closest(".track-content") track_content_area_el = e.target.closest(".track-content-area") if track_content_el?.closest(".timeline-independent") editor.deselect() getSelection().removeAllRanges() return unless track_content_el unless e.target.closest(".track-controls") e.preventDefault() editor.deselect() getSelection().removeAllRanges() return e.preventDefault() position_at = (clientX)=> rect = track_content_el.getBoundingClientRect() (clientX - rect.left + track_content_area_el.scrollLeft) / scale nearest_track_id_at = (clientY)=> track_els = ReactDOM.findDOMNode(@).querySelectorAll(".track") nearest_track_el = track_els[0] distance = Infinity for track_el in track_els when track_el.dataset.trackId rect = track_el.getBoundingClientRect() _distance = Math.abs(clientY - (rect.top + rect.height / 2)) if _distance < distance nearest_track_el = track_el distance = _distance nearest_track_el.dataset.trackId starting_position = position_at e.clientX starting_track_id = nearest_track_id_at e.clientY editor.setState moving_selection: yes if e.shiftKey editor.select_to starting_position, starting_track_id else editor.select_position starting_position, [starting_track_id] auto_scroll_margin = 30 auto_scroll_max_speed = 20 auto_scroll_container_el = ReactDOM.findDOMNode(@).querySelector(".track-content-area") auto_scroll_container_rect = auto_scroll_container_el.getBoundingClientRect() auto_scroll_rect = left: auto_scroll_container_rect.left top: auto_scroll_container_rect.top width: auto_scroll_container_el.clientWidth height: auto_scroll_container_el.clientHeight right: auto_scroll_container_rect.left + auto_scroll_container_el.clientWidth bottom: auto_scroll_container_rect.top + auto_scroll_container_el.clientHeight mouse_x = e.clientX mouse_y = e.clientY auto_scroll_x = 0 auto_scroll_y = 0 @auto_scroll_animation_frame = -1 @auto_scroll_timeout_id = -1 auto_scroll = => auto_scroll_x = if mouse_x < auto_scroll_rect.left + auto_scroll_margin Math.floor(Math.max(-1, (mouse_x - auto_scroll_rect.left) / auto_scroll_margin - 1) * auto_scroll_max_speed) else if mouse_x > auto_scroll_rect.right - auto_scroll_margin Math.ceil(Math.min(1, (mouse_x - auto_scroll_rect.right) / auto_scroll_margin + 1) * auto_scroll_max_speed) else 0 auto_scroll_y = if mouse_y < auto_scroll_rect.top + auto_scroll_margin Math.floor(Math.max(-1, (mouse_y - auto_scroll_rect.top) / auto_scroll_margin - 1) * auto_scroll_max_speed) else if mouse_y > auto_scroll_rect.bottom - auto_scroll_margin Math.ceil(Math.min(1, (mouse_y - auto_scroll_rect.bottom) / auto_scroll_margin + 1) * auto_scroll_max_speed) else 0 # update the selection while auto-scrolling update_selection() @auto_scroll_timeout_id = setTimeout => auto_scroll_container_el.scrollLeft += auto_scroll_x auto_scroll_container_el.scrollTop += auto_scroll_y @auto_scroll_animation_frame = requestAnimationFrame(auto_scroll) mouse_moved_timewise = no mouse_moved_trackwise = no update_selection = => if Math.abs(position_at(mouse_x) - starting_position) > 5 / scale mouse_moved_timewise = yes if nearest_track_id_at(mouse_y) isnt starting_track_id mouse_moved_trackwise = yes if @props.selection and (mouse_moved_timewise or mouse_moved_trackwise) drag_position = if mouse_moved_timewise then position_at(mouse_x) else starting_position drag_track_id = if mouse_moved_trackwise then nearest_track_id_at(mouse_y) else starting_track_id editor.select_to drag_position, drag_track_id window.addEventListener "mousemove", onMouseMove = (e)=> mouse_x = e.clientX mouse_y = e.clientY update_selection() e.preventDefault() cancelAnimationFrame(@auto_scroll_animation_frame) @auto_scroll_animation_frame = requestAnimationFrame(auto_scroll) window.addEventListener "mouseup", onMouseUp = (e)=> window.removeEventListener "mouseup", onMouseUp window.removeEventListener "mousemove", onMouseMove cancelAnimationFrame(@auto_scroll_animation_frame) clearTimeout(@auto_scroll_timeout_id) unless mouse_moved_timewise editor.seek starting_position editor.setState moving_selection: no editor.save() E ".document-width", key: "document-width" style: width: document_width # NOTE: it apparently needs some height to cause scrolling flex: "0 0 1px" # and we don't want some random extra height somewhere # so we at least try to put it at the bottom order: 100000 if position? E ".position-indicator", key: "position-indicator" ref: "position_indicator" for track in tracks switch track.type when "beat" E BeatTrack, {key: track.id, track, scale, editor, document_width} when "audio" E AudioTrack, { key: track.id, track, scale, editor selection: (@props.selection if @props.selection?.containsTrack track) } when "midi" E MIDITrack, { key: track.id, track, scale, editor selection: (@props.selection if @props.selection?.containsTrack track) } else E UnknownTrack, {key: track.id, track, scale, editor} # E MIDITrack, { # key: "midi-PI:KEY:<KEY>END_PI" # track: { # notes: [ # {t: 0, length: 1/4, note: 65} # {t: 1/4, length: 1/4, note: 66} # {t: 2/4, length: 2/4, note: 68} # ] # } # scale, editor # selection: (@props.selection if @props.selection?.containsTrack track) # } if document_is_basically_empty E ".track.getting-started.timeline-independent", {key: "getting-on-track"}, E ".track-content", E "p", "To get started, hit record above or drag and drop to add some tracks." animate: -> {scale} = @props @animation_frame = requestAnimationFrame => @animate() tracks_area_el = ReactDOM.findDOMNode(@) tracks_area_rect = tracks_area_el.getBoundingClientRect() track_content_area_el = tracks_area_el.querySelector(".track-content-area") track_content_area_rect = track_content_area_el.getBoundingClientRect() track_els = tracks_area_el.querySelectorAll(".track") track_controls_els = tracks_area_el.querySelectorAll(".track-controls") for track_controls_el, i in track_controls_els track_el = track_els[i] track_rect = track_el.getBoundingClientRect() track_controls_el.style.top = "#{track_rect.top - tracks_area_rect.top + parseInt(getComputedStyle(track_el).paddingTop)}px" scroll_x = track_content_area_el.scrollLeft for track_el in track_els track_content_el = track_el.querySelector(".track-content > *") y_offset_anims = @y_offset_anims_by_track_id[track_el.dataset.trackId] ? [] new_y_offset_anims = [] y_offset = 0 for anim in y_offset_anims pos = anim.pos() if pos <= 1 y_offset += anim.fn(pos) new_y_offset_anims.push(anim) @y_offset_anims_by_track_id[track_el.dataset.trackId] = new_y_offset_anims track_el.style.transform = "translate(#{scroll_x}px, #{y_offset}px)" unless track_el.classList.contains("timeline-independent") track_content_el.style.transform = "translateX(#{-scroll_x}px)" if @refs.position_indicator any_old_track_content_el = track_el.querySelector(".track-content") any_old_track_content_rect = any_old_track_content_el.getBoundingClientRect() position = @props.position + if @props.playing then actx.currentTime - @props.position_time else 0 x = scale * position + any_old_track_content_rect.left if @props.playing # pagination behavior keep_margin_right = 5 scroll_by = any_old_track_content_rect.width # incremental behavior # keep_margin_right = 5 # scroll_by = 200 # almost-smooth behavior, # but scroll_by is a misnomer here # and even without the setTimeout the position indicator still jiggles # more problematically, if you seek ahead it's confusing # keep_margin_right = 200 # scroll_by = 0 delta_x = x - track_content_area_el.scrollLeft - any_old_track_content_rect.right + keep_margin_right if delta_x > 0 setTimeout -> # do scroll outside of animation loop! # XXX: recalculate delta because it may have changed delta_x = x - track_content_area_el.scrollLeft - any_old_track_content_rect.right + keep_margin_right track_content_area_el.scrollLeft += delta_x + scroll_by @refs.position_indicator.style.left = "#{x - track_content_area_rect.left}px" @refs.position_indicator.style.top = "#{track_content_area_el.scrollTop}px" getSnapshotBeforeUpdate: ()=> # for transitioning track positions # get a baseline for measuring differences in track y positions @last_track_rects = {} for track_current, track_index in @props.tracks track_els = ReactDOM.findDOMNode(@).querySelectorAll(".track") track_el = track_els[track_index] if track_el @last_track_rects[track_current.id] = track_el.getBoundingClientRect() componentDidUpdate: (last_props, last_state)=> # measure differences in track y positions # and queue track transitions track_els = ReactDOM.findDOMNode(@).querySelectorAll(".track") for track_el, track_index in track_els current_rect = track_el.getBoundingClientRect() last_rect = @last_track_rects[track_el.dataset.trackId] if last_rect? do (last_rect, current_rect)=> delta_y = last_rect.top - current_rect.top if delta_y # add a transition transition_seconds = 0.3 start_time = Date.now() y_offset_anims = @y_offset_anims_by_track_id[track_el.dataset.trackId] ?= [] y_offset_anims.push({ pos: -> (Date.now() - start_time) / 1000 / transition_seconds fn: (pos)-> delta_y * easing.easeInOutQuart(1 - pos) }) # update immediately to avoid one-frame artifacts cancelAnimationFrame @animation_frame @animate() componentDidMount: -> @animate() componentWillUnmount: -> cancelAnimationFrame @animation_frame cancelAnimationFrame @auto_scroll_animation_frame
[ { "context": "*\n# @fileoverview Tests for jsx-no-undef\n# @author Yannick Croissant\n###\n\n'use strict'\n\n# ----------------------------", "end": 71, "score": 0.9998453259468079, "start": 54, "tag": "NAME", "value": "Yannick Croissant" } ]
src/tests/rules/jsx-no-undef.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for jsx-no-undef # @author Yannick Croissant ### 'use strict' # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- eslint = require 'eslint' rule = require 'eslint-plugin-react/lib/rules/jsx-no-undef' {RuleTester} = eslint path = require 'path' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' linter = ruleTester.linter or eslint.linter linter.defineRule 'no-undef', require 'eslint/lib/rules/no-undef' ruleTester.run 'jsx-no-undef', rule, valid: [ code: ''' ###eslint no-undef:1### React = null App = null React.render(<App />) ''' , code: ''' ###eslint no-undef:1### React = null App = null React.render(<App />) ''' , code: ''' ###eslint no-undef:1### React = null React.render(<img />) ''' , code: ''' ###eslint no-undef:1### React = null React.render(<x-gif />) ''' , code: ''' ###eslint no-undef:1### React = null app = null React.render(<app.Foo />) ''' , code: ''' ###eslint no-undef:1### React = null app = null React.render(<app.foo.Bar />) ''' , code: ''' ###eslint no-undef:1### React = null class Hello extends React.Component render: -> return <this.props.tag /> ''' , # , # code: ''' # React = null # React.render(<Text />) # ''' # globals: # Text: yes code: ''' React = null React.render(<Text />) ''' globals: Text: yes options: [allowGlobals: yes] , code: ''' import Text from "cool-module" TextWrapper = (props) -> ( <Text /> ) ''' # parserOptions: Object.assign {sourceType: 'module'}, parserOptions options: [allowGlobals: no] # parser: 'babel-eslint' ] invalid: [ code: ''' ###eslint no-undef:1### React = null React.render(<App />) ''' errors: [message: "'App' is not defined."] , code: ''' ###eslint no-undef:1### React = null React.render(<Appp.Foo />) ''' errors: [message: "'Appp' is not defined."] , # , # code: ''' # ###eslint no-undef:1### # React = null # React.render(<Apppp:Foo />) # ''' # errors: [message: "'Apppp' is not defined."] code: ''' ###eslint no-undef:1### React = null React.render(<appp.Foo />) ''' errors: [message: "'appp' is not defined."] , code: ''' ###eslint no-undef:1### React = null React.render(<appp.foo.Bar />) ''' errors: [message: "'appp' is not defined."] , code: ''' TextWrapper = (props) -> return ( <Text /> ) export default TextWrapper ''' # parserOptions: Object.assign {sourceType: 'module'}, parserOptions errors: [message: "'Text' is not defined."] options: [allowGlobals: no] # parser: 'babel-eslint' globals: Text: yes , code: ''' ###eslint no-undef:1### React = null React.render(<Foo />) ''' errors: [message: "'Foo' is not defined."] ]
154324
###* # @fileoverview Tests for jsx-no-undef # @author <NAME> ### 'use strict' # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- eslint = require 'eslint' rule = require 'eslint-plugin-react/lib/rules/jsx-no-undef' {RuleTester} = eslint path = require 'path' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' linter = ruleTester.linter or eslint.linter linter.defineRule 'no-undef', require 'eslint/lib/rules/no-undef' ruleTester.run 'jsx-no-undef', rule, valid: [ code: ''' ###eslint no-undef:1### React = null App = null React.render(<App />) ''' , code: ''' ###eslint no-undef:1### React = null App = null React.render(<App />) ''' , code: ''' ###eslint no-undef:1### React = null React.render(<img />) ''' , code: ''' ###eslint no-undef:1### React = null React.render(<x-gif />) ''' , code: ''' ###eslint no-undef:1### React = null app = null React.render(<app.Foo />) ''' , code: ''' ###eslint no-undef:1### React = null app = null React.render(<app.foo.Bar />) ''' , code: ''' ###eslint no-undef:1### React = null class Hello extends React.Component render: -> return <this.props.tag /> ''' , # , # code: ''' # React = null # React.render(<Text />) # ''' # globals: # Text: yes code: ''' React = null React.render(<Text />) ''' globals: Text: yes options: [allowGlobals: yes] , code: ''' import Text from "cool-module" TextWrapper = (props) -> ( <Text /> ) ''' # parserOptions: Object.assign {sourceType: 'module'}, parserOptions options: [allowGlobals: no] # parser: 'babel-eslint' ] invalid: [ code: ''' ###eslint no-undef:1### React = null React.render(<App />) ''' errors: [message: "'App' is not defined."] , code: ''' ###eslint no-undef:1### React = null React.render(<Appp.Foo />) ''' errors: [message: "'Appp' is not defined."] , # , # code: ''' # ###eslint no-undef:1### # React = null # React.render(<Apppp:Foo />) # ''' # errors: [message: "'Apppp' is not defined."] code: ''' ###eslint no-undef:1### React = null React.render(<appp.Foo />) ''' errors: [message: "'appp' is not defined."] , code: ''' ###eslint no-undef:1### React = null React.render(<appp.foo.Bar />) ''' errors: [message: "'appp' is not defined."] , code: ''' TextWrapper = (props) -> return ( <Text /> ) export default TextWrapper ''' # parserOptions: Object.assign {sourceType: 'module'}, parserOptions errors: [message: "'Text' is not defined."] options: [allowGlobals: no] # parser: 'babel-eslint' globals: Text: yes , code: ''' ###eslint no-undef:1### React = null React.render(<Foo />) ''' errors: [message: "'Foo' is not defined."] ]
true
###* # @fileoverview Tests for jsx-no-undef # @author PI:NAME:<NAME>END_PI ### 'use strict' # ----------------------------------------------------------------------------- # Requirements # ----------------------------------------------------------------------------- eslint = require 'eslint' rule = require 'eslint-plugin-react/lib/rules/jsx-no-undef' {RuleTester} = eslint path = require 'path' # ----------------------------------------------------------------------------- # Tests # ----------------------------------------------------------------------------- ruleTester = new RuleTester parser: path.join __dirname, '../../..' linter = ruleTester.linter or eslint.linter linter.defineRule 'no-undef', require 'eslint/lib/rules/no-undef' ruleTester.run 'jsx-no-undef', rule, valid: [ code: ''' ###eslint no-undef:1### React = null App = null React.render(<App />) ''' , code: ''' ###eslint no-undef:1### React = null App = null React.render(<App />) ''' , code: ''' ###eslint no-undef:1### React = null React.render(<img />) ''' , code: ''' ###eslint no-undef:1### React = null React.render(<x-gif />) ''' , code: ''' ###eslint no-undef:1### React = null app = null React.render(<app.Foo />) ''' , code: ''' ###eslint no-undef:1### React = null app = null React.render(<app.foo.Bar />) ''' , code: ''' ###eslint no-undef:1### React = null class Hello extends React.Component render: -> return <this.props.tag /> ''' , # , # code: ''' # React = null # React.render(<Text />) # ''' # globals: # Text: yes code: ''' React = null React.render(<Text />) ''' globals: Text: yes options: [allowGlobals: yes] , code: ''' import Text from "cool-module" TextWrapper = (props) -> ( <Text /> ) ''' # parserOptions: Object.assign {sourceType: 'module'}, parserOptions options: [allowGlobals: no] # parser: 'babel-eslint' ] invalid: [ code: ''' ###eslint no-undef:1### React = null React.render(<App />) ''' errors: [message: "'App' is not defined."] , code: ''' ###eslint no-undef:1### React = null React.render(<Appp.Foo />) ''' errors: [message: "'Appp' is not defined."] , # , # code: ''' # ###eslint no-undef:1### # React = null # React.render(<Apppp:Foo />) # ''' # errors: [message: "'Apppp' is not defined."] code: ''' ###eslint no-undef:1### React = null React.render(<appp.Foo />) ''' errors: [message: "'appp' is not defined."] , code: ''' ###eslint no-undef:1### React = null React.render(<appp.foo.Bar />) ''' errors: [message: "'appp' is not defined."] , code: ''' TextWrapper = (props) -> return ( <Text /> ) export default TextWrapper ''' # parserOptions: Object.assign {sourceType: 'module'}, parserOptions errors: [message: "'Text' is not defined."] options: [allowGlobals: no] # parser: 'babel-eslint' globals: Text: yes , code: ''' ###eslint no-undef:1### React = null React.render(<Foo />) ''' errors: [message: "'Foo' is not defined."] ]
[ { "context": "# Data sourced by Cobus Coetzee. Available on thedatahub at:\n# http://thedatahu", "end": 31, "score": 0.9998988509178162, "start": 18, "tag": "NAME", "value": "Cobus Coetzee" } ]
data/coffeescript/55375b864f6fe22900eca16fc0e70dcd_data.coffee
maxim5/code-inspector
5
# Data sourced by Cobus Coetzee. Available on thedatahub at: # http://thedatahub.org/dataset/south-african-national-gov-budget-2012-13 exports.income_tax = 2012: bands: [ {width: 160000, rate: 0.18} {width: 90000, rate: 0.25} {width: 96000, rate: 0.30} {width: 138000, rate: 0.35} {width: 133000, rate: 0.38} {rate: 0.4} ] exports.rebates = 2012: base: 11440 # these are ADDITIONAL rebates on top of the base value aged_65_to_74: 6390 aged_75_plus: 2130
8369
# Data sourced by <NAME>. Available on thedatahub at: # http://thedatahub.org/dataset/south-african-national-gov-budget-2012-13 exports.income_tax = 2012: bands: [ {width: 160000, rate: 0.18} {width: 90000, rate: 0.25} {width: 96000, rate: 0.30} {width: 138000, rate: 0.35} {width: 133000, rate: 0.38} {rate: 0.4} ] exports.rebates = 2012: base: 11440 # these are ADDITIONAL rebates on top of the base value aged_65_to_74: 6390 aged_75_plus: 2130
true
# Data sourced by PI:NAME:<NAME>END_PI. Available on thedatahub at: # http://thedatahub.org/dataset/south-african-national-gov-budget-2012-13 exports.income_tax = 2012: bands: [ {width: 160000, rate: 0.18} {width: 90000, rate: 0.25} {width: 96000, rate: 0.30} {width: 138000, rate: 0.35} {width: 133000, rate: 0.38} {rate: 0.4} ] exports.rebates = 2012: base: 11440 # these are ADDITIONAL rebates on top of the base value aged_65_to_74: 6390 aged_75_plus: 2130
[ { "context": "root: root\n gh: gh\n config: config\n user: repo_user\n repo: repo_name\n branch: config.branch or ", "end": 705, "score": 0.9792672991752625, "start": 696, "tag": "USERNAME", "value": "repo_user" }, { "context": "asic'\n username: @config.username\n password: @config.password\n W.resolve()\n\n###*\n * Grabs the l", "end": 1440, "score": 0.5775771737098694, "start": 1440, "tag": "PASSWORD", "value": "" }, { "context": " username: @config.username\n password: @config.password\n W.resolve()\n\n###*\n * Grabs the latest commit fr", "end": 1457, "score": 0.5437073111534119, "start": 1449, "tag": "PASSWORD", "value": "password" }, { "context": "= ->\n nodefn.call @gh.repos.getCommits,\n user: @user\n repo: @repo\n sha: @branch\n .then (res) ->", "end": 1760, "score": 0.9957346320152283, "start": 1755, "tag": "USERNAME", "value": "@user" }, { "context": "= ->\n nodefn.call @gh.repos.createFile,\n user: @user\n repo: @repo\n branch: @branch\n message: ", "end": 2304, "score": 0.9969642162322998, "start": 2299, "tag": "USERNAME", "value": "@user" }, { "context": "defn.call @gh.gitdata.createReference,\n user: @user\n repo: @repo\n ref: \"refs/heads/#{@branc", "end": 2610, "score": 0.9964176416397095, "start": 2605, "tag": "USERNAME", "value": "@user" }, { "context": " ->\n nodefn.call @gh.repos.getBranches,\n user: @user\n repo: @repo\n .then (res) -> res[0]\n\n###*\n * ", "end": 2770, "score": 0.9947996139526367, "start": 2765, "tag": "USERNAME", "value": "@user" }, { "context": "n.call @gh.gitdata.createBlob.bind(@gh),\n user: @user\n repo: @repo\n content: content.toString('ba", "end": 5287, "score": 0.9891290664672852, "start": 5282, "tag": "USERNAME", "value": "@user" }, { "context": "n.call @gh.gitdata.createTree.bind(@gh),\n user: @user\n repo: @repo\n tree: tree\n .then (res) -> r", "end": 5706, "score": 0.9858226776123047, "start": 5701, "tag": "USERNAME", "value": "@user" }, { "context": " nodefn.call @gh.gitdata.createCommit,\n user: @user\n repo: @repo\n parents: [sha]\n tree", "end": 6100, "score": 0.9809674024581909, "start": 6095, "tag": "USERNAME", "value": "@user" }, { "context": "nodefn.call @gh.gitdata.updateReference,\n user: @user\n repo: @repo\n ref: \"heads/#{@branch}\"\n s", "end": 6522, "score": 0.9876882433891296, "start": 6517, "tag": "USERNAME", "value": "@user" }, { "context": "nodefn.call @gh.gitdata.deleteReference,\n user: @user\n repo: @repo\n ref: \"heads/#{@branch}\"\n", "end": 6742, "score": 0.9877156019210815, "start": 6737, "tag": "USERNAME", "value": "@user" } ]
lib/deployers/gh-pages/index.coffee
carrot/ship
151
path = require 'path' fs = require 'fs' W = require 'when' nodefn = require 'when/node' guard = require 'when/guard' keys = require 'when/keys' _ = require 'lodash' readdirp = require 'readdirp' GithubApi = require 'github' minimatch = require 'minimatch' file_map = require 'file-map' module.exports = (root, config) -> d = W.defer() config.ignore = _.compact([ '.gitignore', '.git{/**,}', '**/node_modules{/**,}'].concat(config.ignore)) repo_user = config.repo.split('/')[0] repo_name = config.repo.split('/')[1] gh = new GithubApi(version: "3.0.0", debug: false) ctx = root: root gh: gh config: config user: repo_user repo: repo_name branch: config.branch or 'gh-pages' authenticate.call(ctx).with(ctx) .then(get_latest_commit) .then(build_tree) .then(create_commit) .then(update_gh_pages_branch) .done -> d.resolve deployer: 'gh-pages' url: "http://#{repo_user}.github.io/#{repo_name}" destroy: destroy.bind(@) , d.reject return d.promise module.exports.config = required: ['username', 'password', 'repo'] optional: ['ignore'] ###* * Authenticates with github using the provided credentials * @return {Promise} - completed authentication, if incorrect, errors come later ### authenticate = -> @gh.authenticate type: 'basic' username: @config.username password: @config.password W.resolve() ###* * Grabs the latest commit from the github pages branch. If this doesn't exist, * creates the branch with a commit for a basic readme. * * @return {Promise} a promise for the sha of the latest commit ### get_latest_commit = -> nodefn.call @gh.repos.getCommits, user: @user repo: @repo sha: @branch .then (res) -> res[0].sha .catch (err) => msg = JSON.parse(err.message).message if msg == 'Git Repository is empty.' return create_initial_commit.call(@) if msg == 'Not Found' return create_branch.call(@) throw err ###* * If a repo is empty, a commit needs to be created before trees can be pushed. * This method creates * @return {Promise} a promise for the sha of the newly created commit ### create_initial_commit = -> nodefn.call @gh.repos.createFile, user: @user repo: @repo branch: @branch message: 'initial commit' path: 'README.md' content: new Buffer("#{@user}/#{@repo}").toString('base64') .then (res) -> res.sha create_branch = -> get_default_branch.call(@).then (branch) => nodefn.call @gh.gitdata.createReference, user: @user repo: @repo ref: "refs/heads/#{@branch}" sha: branch.commit.sha get_default_branch = -> nodefn.call @gh.repos.getBranches, user: @user repo: @repo .then (res) -> res[0] ###* * Runs through the root and recrusively builds up the structure in the format * that github needs it. Creates blobs for files and trees at every folder * level, nesting them inside each other and returning a single tree object with * SHA's from github, ready to be committed. * * @return {Object} github-formatted tree object ### build_tree = -> i = @config.ignore file_map(@root, { file_ignores: i, directory_ignores: i }) .then (tree) => format_tree.call(@, path: '', children: tree) ###* * This is the real workhorse. This method recurses through a given directory, * grabbing the files and folders and creating blobs and trees, nested properly, * through github's API. * * @param {Object} root - a directory object provided by file-map * @return {Promise} a promise for a github-formatted tree object ### format_tree = (root) -> dirs = _.where(root.children, { type: 'directory' }) files = _.where(root.children, { type: 'file' }) if dirs.length W.map(dirs, format_tree.bind(@)) .then (dir_objects) => W.map(files, create_blob.bind(@)) .then (file_objects) -> dir_objects.concat(file_objects) .then(create_tree.bind(@, root)) else W.map(files, create_blob.bind(@)) .then(create_tree.bind(@, root)) ###* * Creates a blob through github's API, given a file. * * @param {Object} file - file object via file-map * @return {Promise} promise for a github-formatted file object with the sha ### create_blob = (file) -> nodefn.call(fs.readFile, file.full_path) .then(get_blob_sha.bind(@)) .then (sha) -> path: path.basename(file.path) mode: '100644' type: 'blob' sha: sha ###* * Creates a tree through github's API, given an array of contents. * * @param {Object} root - directory object via file-map of the tree's root dir * @param {Array} tree - array of github-formatted tree and/or blob objects * @return {Promise} promise for a github-formatted tree object with the sha ### create_tree = (root, tree) -> get_tree_sha.call(@, tree) .then (sha) -> path: path.basename(root.path) mode: '040000' type: 'tree' sha: sha ###* * Given a file's content, creates a blob through github and returns the sha. * * @param {String} content - the content of a file, as a utf8 string * @return {Promise} promise for a string representing the blob's sha ### get_blob_sha = (content) -> nodefn.call @gh.gitdata.createBlob.bind(@gh), user: @user repo: @repo content: content.toString('base64') encoding: 'base64' .then (res) -> res.sha ###* * Given a tree array, creates a tree through github and returns the sha. * * @param {Array} tree - array containing tree and/or blob objects * @return {Promise} promise for a string representing the tree's sha ### get_tree_sha = (tree) -> nodefn.call @gh.gitdata.createTree.bind(@gh), user: @user repo: @repo tree: tree .then (res) -> res.sha ###* * Given a tree, creates a new commit pointing to that tree. * * @param {Object} tree - github-formatted tree object * @return {Promise} promise for github api's response to creating the commit ### create_commit = (tree) -> get_latest_commit.call(@) .then (sha) => nodefn.call @gh.gitdata.createCommit, user: @user repo: @repo parents: [sha] tree: tree.sha message: "deploy from ship" ###* * Points the deploy target branch's HEAD to the sha of a given commit. * * @param {Object} commit - github api representation of a commit * @return {Promise} promise for the github api's response to updating the ref ### update_gh_pages_branch = (commit) -> nodefn.call @gh.gitdata.updateReference, user: @user repo: @repo ref: "heads/#{@branch}" sha: commit.sha force: true ###* * Removes the deploy target branch, undoing the deploy. ### destroy = -> nodefn.call @gh.gitdata.deleteReference, user: @user repo: @repo ref: "heads/#{@branch}"
37724
path = require 'path' fs = require 'fs' W = require 'when' nodefn = require 'when/node' guard = require 'when/guard' keys = require 'when/keys' _ = require 'lodash' readdirp = require 'readdirp' GithubApi = require 'github' minimatch = require 'minimatch' file_map = require 'file-map' module.exports = (root, config) -> d = W.defer() config.ignore = _.compact([ '.gitignore', '.git{/**,}', '**/node_modules{/**,}'].concat(config.ignore)) repo_user = config.repo.split('/')[0] repo_name = config.repo.split('/')[1] gh = new GithubApi(version: "3.0.0", debug: false) ctx = root: root gh: gh config: config user: repo_user repo: repo_name branch: config.branch or 'gh-pages' authenticate.call(ctx).with(ctx) .then(get_latest_commit) .then(build_tree) .then(create_commit) .then(update_gh_pages_branch) .done -> d.resolve deployer: 'gh-pages' url: "http://#{repo_user}.github.io/#{repo_name}" destroy: destroy.bind(@) , d.reject return d.promise module.exports.config = required: ['username', 'password', 'repo'] optional: ['ignore'] ###* * Authenticates with github using the provided credentials * @return {Promise} - completed authentication, if incorrect, errors come later ### authenticate = -> @gh.authenticate type: 'basic' username: @config.username password:<PASSWORD> @config.<PASSWORD> W.resolve() ###* * Grabs the latest commit from the github pages branch. If this doesn't exist, * creates the branch with a commit for a basic readme. * * @return {Promise} a promise for the sha of the latest commit ### get_latest_commit = -> nodefn.call @gh.repos.getCommits, user: @user repo: @repo sha: @branch .then (res) -> res[0].sha .catch (err) => msg = JSON.parse(err.message).message if msg == 'Git Repository is empty.' return create_initial_commit.call(@) if msg == 'Not Found' return create_branch.call(@) throw err ###* * If a repo is empty, a commit needs to be created before trees can be pushed. * This method creates * @return {Promise} a promise for the sha of the newly created commit ### create_initial_commit = -> nodefn.call @gh.repos.createFile, user: @user repo: @repo branch: @branch message: 'initial commit' path: 'README.md' content: new Buffer("#{@user}/#{@repo}").toString('base64') .then (res) -> res.sha create_branch = -> get_default_branch.call(@).then (branch) => nodefn.call @gh.gitdata.createReference, user: @user repo: @repo ref: "refs/heads/#{@branch}" sha: branch.commit.sha get_default_branch = -> nodefn.call @gh.repos.getBranches, user: @user repo: @repo .then (res) -> res[0] ###* * Runs through the root and recrusively builds up the structure in the format * that github needs it. Creates blobs for files and trees at every folder * level, nesting them inside each other and returning a single tree object with * SHA's from github, ready to be committed. * * @return {Object} github-formatted tree object ### build_tree = -> i = @config.ignore file_map(@root, { file_ignores: i, directory_ignores: i }) .then (tree) => format_tree.call(@, path: '', children: tree) ###* * This is the real workhorse. This method recurses through a given directory, * grabbing the files and folders and creating blobs and trees, nested properly, * through github's API. * * @param {Object} root - a directory object provided by file-map * @return {Promise} a promise for a github-formatted tree object ### format_tree = (root) -> dirs = _.where(root.children, { type: 'directory' }) files = _.where(root.children, { type: 'file' }) if dirs.length W.map(dirs, format_tree.bind(@)) .then (dir_objects) => W.map(files, create_blob.bind(@)) .then (file_objects) -> dir_objects.concat(file_objects) .then(create_tree.bind(@, root)) else W.map(files, create_blob.bind(@)) .then(create_tree.bind(@, root)) ###* * Creates a blob through github's API, given a file. * * @param {Object} file - file object via file-map * @return {Promise} promise for a github-formatted file object with the sha ### create_blob = (file) -> nodefn.call(fs.readFile, file.full_path) .then(get_blob_sha.bind(@)) .then (sha) -> path: path.basename(file.path) mode: '100644' type: 'blob' sha: sha ###* * Creates a tree through github's API, given an array of contents. * * @param {Object} root - directory object via file-map of the tree's root dir * @param {Array} tree - array of github-formatted tree and/or blob objects * @return {Promise} promise for a github-formatted tree object with the sha ### create_tree = (root, tree) -> get_tree_sha.call(@, tree) .then (sha) -> path: path.basename(root.path) mode: '040000' type: 'tree' sha: sha ###* * Given a file's content, creates a blob through github and returns the sha. * * @param {String} content - the content of a file, as a utf8 string * @return {Promise} promise for a string representing the blob's sha ### get_blob_sha = (content) -> nodefn.call @gh.gitdata.createBlob.bind(@gh), user: @user repo: @repo content: content.toString('base64') encoding: 'base64' .then (res) -> res.sha ###* * Given a tree array, creates a tree through github and returns the sha. * * @param {Array} tree - array containing tree and/or blob objects * @return {Promise} promise for a string representing the tree's sha ### get_tree_sha = (tree) -> nodefn.call @gh.gitdata.createTree.bind(@gh), user: @user repo: @repo tree: tree .then (res) -> res.sha ###* * Given a tree, creates a new commit pointing to that tree. * * @param {Object} tree - github-formatted tree object * @return {Promise} promise for github api's response to creating the commit ### create_commit = (tree) -> get_latest_commit.call(@) .then (sha) => nodefn.call @gh.gitdata.createCommit, user: @user repo: @repo parents: [sha] tree: tree.sha message: "deploy from ship" ###* * Points the deploy target branch's HEAD to the sha of a given commit. * * @param {Object} commit - github api representation of a commit * @return {Promise} promise for the github api's response to updating the ref ### update_gh_pages_branch = (commit) -> nodefn.call @gh.gitdata.updateReference, user: @user repo: @repo ref: "heads/#{@branch}" sha: commit.sha force: true ###* * Removes the deploy target branch, undoing the deploy. ### destroy = -> nodefn.call @gh.gitdata.deleteReference, user: @user repo: @repo ref: "heads/#{@branch}"
true
path = require 'path' fs = require 'fs' W = require 'when' nodefn = require 'when/node' guard = require 'when/guard' keys = require 'when/keys' _ = require 'lodash' readdirp = require 'readdirp' GithubApi = require 'github' minimatch = require 'minimatch' file_map = require 'file-map' module.exports = (root, config) -> d = W.defer() config.ignore = _.compact([ '.gitignore', '.git{/**,}', '**/node_modules{/**,}'].concat(config.ignore)) repo_user = config.repo.split('/')[0] repo_name = config.repo.split('/')[1] gh = new GithubApi(version: "3.0.0", debug: false) ctx = root: root gh: gh config: config user: repo_user repo: repo_name branch: config.branch or 'gh-pages' authenticate.call(ctx).with(ctx) .then(get_latest_commit) .then(build_tree) .then(create_commit) .then(update_gh_pages_branch) .done -> d.resolve deployer: 'gh-pages' url: "http://#{repo_user}.github.io/#{repo_name}" destroy: destroy.bind(@) , d.reject return d.promise module.exports.config = required: ['username', 'password', 'repo'] optional: ['ignore'] ###* * Authenticates with github using the provided credentials * @return {Promise} - completed authentication, if incorrect, errors come later ### authenticate = -> @gh.authenticate type: 'basic' username: @config.username password:PI:PASSWORD:<PASSWORD>END_PI @config.PI:PASSWORD:<PASSWORD>END_PI W.resolve() ###* * Grabs the latest commit from the github pages branch. If this doesn't exist, * creates the branch with a commit for a basic readme. * * @return {Promise} a promise for the sha of the latest commit ### get_latest_commit = -> nodefn.call @gh.repos.getCommits, user: @user repo: @repo sha: @branch .then (res) -> res[0].sha .catch (err) => msg = JSON.parse(err.message).message if msg == 'Git Repository is empty.' return create_initial_commit.call(@) if msg == 'Not Found' return create_branch.call(@) throw err ###* * If a repo is empty, a commit needs to be created before trees can be pushed. * This method creates * @return {Promise} a promise for the sha of the newly created commit ### create_initial_commit = -> nodefn.call @gh.repos.createFile, user: @user repo: @repo branch: @branch message: 'initial commit' path: 'README.md' content: new Buffer("#{@user}/#{@repo}").toString('base64') .then (res) -> res.sha create_branch = -> get_default_branch.call(@).then (branch) => nodefn.call @gh.gitdata.createReference, user: @user repo: @repo ref: "refs/heads/#{@branch}" sha: branch.commit.sha get_default_branch = -> nodefn.call @gh.repos.getBranches, user: @user repo: @repo .then (res) -> res[0] ###* * Runs through the root and recrusively builds up the structure in the format * that github needs it. Creates blobs for files and trees at every folder * level, nesting them inside each other and returning a single tree object with * SHA's from github, ready to be committed. * * @return {Object} github-formatted tree object ### build_tree = -> i = @config.ignore file_map(@root, { file_ignores: i, directory_ignores: i }) .then (tree) => format_tree.call(@, path: '', children: tree) ###* * This is the real workhorse. This method recurses through a given directory, * grabbing the files and folders and creating blobs and trees, nested properly, * through github's API. * * @param {Object} root - a directory object provided by file-map * @return {Promise} a promise for a github-formatted tree object ### format_tree = (root) -> dirs = _.where(root.children, { type: 'directory' }) files = _.where(root.children, { type: 'file' }) if dirs.length W.map(dirs, format_tree.bind(@)) .then (dir_objects) => W.map(files, create_blob.bind(@)) .then (file_objects) -> dir_objects.concat(file_objects) .then(create_tree.bind(@, root)) else W.map(files, create_blob.bind(@)) .then(create_tree.bind(@, root)) ###* * Creates a blob through github's API, given a file. * * @param {Object} file - file object via file-map * @return {Promise} promise for a github-formatted file object with the sha ### create_blob = (file) -> nodefn.call(fs.readFile, file.full_path) .then(get_blob_sha.bind(@)) .then (sha) -> path: path.basename(file.path) mode: '100644' type: 'blob' sha: sha ###* * Creates a tree through github's API, given an array of contents. * * @param {Object} root - directory object via file-map of the tree's root dir * @param {Array} tree - array of github-formatted tree and/or blob objects * @return {Promise} promise for a github-formatted tree object with the sha ### create_tree = (root, tree) -> get_tree_sha.call(@, tree) .then (sha) -> path: path.basename(root.path) mode: '040000' type: 'tree' sha: sha ###* * Given a file's content, creates a blob through github and returns the sha. * * @param {String} content - the content of a file, as a utf8 string * @return {Promise} promise for a string representing the blob's sha ### get_blob_sha = (content) -> nodefn.call @gh.gitdata.createBlob.bind(@gh), user: @user repo: @repo content: content.toString('base64') encoding: 'base64' .then (res) -> res.sha ###* * Given a tree array, creates a tree through github and returns the sha. * * @param {Array} tree - array containing tree and/or blob objects * @return {Promise} promise for a string representing the tree's sha ### get_tree_sha = (tree) -> nodefn.call @gh.gitdata.createTree.bind(@gh), user: @user repo: @repo tree: tree .then (res) -> res.sha ###* * Given a tree, creates a new commit pointing to that tree. * * @param {Object} tree - github-formatted tree object * @return {Promise} promise for github api's response to creating the commit ### create_commit = (tree) -> get_latest_commit.call(@) .then (sha) => nodefn.call @gh.gitdata.createCommit, user: @user repo: @repo parents: [sha] tree: tree.sha message: "deploy from ship" ###* * Points the deploy target branch's HEAD to the sha of a given commit. * * @param {Object} commit - github api representation of a commit * @return {Promise} promise for the github api's response to updating the ref ### update_gh_pages_branch = (commit) -> nodefn.call @gh.gitdata.updateReference, user: @user repo: @repo ref: "heads/#{@branch}" sha: commit.sha force: true ###* * Removes the deploy target branch, undoing the deploy. ### destroy = -> nodefn.call @gh.gitdata.deleteReference, user: @user repo: @repo ref: "heads/#{@branch}"
[ { "context": " good object', (assert) ->\n model = \n email: \"foxnewsnetwork@gmail.com\"\n username: \"foxnewsnetwork\"\n\n presence(\"emai", "end": 393, "score": 0.9999223947525024, "start": 369, "tag": "EMAIL", "value": "foxnewsnetwork@gmail.com" }, { "context": " email: \"foxnewsnetwork@gmail.com\"\n username: \"foxnewsnetwork\"\n\n presence(\"email\", true, model).then (checkedM", "end": 424, "score": 0.999509871006012, "start": 410, "tag": "USERNAME", "value": "foxnewsnetwork" } ]
tests/unit/validators/presence-test.coffee
foxnewsnetwork/ember-functional-validation
4
`import Ember from 'ember'` `import { module, test } from 'qunit'` `import presence from 'ember-functional-validation/validators/presence'` module 'Validators: Presence' test 'it should exist', (assert) -> assert.ok presence assert.equal typeof presence, 'function' test 'it should resolve to a good promise on a good object', (assert) -> model = email: "foxnewsnetwork@gmail.com" username: "foxnewsnetwork" presence("email", true, model).then (checkedModel) -> assert.equal checkedModel, model .catch -> assert.ok false, "it should not get here" test 'it should properly reject a bad object', (assert) -> model = null presence "email", true, model .then -> assert.ok false, "it should not resolve a bad object" .catch (error) -> assert.equal error.size, 1 assert.equal error.get("email"), "cannot be blank" test 'it should properly error when missing an attribute', (assert) -> assert.throws presence, /must specify an attribute/ test 'it should be able to display a custom message', (assert) -> presence "email", { message: ">tfw no gf" }, null .then -> assert.ok false, "it should not resolve a bad object" .catch (error) -> assert.equal error.size, 1 assert.equal error.get("email"), ">tfw no gf"
146493
`import Ember from 'ember'` `import { module, test } from 'qunit'` `import presence from 'ember-functional-validation/validators/presence'` module 'Validators: Presence' test 'it should exist', (assert) -> assert.ok presence assert.equal typeof presence, 'function' test 'it should resolve to a good promise on a good object', (assert) -> model = email: "<EMAIL>" username: "foxnewsnetwork" presence("email", true, model).then (checkedModel) -> assert.equal checkedModel, model .catch -> assert.ok false, "it should not get here" test 'it should properly reject a bad object', (assert) -> model = null presence "email", true, model .then -> assert.ok false, "it should not resolve a bad object" .catch (error) -> assert.equal error.size, 1 assert.equal error.get("email"), "cannot be blank" test 'it should properly error when missing an attribute', (assert) -> assert.throws presence, /must specify an attribute/ test 'it should be able to display a custom message', (assert) -> presence "email", { message: ">tfw no gf" }, null .then -> assert.ok false, "it should not resolve a bad object" .catch (error) -> assert.equal error.size, 1 assert.equal error.get("email"), ">tfw no gf"
true
`import Ember from 'ember'` `import { module, test } from 'qunit'` `import presence from 'ember-functional-validation/validators/presence'` module 'Validators: Presence' test 'it should exist', (assert) -> assert.ok presence assert.equal typeof presence, 'function' test 'it should resolve to a good promise on a good object', (assert) -> model = email: "PI:EMAIL:<EMAIL>END_PI" username: "foxnewsnetwork" presence("email", true, model).then (checkedModel) -> assert.equal checkedModel, model .catch -> assert.ok false, "it should not get here" test 'it should properly reject a bad object', (assert) -> model = null presence "email", true, model .then -> assert.ok false, "it should not resolve a bad object" .catch (error) -> assert.equal error.size, 1 assert.equal error.get("email"), "cannot be blank" test 'it should properly error when missing an attribute', (assert) -> assert.throws presence, /must specify an attribute/ test 'it should be able to display a custom message', (assert) -> presence "email", { message: ">tfw no gf" }, null .then -> assert.ok false, "it should not resolve a bad object" .catch (error) -> assert.equal error.size, 1 assert.equal error.get("email"), ">tfw no gf"
[ { "context": "nstance to add\n ###\n key = _browserInstances.length\n _browserInstances[key] = browserInstance\n ", "end": 3824, "score": 0.7006527185440063, "start": 3818, "tag": "KEY", "value": "length" } ]
src/stof.coffee
megaplan/stof
2
webdriver = require './webdriver' PathResolver = require './utils/PathResolver' fs = require 'fs.extra' path = require 'path' _ = require 'lodash' Browser = require './Browser' # Classes for inheriting in concrete test's implementation PageObject = require './page-objects/PageObject' Form = require './page-objects/Form' TestHelper = require './helpers/TestHelper' ### Private properties and methods ### _config = null _testName = null _currentContext = null _currentAbsolutePath = null _currentRelativePath = null _uncaughtExceptionSet = false _browserInstances = [] _pathResolver = new PathResolver _loadConfig = -> ### Reads test config @return {object} ### stofConfig = require('./config') defaultConfig = self.loadFile('/config//defaultConfig', '', false) _.merge(stofConfig, defaultConfig) _config = self.loadFile('/config//config', '', false) _config = _.merge(stofConfig, _config) _config _parseTestRootDir = -> ### Finds test root dir path in command line arguments and process environment @return {String} ### testRootDir = null process.argv.forEach (value) -> testRootDir = value.substr('--stof-root-dir='.length) if value.indexOf('--stof-root-dir=') == 0 return testRootDir if testRootDir? if not process.env.STOF_ROOT_DIR? throw new Error('Please specify command line argument --stof-root-dir or environment variable STOF_ROOT_DIR') process.env.STOF_ROOT_DIR _parseTargetDir = -> ### Finds test target dir path in command line arguments and process environment. By default returns 'target' @return {String} ### testTargetDir = null process.argv.forEach (value) -> testTargetDir = value.substr('--stof-target-dir='.length) if value.indexOf('--stof-target-dir=') == 0 return testTargetDir if testTargetDir? return process.env.STOF_TARGET_DIR if process.env.STOF_TARGET_DIR? 'target' _prepareStackTrace = (stack) -> ### Cuts useless information from stacktrace @param {String} raw stacktrace @return {String} ### # Try to remove non-async stacktrace asyncSeparator = '==== async task ====' asyncTaskPos = stack.indexOf(asyncSeparator) if stack and asyncTaskPos != -1 stack = stack.substring(asyncTaskPos + asyncSeparator.length) # Remove stacktrace higher than spec, and deeper than stof.webdriver preparedStack = stack.substring(0, stack.indexOf('\n') + 1) write = false for num, line of stack.split(/\n/) preparedStack += line + '\n' if write write = true if line.match('stof') break if line.match(/specs/) preparedStack self = ### Public methods ### getRootBrowser: -> ### Gets and returns root browser's instance. Root browser always exists. @return {Browser} — main browser instance ### _browserInstances[0] newWindow: (capabilities) -> ### Returns new Browser instance. It will have independent driver (and window). It is possible to pass capabilities as an hash-object to explicitly define browser or platform, which new browser windows should be in. @param {Object} Hash table with fields [browser, platform] @return {Browser} ### browserInstance = new Browser if capabilities desiredCapabilities = _.merge(browserInstance.getDesiredCapabilities(), capabilities) browserInstance.setDesiredCapabilities(desiredCapabilities) self.addBrowserInstance(browserInstance) browserInstance addBrowserInstance: (browserInstance) -> ### Adds browser to list of active windows. This is needed to be able to take screenshots, stores logs and quit from all windows, used in a test @param {Browser} browser instance to add ### key = _browserInstances.length _browserInstances[key] = browserInstance browserInstance.browserInstanceKey = key removeBrowserInstance: (key) -> ### Removes browser instance from instance array. Root browser (with key = 0) instance cannot be removed @param {int} browser instance key ### delete _browserInstances[key] if key != 0 resolvePath: (directory, subFolderInBundle = '') -> ### Resolves pseudo path to product @param {String} pseudo-path to the class in BaseFactory.require() notation @param {String} Additional path inside the bundle @return {String} ### {bundle, relativePath} = _pathResolver.parsePathRaw(directory, _currentRelativePath) subFolderInBundle = subFolderInBundle.trimRight('/') + '/' if subFolderInBundle "#{_currentAbsolutePath}/#{bundle}/#{subFolderInBundle}#{relativePath}" loadFile: (directory, subFolderInBundle = '', strict = true) -> ### Requires file in path @param {String} pseudo-path to the class in BaseFactory.require() notation @param {String} Additional path inside the bundle @return {object} ### directory = self.resolvePath(directory, subFolderInBundle) if strict or fs.existsSync("#{directory}.js") require(directory) else {} getConfigValue: (propertyPath) -> ### Returns config property @param {String} Point separated path to property. For example, stof.browser will return config[stof][browser] property value @return {String|object} Property value ### _loadConfig() if not _config? directory = propertyPath.split(/\./) value = _config for part in directory value = value[part] break if not value value defineContext: (filename, updateTestName = true) -> ### Defines current executed file path names. It determines absolute and relative path to bundle. @param {String} Current executed file name. Usually __filename value ### _currentContext = filename directory = path.dirname(filename) pathParts = directory.split(/(?:specs|page-objects|helpers)/) directory = pathParts[0] if pathParts.length == 2 testRootDir = _parseTestRootDir() ### coffee script test spec can be specified. But test objects and helpers must be included from target dir. Let's handle it ### targetDir = _parseTargetDir() splitDir = testRootDir splitDir = splitDir.replace(targetDir + '/', '') if splitDir.indexOf(targetDir) == 0 pathParts = directory.split(new RegExp("(?:#{targetDir}/)?#{splitDir}")) _currentAbsolutePath = "#{pathParts[0]}/#{testRootDir}" _currentAbsolutePath = _currentAbsolutePath.trimRight('/') _currentRelativePath = pathParts[1] if updateTestName filename = path.basename(filename, '.js') _testName = filename self.defineUncaughtExceptionHandler() getCurrentContext: -> ### Returns current context, i.e. current test file name ### _currentContext closeAllWindows: -> ### Closes all browser windows attached to Stof instance ### promises = [] for key, browser of _browserInstances if browser? promises.push(browser.quit()) else throw e webdriver.promise.all(promises) defineUncaughtExceptionHandler: () -> ### Sets global uncaughtException handler @param {String} Current executed file name. Usually __filename value ### return if _uncaughtExceptionSet _uncaughtExceptionSet = true # Uncaught exception handler uncaughtException = (e) => webdriver.promise.controlFlow().removeListener('uncaughtException', uncaughtException) _uncaughtExceptionSet = false fs.mkdirpSync(getConfigValue('stof.screenshotsDir')) fs.mkdirpSync(getConfigValue('stof.logsDir')) e.stack = _prepareStackTrace(e.stack) promises = [] for key, browser of _browserInstances if browser? screenshotKey = browser.browserInstanceKey filename = _testName + screenshotKey promises.push(browser.takeScreenshot(filename)) promises.push(browser.getAndSaveLogs('browser.txt')) promises.push(browser.dumpDomContents("#{filename}_dom")) promises.push(browser.quit()) else throw e webdriver.promise.all(promises).then -> throw e # Bind uncaught exception handler webdriver.promise.controlFlow().on('uncaughtException', uncaughtException) done: -> ### Returns last queued promise in selenium webdriver control flow @return {webdriver.Promise} ### @getRootBrowser().done() promise: -> ### Returns webdriver's promise library Sample usage (written on CoffeeScript) deferred = stof.promise().defer() doSomeThing -> deferred.fulfill() deferred.promise ### webdriver.promise self.newWindow() module.exports = self
93312
webdriver = require './webdriver' PathResolver = require './utils/PathResolver' fs = require 'fs.extra' path = require 'path' _ = require 'lodash' Browser = require './Browser' # Classes for inheriting in concrete test's implementation PageObject = require './page-objects/PageObject' Form = require './page-objects/Form' TestHelper = require './helpers/TestHelper' ### Private properties and methods ### _config = null _testName = null _currentContext = null _currentAbsolutePath = null _currentRelativePath = null _uncaughtExceptionSet = false _browserInstances = [] _pathResolver = new PathResolver _loadConfig = -> ### Reads test config @return {object} ### stofConfig = require('./config') defaultConfig = self.loadFile('/config//defaultConfig', '', false) _.merge(stofConfig, defaultConfig) _config = self.loadFile('/config//config', '', false) _config = _.merge(stofConfig, _config) _config _parseTestRootDir = -> ### Finds test root dir path in command line arguments and process environment @return {String} ### testRootDir = null process.argv.forEach (value) -> testRootDir = value.substr('--stof-root-dir='.length) if value.indexOf('--stof-root-dir=') == 0 return testRootDir if testRootDir? if not process.env.STOF_ROOT_DIR? throw new Error('Please specify command line argument --stof-root-dir or environment variable STOF_ROOT_DIR') process.env.STOF_ROOT_DIR _parseTargetDir = -> ### Finds test target dir path in command line arguments and process environment. By default returns 'target' @return {String} ### testTargetDir = null process.argv.forEach (value) -> testTargetDir = value.substr('--stof-target-dir='.length) if value.indexOf('--stof-target-dir=') == 0 return testTargetDir if testTargetDir? return process.env.STOF_TARGET_DIR if process.env.STOF_TARGET_DIR? 'target' _prepareStackTrace = (stack) -> ### Cuts useless information from stacktrace @param {String} raw stacktrace @return {String} ### # Try to remove non-async stacktrace asyncSeparator = '==== async task ====' asyncTaskPos = stack.indexOf(asyncSeparator) if stack and asyncTaskPos != -1 stack = stack.substring(asyncTaskPos + asyncSeparator.length) # Remove stacktrace higher than spec, and deeper than stof.webdriver preparedStack = stack.substring(0, stack.indexOf('\n') + 1) write = false for num, line of stack.split(/\n/) preparedStack += line + '\n' if write write = true if line.match('stof') break if line.match(/specs/) preparedStack self = ### Public methods ### getRootBrowser: -> ### Gets and returns root browser's instance. Root browser always exists. @return {Browser} — main browser instance ### _browserInstances[0] newWindow: (capabilities) -> ### Returns new Browser instance. It will have independent driver (and window). It is possible to pass capabilities as an hash-object to explicitly define browser or platform, which new browser windows should be in. @param {Object} Hash table with fields [browser, platform] @return {Browser} ### browserInstance = new Browser if capabilities desiredCapabilities = _.merge(browserInstance.getDesiredCapabilities(), capabilities) browserInstance.setDesiredCapabilities(desiredCapabilities) self.addBrowserInstance(browserInstance) browserInstance addBrowserInstance: (browserInstance) -> ### Adds browser to list of active windows. This is needed to be able to take screenshots, stores logs and quit from all windows, used in a test @param {Browser} browser instance to add ### key = _browserInstances.<KEY> _browserInstances[key] = browserInstance browserInstance.browserInstanceKey = key removeBrowserInstance: (key) -> ### Removes browser instance from instance array. Root browser (with key = 0) instance cannot be removed @param {int} browser instance key ### delete _browserInstances[key] if key != 0 resolvePath: (directory, subFolderInBundle = '') -> ### Resolves pseudo path to product @param {String} pseudo-path to the class in BaseFactory.require() notation @param {String} Additional path inside the bundle @return {String} ### {bundle, relativePath} = _pathResolver.parsePathRaw(directory, _currentRelativePath) subFolderInBundle = subFolderInBundle.trimRight('/') + '/' if subFolderInBundle "#{_currentAbsolutePath}/#{bundle}/#{subFolderInBundle}#{relativePath}" loadFile: (directory, subFolderInBundle = '', strict = true) -> ### Requires file in path @param {String} pseudo-path to the class in BaseFactory.require() notation @param {String} Additional path inside the bundle @return {object} ### directory = self.resolvePath(directory, subFolderInBundle) if strict or fs.existsSync("#{directory}.js") require(directory) else {} getConfigValue: (propertyPath) -> ### Returns config property @param {String} Point separated path to property. For example, stof.browser will return config[stof][browser] property value @return {String|object} Property value ### _loadConfig() if not _config? directory = propertyPath.split(/\./) value = _config for part in directory value = value[part] break if not value value defineContext: (filename, updateTestName = true) -> ### Defines current executed file path names. It determines absolute and relative path to bundle. @param {String} Current executed file name. Usually __filename value ### _currentContext = filename directory = path.dirname(filename) pathParts = directory.split(/(?:specs|page-objects|helpers)/) directory = pathParts[0] if pathParts.length == 2 testRootDir = _parseTestRootDir() ### coffee script test spec can be specified. But test objects and helpers must be included from target dir. Let's handle it ### targetDir = _parseTargetDir() splitDir = testRootDir splitDir = splitDir.replace(targetDir + '/', '') if splitDir.indexOf(targetDir) == 0 pathParts = directory.split(new RegExp("(?:#{targetDir}/)?#{splitDir}")) _currentAbsolutePath = "#{pathParts[0]}/#{testRootDir}" _currentAbsolutePath = _currentAbsolutePath.trimRight('/') _currentRelativePath = pathParts[1] if updateTestName filename = path.basename(filename, '.js') _testName = filename self.defineUncaughtExceptionHandler() getCurrentContext: -> ### Returns current context, i.e. current test file name ### _currentContext closeAllWindows: -> ### Closes all browser windows attached to Stof instance ### promises = [] for key, browser of _browserInstances if browser? promises.push(browser.quit()) else throw e webdriver.promise.all(promises) defineUncaughtExceptionHandler: () -> ### Sets global uncaughtException handler @param {String} Current executed file name. Usually __filename value ### return if _uncaughtExceptionSet _uncaughtExceptionSet = true # Uncaught exception handler uncaughtException = (e) => webdriver.promise.controlFlow().removeListener('uncaughtException', uncaughtException) _uncaughtExceptionSet = false fs.mkdirpSync(getConfigValue('stof.screenshotsDir')) fs.mkdirpSync(getConfigValue('stof.logsDir')) e.stack = _prepareStackTrace(e.stack) promises = [] for key, browser of _browserInstances if browser? screenshotKey = browser.browserInstanceKey filename = _testName + screenshotKey promises.push(browser.takeScreenshot(filename)) promises.push(browser.getAndSaveLogs('browser.txt')) promises.push(browser.dumpDomContents("#{filename}_dom")) promises.push(browser.quit()) else throw e webdriver.promise.all(promises).then -> throw e # Bind uncaught exception handler webdriver.promise.controlFlow().on('uncaughtException', uncaughtException) done: -> ### Returns last queued promise in selenium webdriver control flow @return {webdriver.Promise} ### @getRootBrowser().done() promise: -> ### Returns webdriver's promise library Sample usage (written on CoffeeScript) deferred = stof.promise().defer() doSomeThing -> deferred.fulfill() deferred.promise ### webdriver.promise self.newWindow() module.exports = self
true
webdriver = require './webdriver' PathResolver = require './utils/PathResolver' fs = require 'fs.extra' path = require 'path' _ = require 'lodash' Browser = require './Browser' # Classes for inheriting in concrete test's implementation PageObject = require './page-objects/PageObject' Form = require './page-objects/Form' TestHelper = require './helpers/TestHelper' ### Private properties and methods ### _config = null _testName = null _currentContext = null _currentAbsolutePath = null _currentRelativePath = null _uncaughtExceptionSet = false _browserInstances = [] _pathResolver = new PathResolver _loadConfig = -> ### Reads test config @return {object} ### stofConfig = require('./config') defaultConfig = self.loadFile('/config//defaultConfig', '', false) _.merge(stofConfig, defaultConfig) _config = self.loadFile('/config//config', '', false) _config = _.merge(stofConfig, _config) _config _parseTestRootDir = -> ### Finds test root dir path in command line arguments and process environment @return {String} ### testRootDir = null process.argv.forEach (value) -> testRootDir = value.substr('--stof-root-dir='.length) if value.indexOf('--stof-root-dir=') == 0 return testRootDir if testRootDir? if not process.env.STOF_ROOT_DIR? throw new Error('Please specify command line argument --stof-root-dir or environment variable STOF_ROOT_DIR') process.env.STOF_ROOT_DIR _parseTargetDir = -> ### Finds test target dir path in command line arguments and process environment. By default returns 'target' @return {String} ### testTargetDir = null process.argv.forEach (value) -> testTargetDir = value.substr('--stof-target-dir='.length) if value.indexOf('--stof-target-dir=') == 0 return testTargetDir if testTargetDir? return process.env.STOF_TARGET_DIR if process.env.STOF_TARGET_DIR? 'target' _prepareStackTrace = (stack) -> ### Cuts useless information from stacktrace @param {String} raw stacktrace @return {String} ### # Try to remove non-async stacktrace asyncSeparator = '==== async task ====' asyncTaskPos = stack.indexOf(asyncSeparator) if stack and asyncTaskPos != -1 stack = stack.substring(asyncTaskPos + asyncSeparator.length) # Remove stacktrace higher than spec, and deeper than stof.webdriver preparedStack = stack.substring(0, stack.indexOf('\n') + 1) write = false for num, line of stack.split(/\n/) preparedStack += line + '\n' if write write = true if line.match('stof') break if line.match(/specs/) preparedStack self = ### Public methods ### getRootBrowser: -> ### Gets and returns root browser's instance. Root browser always exists. @return {Browser} — main browser instance ### _browserInstances[0] newWindow: (capabilities) -> ### Returns new Browser instance. It will have independent driver (and window). It is possible to pass capabilities as an hash-object to explicitly define browser or platform, which new browser windows should be in. @param {Object} Hash table with fields [browser, platform] @return {Browser} ### browserInstance = new Browser if capabilities desiredCapabilities = _.merge(browserInstance.getDesiredCapabilities(), capabilities) browserInstance.setDesiredCapabilities(desiredCapabilities) self.addBrowserInstance(browserInstance) browserInstance addBrowserInstance: (browserInstance) -> ### Adds browser to list of active windows. This is needed to be able to take screenshots, stores logs and quit from all windows, used in a test @param {Browser} browser instance to add ### key = _browserInstances.PI:KEY:<KEY>END_PI _browserInstances[key] = browserInstance browserInstance.browserInstanceKey = key removeBrowserInstance: (key) -> ### Removes browser instance from instance array. Root browser (with key = 0) instance cannot be removed @param {int} browser instance key ### delete _browserInstances[key] if key != 0 resolvePath: (directory, subFolderInBundle = '') -> ### Resolves pseudo path to product @param {String} pseudo-path to the class in BaseFactory.require() notation @param {String} Additional path inside the bundle @return {String} ### {bundle, relativePath} = _pathResolver.parsePathRaw(directory, _currentRelativePath) subFolderInBundle = subFolderInBundle.trimRight('/') + '/' if subFolderInBundle "#{_currentAbsolutePath}/#{bundle}/#{subFolderInBundle}#{relativePath}" loadFile: (directory, subFolderInBundle = '', strict = true) -> ### Requires file in path @param {String} pseudo-path to the class in BaseFactory.require() notation @param {String} Additional path inside the bundle @return {object} ### directory = self.resolvePath(directory, subFolderInBundle) if strict or fs.existsSync("#{directory}.js") require(directory) else {} getConfigValue: (propertyPath) -> ### Returns config property @param {String} Point separated path to property. For example, stof.browser will return config[stof][browser] property value @return {String|object} Property value ### _loadConfig() if not _config? directory = propertyPath.split(/\./) value = _config for part in directory value = value[part] break if not value value defineContext: (filename, updateTestName = true) -> ### Defines current executed file path names. It determines absolute and relative path to bundle. @param {String} Current executed file name. Usually __filename value ### _currentContext = filename directory = path.dirname(filename) pathParts = directory.split(/(?:specs|page-objects|helpers)/) directory = pathParts[0] if pathParts.length == 2 testRootDir = _parseTestRootDir() ### coffee script test spec can be specified. But test objects and helpers must be included from target dir. Let's handle it ### targetDir = _parseTargetDir() splitDir = testRootDir splitDir = splitDir.replace(targetDir + '/', '') if splitDir.indexOf(targetDir) == 0 pathParts = directory.split(new RegExp("(?:#{targetDir}/)?#{splitDir}")) _currentAbsolutePath = "#{pathParts[0]}/#{testRootDir}" _currentAbsolutePath = _currentAbsolutePath.trimRight('/') _currentRelativePath = pathParts[1] if updateTestName filename = path.basename(filename, '.js') _testName = filename self.defineUncaughtExceptionHandler() getCurrentContext: -> ### Returns current context, i.e. current test file name ### _currentContext closeAllWindows: -> ### Closes all browser windows attached to Stof instance ### promises = [] for key, browser of _browserInstances if browser? promises.push(browser.quit()) else throw e webdriver.promise.all(promises) defineUncaughtExceptionHandler: () -> ### Sets global uncaughtException handler @param {String} Current executed file name. Usually __filename value ### return if _uncaughtExceptionSet _uncaughtExceptionSet = true # Uncaught exception handler uncaughtException = (e) => webdriver.promise.controlFlow().removeListener('uncaughtException', uncaughtException) _uncaughtExceptionSet = false fs.mkdirpSync(getConfigValue('stof.screenshotsDir')) fs.mkdirpSync(getConfigValue('stof.logsDir')) e.stack = _prepareStackTrace(e.stack) promises = [] for key, browser of _browserInstances if browser? screenshotKey = browser.browserInstanceKey filename = _testName + screenshotKey promises.push(browser.takeScreenshot(filename)) promises.push(browser.getAndSaveLogs('browser.txt')) promises.push(browser.dumpDomContents("#{filename}_dom")) promises.push(browser.quit()) else throw e webdriver.promise.all(promises).then -> throw e # Bind uncaught exception handler webdriver.promise.controlFlow().on('uncaughtException', uncaughtException) done: -> ### Returns last queued promise in selenium webdriver control flow @return {webdriver.Promise} ### @getRootBrowser().done() promise: -> ### Returns webdriver's promise library Sample usage (written on CoffeeScript) deferred = stof.promise().defer() doSomeThing -> deferred.fulfill() deferred.promise ### webdriver.promise self.newWindow() module.exports = self
[ { "context": "gree vertically.\n#\n# @license Apache 2.0\n# @author MixFlow\n# @date 2017-08\n###\n\nwindow.threePanorama = (sett", "end": 187, "score": 0.9960964918136597, "start": 180, "tag": "USERNAME", "value": "MixFlow" }, { "context": "YyIgZD0iTTEyNSAxODAuODVsLTEwNSAxMDVWMjAzLjRIMFYzMjBoMTE2LjZ2LTIwSDM0LjE0bDEwNS4wMS0xMDV6TTIwMy40IDB2MjBoODIuNDZMMTgwLjg1IDEyNWwxNC4xNCAxNC4xNUwzMDAgMzQuMTR2ODIuNDZoMjBWMHoiLz4gIDxwYXRoIGZpbGw9IiNGRkYiIGQ9Ik0yMCAzNC4xNGwxMDUgMTA1IDE0LjE1LTE0LjEzTDM0LjE1IDIwaDgyLjQ1VjBIMHYxMTYuNmgyMHpNMzAwIDI4NS44NkwxOTUgMTgwLjg1bC0xNC4xNSAxNC4xNEwyODUuODYgMzAwSDIwMy40djIwSDMyMFYyMDMuNGgtMjB6Ii8+PC9zdmc+\"\n fullscreenUtil.css iconStyle\n\n ful", "end": 16585, "score": 0.9995253682136536, "start": 16246, "tag": "KEY", "value": "BoMTE2LjZ2LTIwSDM0LjE0bDEwNS4wMS0xMDV6TTIwMy40IDB2MjBoODIuNDZMMTgwLjg1IDEyNWwxNC4xNCAxNC4xNUwzMDAgMzQuMTR2ODIuNDZoMjBWMHoiLz4gIDxwYXRoIGZpbGw9IiNGRkYiIGQ9Ik0yMCAzNC4xNGwxMDUgMTA1IDE0LjE1LTE0LjEzTDM0LjE1IDIwaDgyLjQ1VjBIMHYxMTYuNmgyMHpNMzAwIDI4NS44NkwxOTUgMTgwLjg1bC0xNC4xNSAxNC4xNEwyODUuODYgMzAwSDIwMy40djIwSDMyMFYyMDMuNGgtMjB6Ii8+PC9zdmc+\"" }, { "context": " setting.src = \"data:image/svg+xml;base64,PHN2ZyBiYXNlUHJvZmlsZT0iZnVsbCIgd2lkdGg9IjEwMCIgaGVpZ", "end": 17676, "score": 0.5733682513237, "start": 17675, "tag": "KEY", "value": "N" }, { "context": "+xml;base64,PHN2ZyBiYXNlUHJvZmlsZT0iZnVsbCIgd2lkdGg9IjEwMCIgaGVpZ2h0PSIxMDAiIHhtbG5zPSJodHRwOi8vd3d3L", "end": 17712, "score": 0.6335756182670593, "start": 17711, "tag": "KEY", "value": "g" }, { "context": ";base64,PHN2ZyBiYXNlUHJvZmlsZT0iZnVsbCIgd2lkdGg9IjEwMCIgaGVpZ2h0PSIxMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMD", "end": 17725, "score": 0.6299461126327515, "start": 17715, "tag": "KEY", "value": "EwMCIgaGVp" }, { "context": "2ZyBiYXNlUHJvZmlsZT0iZnVsbCIgd2lkdGg9IjEwMCIgaGVpZ2h0PSIxMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+ICA8cGF0aCBkPSJNNDAgODQuNThsNC", "end": 17765, "score": 0.6916758418083191, "start": 17726, "tag": "KEY", "value": "2h0PSIxMDAiIHhtbG5zPSJodHRwOi8vd3d3Lncz" }, { "context": "MCIgaGVpZ2h0PSIxMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+ICA8cGF0aCBkPSJNNDAgODQuNThsNCAxMy", "end": 17769, "score": 0.6999855637550354, "start": 17767, "tag": "KEY", "value": "9y" }, { "context": "aGVpZ2h0PSIxMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+ICA8cGF0aCBkPSJNNDAgODQuNThsNCAxMy4wN", "end": 17772, "score": 0.5738140344619751, "start": 17771, "tag": "KEY", "value": "8" }, { "context": "VpZ2h0PSIxMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+ICA8cGF0aCBkPSJNNDAgODQuNThsNCAxMy4wNGgxMmw0LTEzLjA0YTMwIDMwIDAgMCAwIDE0Ljk1LTguNjNsMTMuMyAzLjA2IDYtMTAuNC05LjMtOS45OGEzMCAzMCAwIDAgMCAwLTE3LjI2bDkuMy05Ljk5LTYtMTAuMzktMTMuMyAzLjA2QTMwIDMwIDAgMCAwIDYwIDE1LjQyTDU2IDIuMzhINDRsLTQgMTMuMDRhMzAgMzAgMCAwIDAtMTQuOTUgOC42M2wtMTMuMy0zLjA2LTYgMTAuNCA5LjMgOS45OGEzMCAzMCAwIDAgMCAwIDE3LjI2bC05LjMgOS45OSA2IDEwLjM5IDEzLjMtMy4wNkEzMCAzMCAwIDAgMCA0MCA4NC41OHpNMzUgNTBhMTUgMTUgMCAxIDEgMzAgMCAxNSAxNSAwIDEgMS0zMCAwIiBmaWxsPSIjZmZmIiBzdHJva2U9IiM1YTljZmMiIHN0cm9rZS13aWR0aD0iNSIvPjwvc3ZnPg==\";\n settingUtil = util(setting)\n ", "end": 18310, "score": 0.9996980428695679, "start": 17773, "tag": "KEY", "value": "MDAwL3N2ZyI+ICA8cGF0aCBkPSJNNDAgODQuNThsNCAxMy4wNGgxMmw0LTEzLjA0YTMwIDMwIDAgMCAwIDE0Ljk1LTguNjNsMTMuMyAzLjA2IDYtMTAuNC05LjMtOS45OGEzMCAzMCAwIDAgMCAwLTE3LjI2bDkuMy05Ljk5LTYtMTAuMzktMTMuMyAzLjA2QTMwIDMwIDAgMCAwIDYwIDE1LjQyTDU2IDIuMzhINDRsLTQgMTMuMDRhMzAgMzAgMCAwIDAtMTQuOTUgOC42M2wtMTMuMy0zLjA2LTYgMTAuNCA5LjMgOS45OGEzMCAzMCAwIDAgMCAwIDE3LjI2bC05LjMgOS45OSA2IDEwLjM5IDEzLjMtMy4wNkEzMCAzMCAwIDAgMCA0MCA4NC41OHpNMzUgNTBhMTUgMTUgMCAxIDEgMzAgMCAxNSAxNSAwIDEgMS0zMCAwIiBmaWxsPSIjZmZmIiBzdHJva2U9IiM1YTljZmMiIHN0cm9rZS13aWR0aD0iNSIvPjwvc3ZnPg==\"" } ]
js/3panorama.coffee
mixflow/3panorama
1
### # A panorama viewer base on three.js. # Panarama is a type of image which can be watched in 360 degree horizonally and 180 degree vertically. # # @license Apache 2.0 # @author MixFlow # @date 2017-08 ### window.threePanorama = (settings) -> defaultSettings = container: document.body image: undefined fov: 65 # camera fov(field of view) canUseWindowSize: false # If set false(defalut), Camera ratio and render size (Viewer size) are base on container size(fill). If set true, use window innerWidth and innerHeight. ### If width or height is missing(0), use this alternate ratio to calculate the missing size. If you want set specific ratio, please set your container size(width / height = ratio) and `canUseWindowSize` is false ### alternateRatio: 16/9 ### recommend to set `true`, if you don't set container width and height. Prevent the size of the container and renderer growing when window resizes(fire `onWindowResize` event). Record width and height data, next time the container width is some record again, use the correlative height. ### canKeepInitalSize: true enableDragNewImage: true # TODO [Not implemented] can drag image file which will be show as the new panorama to viewer(container) # [controls] # mouse mouseSensitivity: 0.1 # the sensitivity of mouse when is drag to control the camera. # device orientation enableDeviceOrientation: true # when device orientation(if the device has the sensor) is enabled, user turns around device to change the direction that user look at. # [end][controls] lonlat: [0, 0] # the initialize position that camera look at. sphere: # Default value works well. changing is not necessary. radius: 500 # the radius of the sphere whose texture is the panorama. debug: imageLoadProgress: false # !! not work for now!! lonlat: false # output the lon and lat positions. when user is controling. cameraSize: false # output camera size when it is changed. settings = settings || {} # put default setting into settings. for key,val of defaultSettings if key not of settings settings[key] = val # must provide image if not settings.image? throw { type: "No image provided." msg: "Please fill panorama image path(string) in the parameter 'image' of settings" } # set container dom. if typeof settings.container is "string" # only select first one container = document.querySelectorAll(settings.container)[0] else container = settings.container # the longitude and latitude position which are mapped to the sphere lon = settings.lonlat[0] lat = settings.lonlat[1] width = 0 height = 0 # size of render records = {} # the camera size records getViewerSize = (canKeepInitalSize = settings.canKeepInitalSize)-> if not settings.canUseWindowSize rect = container.getBoundingClientRect() width = rect.width height = rect.height else # use the browser window size width = window.innerWidth height = window.innerHeight if not width and not height throw { type: "Lack of Viewer Size.", msg: "Viewer width and height are both missing(value is 0), Please check the container size(width and height > 0). Or use window size to set Viewer size by setting `canUseWindowSize` as `true`" } else if not height height = width / settings.alternateRatio else if not width # height is not zero width = height * settings.alternateRatio if canKeepInitalSize is true if width not of records # record width height, may use later records[width] = height else # get older data height = records[width] if settings.debug.cameraSize console.log("current camera size:", width, height) return {width, height} # get init size getViewerSize() util = do -> handler = addClass: (domel, clazz) -> domel.className += " " + clazz removeClass: (domel, clazz) -> domel.className = domel.className.replace(new RegExp('(\\s|^)' + clazz + '(\\s|$)'), '') getAttribute: (domel, attr) -> return domel.getAttribute(attr) setAttributes: (domel, options) -> domel.setAttribute(key, val) for key,val of options css: (domel, options) -> for property, value of options domel.style[property] = value on: (domel, event, callback, useCapture=false) -> evts = event.split(" ") domel.addEventListener(evt, callback, useCapture) for evt in evts off: (domel, eventsString, callback, useCapture=false) -> evts = eventsString.split(" ") domel.removeEventListener(evt, callback, useCapture) for evt in evts wrapperGenerator = (wrapper)-> methodHelper = (fn) -> # avoid create function in the loop return (args...) -> # the real method of util fn(wrapper.domel, args...) wrapper # return wrapper itself to call continually later for method, fn of handler # transfer the handler methods to the wrapper methods wrapper[method] = methodHelper(fn) wrapper # the generated wrapper return (el)-> # if el? wrapper = domel: el # set DOM element wrapperGenerator(wrapper) else return handler ### # Initiate the three.js components. # Steps: # create a sphere and put panorama on faces inside # create a camera, put it on origin which is also the center of sphere # bind some control: # 1. mouse or touch or device orient to control the rotation of camera. # render the scene ### init = -> # noraml camera (Perspective). (fov, camera screen ratio(width / height), near clip distance, far clip dist) # TODO ? take 'ratio' param from setting? camera = new THREE.PerspectiveCamera(settings.fov, width / height, 1, 1100 ) # the camera lookAt target whose position in 3D space for the camera to point towards # TODO the init camera target position # camera.lookAt(new THREE.Vector3(0, 0, 0)) camera.target = new THREE.Vector3( 0, 0, 0 ) # create the sphere mesh, put panorama on it. # SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) geometry = new THREE.SphereBufferGeometry(settings.sphere.radius, 50, 50) geometry.scale(-1, 1, 1) # filp the face of sphere, because the material(texture) should be on inside. # !!onProgress not work now. the part is comment out in the three.js(r87) ImageLoad source code # loadingManager = new THREE.LoadingManager() # loadingManager.onProgress = (url, loaded, total)-> # # onProgress, Will be called while load progresses, he argument will be the XMLHttpRequest instance, which contains .total and .loaded bytes. # precent = loaded / total * 100 # # if settings.debug.imageLoadProgress # console.log("Image loaded: ", Math.round(precent, 2), "%") texture = new THREE.TextureLoader().load(settings.image) material = new THREE.MeshBasicMaterial map: texture mesh = new THREE.Mesh(geometry, material) # create a scene and put the sphere in the scene. scene = new THREE.Scene() scene.add(mesh) # create renderer and attach the result(renderer dom) in container renderer = initRenderer() container.appendChild( renderer.domElement ) # bind mouse event to control the camera bindMouseTouchControl(renderer.domElement) # control bar initControls(container) # resize the camera and renderer when window size changed. util(window).on("resize", do -> # prevent fire resize multi times. only need call the function when resize finished resizeTimer = undefined return (event) -> clearTimeout resizeTimer resizeTimer = setTimeout( -> onWindowResize(event, false) , 100) ,false) return {camera, mesh, scene, renderer} # [end] init # the components initiate functions. initRenderer = -> renderer = new THREE.WebGLRenderer() renderer.setPixelRatio( window.devicePixelRatio ) renderer.setSize(width, height) return renderer # [end] init_renderer bindMouseTouchControl = (target) -> # the dom target, which the mouse events are trigged on. controlStartX = 0 controlStartY = 0 controlStartLon = 0 controlStartLat = 0 isUserControling = false controlStartHelper = (isTouch) -> # Base on `isTouch`, generate touch(true) or mouse(otherwise) version event handler. return (event) -> event.preventDefault() isUserControling = true controlStartX = if not isTouch then event.clientX else event.changedTouches[0].clientX controlStartY = if not isTouch then event.clientY else event.changedTouches[0].clientY controlStartLon = lon controlStartLat = lat controlMoveHelper = (isTouch) -> return (event) -> # mouse move over, or touch move over if isUserControling is true x = if not isTouch then event.clientX else event.changedTouches[0].clientX y = if not isTouch then event.clientY else event.changedTouches[0].clientY sensitivity = settings.mouseSensitivity # TODO ? touch sensitivity? lon = (controlStartX - x) * sensitivity + controlStartLon lat = (y - controlStartY) * sensitivity + controlStartLat if settings.debug.lonlat console.log "longitude: ", lon, "latitude: ", lat controlEnd = (event) -> # release the mouse key. isUserControling = false mouseDownHandle = controlStartHelper(false) mouseMoveHandle = controlMoveHelper(false) mouseUpHandle = controlEnd targetUtil = util(target) # bind mouse event targetUtil.on 'mousedown', mouseDownHandle, false .on 'mousemove', mouseMoveHandle, false .on 'mouseup', mouseUpHandle, false touchStartHandle = controlStartHelper(true) touchMoveHandle = controlMoveHelper(true) touchEndHandle = controlEnd # touch event targetUtil.on "touchstart", touchStartHandle, false .on "touchmove", touchMoveHandle, false .on "touchend", touchEndHandle, false getFullscreenElementHelper = (container) -> if not container? container = document return -> container.fullscreenElement or container.webkitFullscreenElement or container.mozFullScreenElement or container.msFullscreenElement getFullscreenElement = getFullscreenElementHelper() requestAndExitFullscreenHelper = -> ### The helper function to create the `exitFullscreen` and `requestFullscreen` callback function. There is no need for checking different broswer methods when the fullscreen is toggled every time. ### if document.exitFullscreen ### `exitFn = document.exitFullscreen` not work alternate way: `exitFn = document.exitFullscreen.bind(document)` (es5) ### exitFn = -> document.exitFullscreen() requestFn = (target) -> target.requestFullscreen() else if document.msExitFullscreen exitFn = -> document.msExitFullscreen() requestFn = (target) -> target.msRequestFullscreen() else if document.mozCancelFullScreen exitFn = -> document.mozCancelFullScreen() requestFn = (target) -> target.mozRequestFullscreen() else if document.webkitExitFullscreen exitFn = -> document.webkitExitFullscreen() requestFn = (target) -> target.webkitRequestFullscreen() else exitFn = -> console.log("The bowser doesn't support fullscreen mode") # Don't support fullscreen requestFn = exitFn return { request: requestFn exit: exitFn } toggleTargetFullscreen = do -> {request, exit} = requestAndExitFullscreenHelper() return (target) -> ### If no fullscreen element, the `target` enters fullscree. Otherwise fullscreen element exit fullscreen. Both trigge the `fullscreenchange` event. ### if getFullscreenElement() # Before fullscreen state, exit fullscreen now. # call the `exit` helper function exit() else # enter fullscreen now. # the `request` helper function which requests the fullscreen. request(target) changeFullscreenState = (target) -> ### the actual behavior when fullscreen state is changed. ### # TODO [important] make a wrapper for styling?? fullscreenElement = getFullscreenElement() clazz = "fullscreen-mode" targetUtil = util(target) if (fullscreenElement?) # fullscreen # target.className += " " + clazz targetUtil.addClass(clazz) target.style.width = "100vw" target.style.height = "100vh" target.style["max-width"] = "unset" target.style["max-height"] = "unset" else # remove class name # TODO clean up. make a helper to handle class name. # target.className = target.className.replace(new RegExp('(\\s|^)' + clazz + '(\\s|$)'), '') targetUtil.removeClass(clazz) target.style.width = null target.style.height = null target.style["max-width"] = null target.style["max-height"] = null # [don't uncomment] enter or exit fullscreen will toggle `resize` event of `window`. no need to call the function to resize again. # reset 3panorama camera and renderer(cavans) size # onWindowResize(undefined, false) initControls = (container) -> controls = document.createElement("div") controls.className = "3panorama-controls" # postion: above the container controls.style.position = "absolute" controls.style.bottom = 0 controls.style.width = "100%" controls.style.height = "3.5em" controls.style["min-height"] = "32px" iconStyle = {height: '75%', 'min-height': '24px', padding: '0.3em'} # fullscreen button fullscreen = document.createElement("img") fullscreenUtil = util(fullscreen) # the converted base64 url based on svg file (fullscreen-icon-opt.svg) fullscreen.src = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzMjAgMzIwIiB3aWR0aD0iMjQiIGhlaWdodD0iMjQiPiAgPHBhdGggZmlsbD0iIzVhOWNmYyIgZD0iTTEyNSAxODAuODVsLTEwNSAxMDVWMjAzLjRIMFYzMjBoMTE2LjZ2LTIwSDM0LjE0bDEwNS4wMS0xMDV6TTIwMy40IDB2MjBoODIuNDZMMTgwLjg1IDEyNWwxNC4xNCAxNC4xNUwzMDAgMzQuMTR2ODIuNDZoMjBWMHoiLz4gIDxwYXRoIGZpbGw9IiNGRkYiIGQ9Ik0yMCAzNC4xNGwxMDUgMTA1IDE0LjE1LTE0LjEzTDM0LjE1IDIwaDgyLjQ1VjBIMHYxMTYuNmgyMHpNMzAwIDI4NS44NkwxOTUgMTgwLjg1bC0xNC4xNSAxNC4xNEwyODUuODYgMzAwSDIwMy40djIwSDMyMFYyMDMuNGgtMjB6Ii8+PC9zdmc+" fullscreenUtil.css iconStyle fullscreenUtil.on("click", -> toggleTargetFullscreen(container) , false) util(document).on "webkitfullscreenchange mozfullscreenchange fullscreenchange msfullscreenchange", -> changeFullscreenState(container) controls.appendChild(fullscreen) # setting button {_, settingPanel} = do -> # settings on the pannel settingPanel = document.createElement('div') panelUtil = util(settingPanel) panelUtil.addClass('3panorama-setting-pannel') panelUtil.css 'visibility': 'hidden' display: 'inline' position: 'relative' background: '#FFF' bottom: '100%' left: '-24px' padding: '0.4em 0.8em' # setting icon buttion setting = document.createElement("img") # setting.src = '../images/setting-icon-opt.svg' setting.src = "data:image/svg+xml;base64,PHN2ZyBiYXNlUHJvZmlsZT0iZnVsbCIgd2lkdGg9IjEwMCIgaGVpZ2h0PSIxMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+ICA8cGF0aCBkPSJNNDAgODQuNThsNCAxMy4wNGgxMmw0LTEzLjA0YTMwIDMwIDAgMCAwIDE0Ljk1LTguNjNsMTMuMyAzLjA2IDYtMTAuNC05LjMtOS45OGEzMCAzMCAwIDAgMCAwLTE3LjI2bDkuMy05Ljk5LTYtMTAuMzktMTMuMyAzLjA2QTMwIDMwIDAgMCAwIDYwIDE1LjQyTDU2IDIuMzhINDRsLTQgMTMuMDRhMzAgMzAgMCAwIDAtMTQuOTUgOC42M2wtMTMuMy0zLjA2LTYgMTAuNCA5LjMgOS45OGEzMCAzMCAwIDAgMCAwIDE3LjI2bC05LjMgOS45OSA2IDEwLjM5IDEzLjMtMy4wNkEzMCAzMCAwIDAgMCA0MCA4NC41OHpNMzUgNTBhMTUgMTUgMCAxIDEgMzAgMCAxNSAxNSAwIDEgMS0zMCAwIiBmaWxsPSIjZmZmIiBzdHJva2U9IiM1YTljZmMiIHN0cm9rZS13aWR0aD0iNSIvPjwvc3ZnPg=="; settingUtil = util(setting) settingUtil.css(iconStyle) settingUtil.on("click", do -> now = 'hidden'; after = 'visible' return -> panelUtil.css({'visibility': after}) # update state, swap variables [now, after] = [after, now] , false) controls.appendChild(setting) controls.appendChild(settingPanel) return {setting, settingPanel} # device orientation do -> # function scope for short variable that would not affect outside(same name) switchor = document.createElement("div") # the switch to control whether device orientation is on or off. switchorUtil = util(switchor) switchor.innerText = "Enable Sensor: " switchorUtil.css 'display': 'inline' 'color': "#000" 'font-size': "1em" 'font-weight': 'bold' # 'text-stroke': "0.2px #5a9cfc" # '-webkit-text-stroke': "0.2px #5a9cfc" status = document.createElement("span") util(status).css {'font-weight': 'normal'} on_tag = 'ON' off_tag = 'OFF' status.innerText = if settings.enableDeviceOrientation then on_tag else off_tag switchor.appendChild(status) switchorUtil.on('click', -> # switch change settings.enableDeviceOrientation = !settings.enableDeviceOrientation # update the status text if settings.enableDeviceOrientation status.innerText = on_tag else status.innerText = off_tag , false) # [end] attach event of device orientation switch settingPanel.appendChild(switchor) return switchor # [end] device orientation container.appendChild(controls) bindDeviceOrientation = () -> eventHandler = do -> ### # https://developer.mozilla.org/en-US/docs/Web/API/Detecting_device_orientation # the event values: # alpha: value represents the motion of the device around the z axis, represented in degrees with values ranging from 0 to 360. # beta: value represents the motion of the device around the x axis, represented in degrees with values ranging from -180 to 180. This represents a front to back motion of the device. # gamma: value represents the motion of the device around the y axis, represented in degrees with values ranging from -90 to 90. This represents a left to right motion of the device. ### alphaBefore = undefined betaBefore = undefined return (event)-> ### real event handler function. apply device orientation changed to lon and lat. ### if settings.enableDeviceOrientation # device orientation enabled alpha = event.alpha beta = event.beta if alphaBefore? ### alphaDelta(Δalpha) and betaDelta(Δbeta) are the changes of the orientation which longitude and latitude (lon lat) are applied. ### alphaDelta = alpha - alphaBefore betaDelta = beta - betaBefore lon = lon + alphaDelta lat = lat + betaDelta # record the orientation data for the next change alphaBefore = alpha betaBefore = beta else # device orientation is NOT enabled # reset the record of alpha and beta. alphaBefore = undefined betaBefore = undefined # register `deviceorientation` event util().on(window, "deviceorientation", eventHandler, true) # TODO TESTdeviceorientation bindDeviceOrientation() onWindowResize = (event, doesKeepInitSize = true) -> getViewerSize(doesKeepInitSize) camera.aspect = width / height camera.updateProjectionMatrix() renderer.setSize(width, height) {camera, mesh, scene, renderer} = init() # animate animate = () -> requestAnimationFrame animate update() return # the function is excuted each frame update = () -> # render the scene, capture result with the camera. updateCamera() renderer.render(scene, camera) updateCamera = () -> lat = Math.max(-85, Math.min(85, lat)) # the limit [-85, 85] that no pass over pole. # covent degrees to radians phi = THREE.Math.degToRad(90 - lat) theta = THREE.Math.degToRad(lon) radius = settings.sphere.radius x = radius * Math.sin(phi) * Math.cos(theta) y = radius * Math.cos(phi) z = radius * Math.sin(phi) * Math.sin(theta) camera.lookAt(new THREE.Vector3(x, y, z)) # first call to start animation. animate() # expose the object contains variable and function which can be accessed. debugSettings = settings.debug return { container, camera, mesh, scene, renderer, debugSettings, util}
166182
### # A panorama viewer base on three.js. # Panarama is a type of image which can be watched in 360 degree horizonally and 180 degree vertically. # # @license Apache 2.0 # @author MixFlow # @date 2017-08 ### window.threePanorama = (settings) -> defaultSettings = container: document.body image: undefined fov: 65 # camera fov(field of view) canUseWindowSize: false # If set false(defalut), Camera ratio and render size (Viewer size) are base on container size(fill). If set true, use window innerWidth and innerHeight. ### If width or height is missing(0), use this alternate ratio to calculate the missing size. If you want set specific ratio, please set your container size(width / height = ratio) and `canUseWindowSize` is false ### alternateRatio: 16/9 ### recommend to set `true`, if you don't set container width and height. Prevent the size of the container and renderer growing when window resizes(fire `onWindowResize` event). Record width and height data, next time the container width is some record again, use the correlative height. ### canKeepInitalSize: true enableDragNewImage: true # TODO [Not implemented] can drag image file which will be show as the new panorama to viewer(container) # [controls] # mouse mouseSensitivity: 0.1 # the sensitivity of mouse when is drag to control the camera. # device orientation enableDeviceOrientation: true # when device orientation(if the device has the sensor) is enabled, user turns around device to change the direction that user look at. # [end][controls] lonlat: [0, 0] # the initialize position that camera look at. sphere: # Default value works well. changing is not necessary. radius: 500 # the radius of the sphere whose texture is the panorama. debug: imageLoadProgress: false # !! not work for now!! lonlat: false # output the lon and lat positions. when user is controling. cameraSize: false # output camera size when it is changed. settings = settings || {} # put default setting into settings. for key,val of defaultSettings if key not of settings settings[key] = val # must provide image if not settings.image? throw { type: "No image provided." msg: "Please fill panorama image path(string) in the parameter 'image' of settings" } # set container dom. if typeof settings.container is "string" # only select first one container = document.querySelectorAll(settings.container)[0] else container = settings.container # the longitude and latitude position which are mapped to the sphere lon = settings.lonlat[0] lat = settings.lonlat[1] width = 0 height = 0 # size of render records = {} # the camera size records getViewerSize = (canKeepInitalSize = settings.canKeepInitalSize)-> if not settings.canUseWindowSize rect = container.getBoundingClientRect() width = rect.width height = rect.height else # use the browser window size width = window.innerWidth height = window.innerHeight if not width and not height throw { type: "Lack of Viewer Size.", msg: "Viewer width and height are both missing(value is 0), Please check the container size(width and height > 0). Or use window size to set Viewer size by setting `canUseWindowSize` as `true`" } else if not height height = width / settings.alternateRatio else if not width # height is not zero width = height * settings.alternateRatio if canKeepInitalSize is true if width not of records # record width height, may use later records[width] = height else # get older data height = records[width] if settings.debug.cameraSize console.log("current camera size:", width, height) return {width, height} # get init size getViewerSize() util = do -> handler = addClass: (domel, clazz) -> domel.className += " " + clazz removeClass: (domel, clazz) -> domel.className = domel.className.replace(new RegExp('(\\s|^)' + clazz + '(\\s|$)'), '') getAttribute: (domel, attr) -> return domel.getAttribute(attr) setAttributes: (domel, options) -> domel.setAttribute(key, val) for key,val of options css: (domel, options) -> for property, value of options domel.style[property] = value on: (domel, event, callback, useCapture=false) -> evts = event.split(" ") domel.addEventListener(evt, callback, useCapture) for evt in evts off: (domel, eventsString, callback, useCapture=false) -> evts = eventsString.split(" ") domel.removeEventListener(evt, callback, useCapture) for evt in evts wrapperGenerator = (wrapper)-> methodHelper = (fn) -> # avoid create function in the loop return (args...) -> # the real method of util fn(wrapper.domel, args...) wrapper # return wrapper itself to call continually later for method, fn of handler # transfer the handler methods to the wrapper methods wrapper[method] = methodHelper(fn) wrapper # the generated wrapper return (el)-> # if el? wrapper = domel: el # set DOM element wrapperGenerator(wrapper) else return handler ### # Initiate the three.js components. # Steps: # create a sphere and put panorama on faces inside # create a camera, put it on origin which is also the center of sphere # bind some control: # 1. mouse or touch or device orient to control the rotation of camera. # render the scene ### init = -> # noraml camera (Perspective). (fov, camera screen ratio(width / height), near clip distance, far clip dist) # TODO ? take 'ratio' param from setting? camera = new THREE.PerspectiveCamera(settings.fov, width / height, 1, 1100 ) # the camera lookAt target whose position in 3D space for the camera to point towards # TODO the init camera target position # camera.lookAt(new THREE.Vector3(0, 0, 0)) camera.target = new THREE.Vector3( 0, 0, 0 ) # create the sphere mesh, put panorama on it. # SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) geometry = new THREE.SphereBufferGeometry(settings.sphere.radius, 50, 50) geometry.scale(-1, 1, 1) # filp the face of sphere, because the material(texture) should be on inside. # !!onProgress not work now. the part is comment out in the three.js(r87) ImageLoad source code # loadingManager = new THREE.LoadingManager() # loadingManager.onProgress = (url, loaded, total)-> # # onProgress, Will be called while load progresses, he argument will be the XMLHttpRequest instance, which contains .total and .loaded bytes. # precent = loaded / total * 100 # # if settings.debug.imageLoadProgress # console.log("Image loaded: ", Math.round(precent, 2), "%") texture = new THREE.TextureLoader().load(settings.image) material = new THREE.MeshBasicMaterial map: texture mesh = new THREE.Mesh(geometry, material) # create a scene and put the sphere in the scene. scene = new THREE.Scene() scene.add(mesh) # create renderer and attach the result(renderer dom) in container renderer = initRenderer() container.appendChild( renderer.domElement ) # bind mouse event to control the camera bindMouseTouchControl(renderer.domElement) # control bar initControls(container) # resize the camera and renderer when window size changed. util(window).on("resize", do -> # prevent fire resize multi times. only need call the function when resize finished resizeTimer = undefined return (event) -> clearTimeout resizeTimer resizeTimer = setTimeout( -> onWindowResize(event, false) , 100) ,false) return {camera, mesh, scene, renderer} # [end] init # the components initiate functions. initRenderer = -> renderer = new THREE.WebGLRenderer() renderer.setPixelRatio( window.devicePixelRatio ) renderer.setSize(width, height) return renderer # [end] init_renderer bindMouseTouchControl = (target) -> # the dom target, which the mouse events are trigged on. controlStartX = 0 controlStartY = 0 controlStartLon = 0 controlStartLat = 0 isUserControling = false controlStartHelper = (isTouch) -> # Base on `isTouch`, generate touch(true) or mouse(otherwise) version event handler. return (event) -> event.preventDefault() isUserControling = true controlStartX = if not isTouch then event.clientX else event.changedTouches[0].clientX controlStartY = if not isTouch then event.clientY else event.changedTouches[0].clientY controlStartLon = lon controlStartLat = lat controlMoveHelper = (isTouch) -> return (event) -> # mouse move over, or touch move over if isUserControling is true x = if not isTouch then event.clientX else event.changedTouches[0].clientX y = if not isTouch then event.clientY else event.changedTouches[0].clientY sensitivity = settings.mouseSensitivity # TODO ? touch sensitivity? lon = (controlStartX - x) * sensitivity + controlStartLon lat = (y - controlStartY) * sensitivity + controlStartLat if settings.debug.lonlat console.log "longitude: ", lon, "latitude: ", lat controlEnd = (event) -> # release the mouse key. isUserControling = false mouseDownHandle = controlStartHelper(false) mouseMoveHandle = controlMoveHelper(false) mouseUpHandle = controlEnd targetUtil = util(target) # bind mouse event targetUtil.on 'mousedown', mouseDownHandle, false .on 'mousemove', mouseMoveHandle, false .on 'mouseup', mouseUpHandle, false touchStartHandle = controlStartHelper(true) touchMoveHandle = controlMoveHelper(true) touchEndHandle = controlEnd # touch event targetUtil.on "touchstart", touchStartHandle, false .on "touchmove", touchMoveHandle, false .on "touchend", touchEndHandle, false getFullscreenElementHelper = (container) -> if not container? container = document return -> container.fullscreenElement or container.webkitFullscreenElement or container.mozFullScreenElement or container.msFullscreenElement getFullscreenElement = getFullscreenElementHelper() requestAndExitFullscreenHelper = -> ### The helper function to create the `exitFullscreen` and `requestFullscreen` callback function. There is no need for checking different broswer methods when the fullscreen is toggled every time. ### if document.exitFullscreen ### `exitFn = document.exitFullscreen` not work alternate way: `exitFn = document.exitFullscreen.bind(document)` (es5) ### exitFn = -> document.exitFullscreen() requestFn = (target) -> target.requestFullscreen() else if document.msExitFullscreen exitFn = -> document.msExitFullscreen() requestFn = (target) -> target.msRequestFullscreen() else if document.mozCancelFullScreen exitFn = -> document.mozCancelFullScreen() requestFn = (target) -> target.mozRequestFullscreen() else if document.webkitExitFullscreen exitFn = -> document.webkitExitFullscreen() requestFn = (target) -> target.webkitRequestFullscreen() else exitFn = -> console.log("The bowser doesn't support fullscreen mode") # Don't support fullscreen requestFn = exitFn return { request: requestFn exit: exitFn } toggleTargetFullscreen = do -> {request, exit} = requestAndExitFullscreenHelper() return (target) -> ### If no fullscreen element, the `target` enters fullscree. Otherwise fullscreen element exit fullscreen. Both trigge the `fullscreenchange` event. ### if getFullscreenElement() # Before fullscreen state, exit fullscreen now. # call the `exit` helper function exit() else # enter fullscreen now. # the `request` helper function which requests the fullscreen. request(target) changeFullscreenState = (target) -> ### the actual behavior when fullscreen state is changed. ### # TODO [important] make a wrapper for styling?? fullscreenElement = getFullscreenElement() clazz = "fullscreen-mode" targetUtil = util(target) if (fullscreenElement?) # fullscreen # target.className += " " + clazz targetUtil.addClass(clazz) target.style.width = "100vw" target.style.height = "100vh" target.style["max-width"] = "unset" target.style["max-height"] = "unset" else # remove class name # TODO clean up. make a helper to handle class name. # target.className = target.className.replace(new RegExp('(\\s|^)' + clazz + '(\\s|$)'), '') targetUtil.removeClass(clazz) target.style.width = null target.style.height = null target.style["max-width"] = null target.style["max-height"] = null # [don't uncomment] enter or exit fullscreen will toggle `resize` event of `window`. no need to call the function to resize again. # reset 3panorama camera and renderer(cavans) size # onWindowResize(undefined, false) initControls = (container) -> controls = document.createElement("div") controls.className = "3panorama-controls" # postion: above the container controls.style.position = "absolute" controls.style.bottom = 0 controls.style.width = "100%" controls.style.height = "3.5em" controls.style["min-height"] = "32px" iconStyle = {height: '75%', 'min-height': '24px', padding: '0.3em'} # fullscreen button fullscreen = document.createElement("img") fullscreenUtil = util(fullscreen) # the converted base64 url based on svg file (fullscreen-icon-opt.svg) fullscreen.src = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzMjAgMzIwIiB3aWR0aD0iMjQiIGhlaWdodD0iMjQiPiAgPHBhdGggZmlsbD0iIzVhOWNmYyIgZD0iTTEyNSAxODAuODVsLTEwNSAxMDVWMjAzLjRIMFYzMj<KEY> fullscreenUtil.css iconStyle fullscreenUtil.on("click", -> toggleTargetFullscreen(container) , false) util(document).on "webkitfullscreenchange mozfullscreenchange fullscreenchange msfullscreenchange", -> changeFullscreenState(container) controls.appendChild(fullscreen) # setting button {_, settingPanel} = do -> # settings on the pannel settingPanel = document.createElement('div') panelUtil = util(settingPanel) panelUtil.addClass('3panorama-setting-pannel') panelUtil.css 'visibility': 'hidden' display: 'inline' position: 'relative' background: '#FFF' bottom: '100%' left: '-24px' padding: '0.4em 0.8em' # setting icon buttion setting = document.createElement("img") # setting.src = '../images/setting-icon-opt.svg' setting.src = "data:image/svg+xml;base64,PH<KEY>2ZyBiYXNlUHJvZmlsZT0iZnVsbCIgd2lkdG<KEY>9Ij<KEY>Z<KEY>Lm<KEY>Zy<KEY>y<KEY>; settingUtil = util(setting) settingUtil.css(iconStyle) settingUtil.on("click", do -> now = 'hidden'; after = 'visible' return -> panelUtil.css({'visibility': after}) # update state, swap variables [now, after] = [after, now] , false) controls.appendChild(setting) controls.appendChild(settingPanel) return {setting, settingPanel} # device orientation do -> # function scope for short variable that would not affect outside(same name) switchor = document.createElement("div") # the switch to control whether device orientation is on or off. switchorUtil = util(switchor) switchor.innerText = "Enable Sensor: " switchorUtil.css 'display': 'inline' 'color': "#000" 'font-size': "1em" 'font-weight': 'bold' # 'text-stroke': "0.2px #5a9cfc" # '-webkit-text-stroke': "0.2px #5a9cfc" status = document.createElement("span") util(status).css {'font-weight': 'normal'} on_tag = 'ON' off_tag = 'OFF' status.innerText = if settings.enableDeviceOrientation then on_tag else off_tag switchor.appendChild(status) switchorUtil.on('click', -> # switch change settings.enableDeviceOrientation = !settings.enableDeviceOrientation # update the status text if settings.enableDeviceOrientation status.innerText = on_tag else status.innerText = off_tag , false) # [end] attach event of device orientation switch settingPanel.appendChild(switchor) return switchor # [end] device orientation container.appendChild(controls) bindDeviceOrientation = () -> eventHandler = do -> ### # https://developer.mozilla.org/en-US/docs/Web/API/Detecting_device_orientation # the event values: # alpha: value represents the motion of the device around the z axis, represented in degrees with values ranging from 0 to 360. # beta: value represents the motion of the device around the x axis, represented in degrees with values ranging from -180 to 180. This represents a front to back motion of the device. # gamma: value represents the motion of the device around the y axis, represented in degrees with values ranging from -90 to 90. This represents a left to right motion of the device. ### alphaBefore = undefined betaBefore = undefined return (event)-> ### real event handler function. apply device orientation changed to lon and lat. ### if settings.enableDeviceOrientation # device orientation enabled alpha = event.alpha beta = event.beta if alphaBefore? ### alphaDelta(Δalpha) and betaDelta(Δbeta) are the changes of the orientation which longitude and latitude (lon lat) are applied. ### alphaDelta = alpha - alphaBefore betaDelta = beta - betaBefore lon = lon + alphaDelta lat = lat + betaDelta # record the orientation data for the next change alphaBefore = alpha betaBefore = beta else # device orientation is NOT enabled # reset the record of alpha and beta. alphaBefore = undefined betaBefore = undefined # register `deviceorientation` event util().on(window, "deviceorientation", eventHandler, true) # TODO TESTdeviceorientation bindDeviceOrientation() onWindowResize = (event, doesKeepInitSize = true) -> getViewerSize(doesKeepInitSize) camera.aspect = width / height camera.updateProjectionMatrix() renderer.setSize(width, height) {camera, mesh, scene, renderer} = init() # animate animate = () -> requestAnimationFrame animate update() return # the function is excuted each frame update = () -> # render the scene, capture result with the camera. updateCamera() renderer.render(scene, camera) updateCamera = () -> lat = Math.max(-85, Math.min(85, lat)) # the limit [-85, 85] that no pass over pole. # covent degrees to radians phi = THREE.Math.degToRad(90 - lat) theta = THREE.Math.degToRad(lon) radius = settings.sphere.radius x = radius * Math.sin(phi) * Math.cos(theta) y = radius * Math.cos(phi) z = radius * Math.sin(phi) * Math.sin(theta) camera.lookAt(new THREE.Vector3(x, y, z)) # first call to start animation. animate() # expose the object contains variable and function which can be accessed. debugSettings = settings.debug return { container, camera, mesh, scene, renderer, debugSettings, util}
true
### # A panorama viewer base on three.js. # Panarama is a type of image which can be watched in 360 degree horizonally and 180 degree vertically. # # @license Apache 2.0 # @author MixFlow # @date 2017-08 ### window.threePanorama = (settings) -> defaultSettings = container: document.body image: undefined fov: 65 # camera fov(field of view) canUseWindowSize: false # If set false(defalut), Camera ratio and render size (Viewer size) are base on container size(fill). If set true, use window innerWidth and innerHeight. ### If width or height is missing(0), use this alternate ratio to calculate the missing size. If you want set specific ratio, please set your container size(width / height = ratio) and `canUseWindowSize` is false ### alternateRatio: 16/9 ### recommend to set `true`, if you don't set container width and height. Prevent the size of the container and renderer growing when window resizes(fire `onWindowResize` event). Record width and height data, next time the container width is some record again, use the correlative height. ### canKeepInitalSize: true enableDragNewImage: true # TODO [Not implemented] can drag image file which will be show as the new panorama to viewer(container) # [controls] # mouse mouseSensitivity: 0.1 # the sensitivity of mouse when is drag to control the camera. # device orientation enableDeviceOrientation: true # when device orientation(if the device has the sensor) is enabled, user turns around device to change the direction that user look at. # [end][controls] lonlat: [0, 0] # the initialize position that camera look at. sphere: # Default value works well. changing is not necessary. radius: 500 # the radius of the sphere whose texture is the panorama. debug: imageLoadProgress: false # !! not work for now!! lonlat: false # output the lon and lat positions. when user is controling. cameraSize: false # output camera size when it is changed. settings = settings || {} # put default setting into settings. for key,val of defaultSettings if key not of settings settings[key] = val # must provide image if not settings.image? throw { type: "No image provided." msg: "Please fill panorama image path(string) in the parameter 'image' of settings" } # set container dom. if typeof settings.container is "string" # only select first one container = document.querySelectorAll(settings.container)[0] else container = settings.container # the longitude and latitude position which are mapped to the sphere lon = settings.lonlat[0] lat = settings.lonlat[1] width = 0 height = 0 # size of render records = {} # the camera size records getViewerSize = (canKeepInitalSize = settings.canKeepInitalSize)-> if not settings.canUseWindowSize rect = container.getBoundingClientRect() width = rect.width height = rect.height else # use the browser window size width = window.innerWidth height = window.innerHeight if not width and not height throw { type: "Lack of Viewer Size.", msg: "Viewer width and height are both missing(value is 0), Please check the container size(width and height > 0). Or use window size to set Viewer size by setting `canUseWindowSize` as `true`" } else if not height height = width / settings.alternateRatio else if not width # height is not zero width = height * settings.alternateRatio if canKeepInitalSize is true if width not of records # record width height, may use later records[width] = height else # get older data height = records[width] if settings.debug.cameraSize console.log("current camera size:", width, height) return {width, height} # get init size getViewerSize() util = do -> handler = addClass: (domel, clazz) -> domel.className += " " + clazz removeClass: (domel, clazz) -> domel.className = domel.className.replace(new RegExp('(\\s|^)' + clazz + '(\\s|$)'), '') getAttribute: (domel, attr) -> return domel.getAttribute(attr) setAttributes: (domel, options) -> domel.setAttribute(key, val) for key,val of options css: (domel, options) -> for property, value of options domel.style[property] = value on: (domel, event, callback, useCapture=false) -> evts = event.split(" ") domel.addEventListener(evt, callback, useCapture) for evt in evts off: (domel, eventsString, callback, useCapture=false) -> evts = eventsString.split(" ") domel.removeEventListener(evt, callback, useCapture) for evt in evts wrapperGenerator = (wrapper)-> methodHelper = (fn) -> # avoid create function in the loop return (args...) -> # the real method of util fn(wrapper.domel, args...) wrapper # return wrapper itself to call continually later for method, fn of handler # transfer the handler methods to the wrapper methods wrapper[method] = methodHelper(fn) wrapper # the generated wrapper return (el)-> # if el? wrapper = domel: el # set DOM element wrapperGenerator(wrapper) else return handler ### # Initiate the three.js components. # Steps: # create a sphere and put panorama on faces inside # create a camera, put it on origin which is also the center of sphere # bind some control: # 1. mouse or touch or device orient to control the rotation of camera. # render the scene ### init = -> # noraml camera (Perspective). (fov, camera screen ratio(width / height), near clip distance, far clip dist) # TODO ? take 'ratio' param from setting? camera = new THREE.PerspectiveCamera(settings.fov, width / height, 1, 1100 ) # the camera lookAt target whose position in 3D space for the camera to point towards # TODO the init camera target position # camera.lookAt(new THREE.Vector3(0, 0, 0)) camera.target = new THREE.Vector3( 0, 0, 0 ) # create the sphere mesh, put panorama on it. # SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) geometry = new THREE.SphereBufferGeometry(settings.sphere.radius, 50, 50) geometry.scale(-1, 1, 1) # filp the face of sphere, because the material(texture) should be on inside. # !!onProgress not work now. the part is comment out in the three.js(r87) ImageLoad source code # loadingManager = new THREE.LoadingManager() # loadingManager.onProgress = (url, loaded, total)-> # # onProgress, Will be called while load progresses, he argument will be the XMLHttpRequest instance, which contains .total and .loaded bytes. # precent = loaded / total * 100 # # if settings.debug.imageLoadProgress # console.log("Image loaded: ", Math.round(precent, 2), "%") texture = new THREE.TextureLoader().load(settings.image) material = new THREE.MeshBasicMaterial map: texture mesh = new THREE.Mesh(geometry, material) # create a scene and put the sphere in the scene. scene = new THREE.Scene() scene.add(mesh) # create renderer and attach the result(renderer dom) in container renderer = initRenderer() container.appendChild( renderer.domElement ) # bind mouse event to control the camera bindMouseTouchControl(renderer.domElement) # control bar initControls(container) # resize the camera and renderer when window size changed. util(window).on("resize", do -> # prevent fire resize multi times. only need call the function when resize finished resizeTimer = undefined return (event) -> clearTimeout resizeTimer resizeTimer = setTimeout( -> onWindowResize(event, false) , 100) ,false) return {camera, mesh, scene, renderer} # [end] init # the components initiate functions. initRenderer = -> renderer = new THREE.WebGLRenderer() renderer.setPixelRatio( window.devicePixelRatio ) renderer.setSize(width, height) return renderer # [end] init_renderer bindMouseTouchControl = (target) -> # the dom target, which the mouse events are trigged on. controlStartX = 0 controlStartY = 0 controlStartLon = 0 controlStartLat = 0 isUserControling = false controlStartHelper = (isTouch) -> # Base on `isTouch`, generate touch(true) or mouse(otherwise) version event handler. return (event) -> event.preventDefault() isUserControling = true controlStartX = if not isTouch then event.clientX else event.changedTouches[0].clientX controlStartY = if not isTouch then event.clientY else event.changedTouches[0].clientY controlStartLon = lon controlStartLat = lat controlMoveHelper = (isTouch) -> return (event) -> # mouse move over, or touch move over if isUserControling is true x = if not isTouch then event.clientX else event.changedTouches[0].clientX y = if not isTouch then event.clientY else event.changedTouches[0].clientY sensitivity = settings.mouseSensitivity # TODO ? touch sensitivity? lon = (controlStartX - x) * sensitivity + controlStartLon lat = (y - controlStartY) * sensitivity + controlStartLat if settings.debug.lonlat console.log "longitude: ", lon, "latitude: ", lat controlEnd = (event) -> # release the mouse key. isUserControling = false mouseDownHandle = controlStartHelper(false) mouseMoveHandle = controlMoveHelper(false) mouseUpHandle = controlEnd targetUtil = util(target) # bind mouse event targetUtil.on 'mousedown', mouseDownHandle, false .on 'mousemove', mouseMoveHandle, false .on 'mouseup', mouseUpHandle, false touchStartHandle = controlStartHelper(true) touchMoveHandle = controlMoveHelper(true) touchEndHandle = controlEnd # touch event targetUtil.on "touchstart", touchStartHandle, false .on "touchmove", touchMoveHandle, false .on "touchend", touchEndHandle, false getFullscreenElementHelper = (container) -> if not container? container = document return -> container.fullscreenElement or container.webkitFullscreenElement or container.mozFullScreenElement or container.msFullscreenElement getFullscreenElement = getFullscreenElementHelper() requestAndExitFullscreenHelper = -> ### The helper function to create the `exitFullscreen` and `requestFullscreen` callback function. There is no need for checking different broswer methods when the fullscreen is toggled every time. ### if document.exitFullscreen ### `exitFn = document.exitFullscreen` not work alternate way: `exitFn = document.exitFullscreen.bind(document)` (es5) ### exitFn = -> document.exitFullscreen() requestFn = (target) -> target.requestFullscreen() else if document.msExitFullscreen exitFn = -> document.msExitFullscreen() requestFn = (target) -> target.msRequestFullscreen() else if document.mozCancelFullScreen exitFn = -> document.mozCancelFullScreen() requestFn = (target) -> target.mozRequestFullscreen() else if document.webkitExitFullscreen exitFn = -> document.webkitExitFullscreen() requestFn = (target) -> target.webkitRequestFullscreen() else exitFn = -> console.log("The bowser doesn't support fullscreen mode") # Don't support fullscreen requestFn = exitFn return { request: requestFn exit: exitFn } toggleTargetFullscreen = do -> {request, exit} = requestAndExitFullscreenHelper() return (target) -> ### If no fullscreen element, the `target` enters fullscree. Otherwise fullscreen element exit fullscreen. Both trigge the `fullscreenchange` event. ### if getFullscreenElement() # Before fullscreen state, exit fullscreen now. # call the `exit` helper function exit() else # enter fullscreen now. # the `request` helper function which requests the fullscreen. request(target) changeFullscreenState = (target) -> ### the actual behavior when fullscreen state is changed. ### # TODO [important] make a wrapper for styling?? fullscreenElement = getFullscreenElement() clazz = "fullscreen-mode" targetUtil = util(target) if (fullscreenElement?) # fullscreen # target.className += " " + clazz targetUtil.addClass(clazz) target.style.width = "100vw" target.style.height = "100vh" target.style["max-width"] = "unset" target.style["max-height"] = "unset" else # remove class name # TODO clean up. make a helper to handle class name. # target.className = target.className.replace(new RegExp('(\\s|^)' + clazz + '(\\s|$)'), '') targetUtil.removeClass(clazz) target.style.width = null target.style.height = null target.style["max-width"] = null target.style["max-height"] = null # [don't uncomment] enter or exit fullscreen will toggle `resize` event of `window`. no need to call the function to resize again. # reset 3panorama camera and renderer(cavans) size # onWindowResize(undefined, false) initControls = (container) -> controls = document.createElement("div") controls.className = "3panorama-controls" # postion: above the container controls.style.position = "absolute" controls.style.bottom = 0 controls.style.width = "100%" controls.style.height = "3.5em" controls.style["min-height"] = "32px" iconStyle = {height: '75%', 'min-height': '24px', padding: '0.3em'} # fullscreen button fullscreen = document.createElement("img") fullscreenUtil = util(fullscreen) # the converted base64 url based on svg file (fullscreen-icon-opt.svg) fullscreen.src = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzMjAgMzIwIiB3aWR0aD0iMjQiIGhlaWdodD0iMjQiPiAgPHBhdGggZmlsbD0iIzVhOWNmYyIgZD0iTTEyNSAxODAuODVsLTEwNSAxMDVWMjAzLjRIMFYzMjPI:KEY:<KEY>END_PI fullscreenUtil.css iconStyle fullscreenUtil.on("click", -> toggleTargetFullscreen(container) , false) util(document).on "webkitfullscreenchange mozfullscreenchange fullscreenchange msfullscreenchange", -> changeFullscreenState(container) controls.appendChild(fullscreen) # setting button {_, settingPanel} = do -> # settings on the pannel settingPanel = document.createElement('div') panelUtil = util(settingPanel) panelUtil.addClass('3panorama-setting-pannel') panelUtil.css 'visibility': 'hidden' display: 'inline' position: 'relative' background: '#FFF' bottom: '100%' left: '-24px' padding: '0.4em 0.8em' # setting icon buttion setting = document.createElement("img") # setting.src = '../images/setting-icon-opt.svg' setting.src = "data:image/svg+xml;base64,PHPI:KEY:<KEY>END_PI2ZyBiYXNlUHJvZmlsZT0iZnVsbCIgd2lkdGPI:KEY:<KEY>END_PI9IjPI:KEY:<KEY>END_PIZPI:KEY:<KEY>END_PILmPI:KEY:<KEY>END_PIZyPI:KEY:<KEY>END_PIyPI:KEY:<KEY>END_PI; settingUtil = util(setting) settingUtil.css(iconStyle) settingUtil.on("click", do -> now = 'hidden'; after = 'visible' return -> panelUtil.css({'visibility': after}) # update state, swap variables [now, after] = [after, now] , false) controls.appendChild(setting) controls.appendChild(settingPanel) return {setting, settingPanel} # device orientation do -> # function scope for short variable that would not affect outside(same name) switchor = document.createElement("div") # the switch to control whether device orientation is on or off. switchorUtil = util(switchor) switchor.innerText = "Enable Sensor: " switchorUtil.css 'display': 'inline' 'color': "#000" 'font-size': "1em" 'font-weight': 'bold' # 'text-stroke': "0.2px #5a9cfc" # '-webkit-text-stroke': "0.2px #5a9cfc" status = document.createElement("span") util(status).css {'font-weight': 'normal'} on_tag = 'ON' off_tag = 'OFF' status.innerText = if settings.enableDeviceOrientation then on_tag else off_tag switchor.appendChild(status) switchorUtil.on('click', -> # switch change settings.enableDeviceOrientation = !settings.enableDeviceOrientation # update the status text if settings.enableDeviceOrientation status.innerText = on_tag else status.innerText = off_tag , false) # [end] attach event of device orientation switch settingPanel.appendChild(switchor) return switchor # [end] device orientation container.appendChild(controls) bindDeviceOrientation = () -> eventHandler = do -> ### # https://developer.mozilla.org/en-US/docs/Web/API/Detecting_device_orientation # the event values: # alpha: value represents the motion of the device around the z axis, represented in degrees with values ranging from 0 to 360. # beta: value represents the motion of the device around the x axis, represented in degrees with values ranging from -180 to 180. This represents a front to back motion of the device. # gamma: value represents the motion of the device around the y axis, represented in degrees with values ranging from -90 to 90. This represents a left to right motion of the device. ### alphaBefore = undefined betaBefore = undefined return (event)-> ### real event handler function. apply device orientation changed to lon and lat. ### if settings.enableDeviceOrientation # device orientation enabled alpha = event.alpha beta = event.beta if alphaBefore? ### alphaDelta(Δalpha) and betaDelta(Δbeta) are the changes of the orientation which longitude and latitude (lon lat) are applied. ### alphaDelta = alpha - alphaBefore betaDelta = beta - betaBefore lon = lon + alphaDelta lat = lat + betaDelta # record the orientation data for the next change alphaBefore = alpha betaBefore = beta else # device orientation is NOT enabled # reset the record of alpha and beta. alphaBefore = undefined betaBefore = undefined # register `deviceorientation` event util().on(window, "deviceorientation", eventHandler, true) # TODO TESTdeviceorientation bindDeviceOrientation() onWindowResize = (event, doesKeepInitSize = true) -> getViewerSize(doesKeepInitSize) camera.aspect = width / height camera.updateProjectionMatrix() renderer.setSize(width, height) {camera, mesh, scene, renderer} = init() # animate animate = () -> requestAnimationFrame animate update() return # the function is excuted each frame update = () -> # render the scene, capture result with the camera. updateCamera() renderer.render(scene, camera) updateCamera = () -> lat = Math.max(-85, Math.min(85, lat)) # the limit [-85, 85] that no pass over pole. # covent degrees to radians phi = THREE.Math.degToRad(90 - lat) theta = THREE.Math.degToRad(lon) radius = settings.sphere.radius x = radius * Math.sin(phi) * Math.cos(theta) y = radius * Math.cos(phi) z = radius * Math.sin(phi) * Math.sin(theta) camera.lookAt(new THREE.Vector3(x, y, z)) # first call to start animation. animate() # expose the object contains variable and function which can be accessed. debugSettings = settings.debug return { container, camera, mesh, scene, renderer, debugSettings, util}
[ { "context": "te'\n 'change #order': 'compileQuery'\n\n # XXX (Mispy): This is a bit messy and redundant\n # with th", "end": 1229, "score": 0.5211732387542725, "start": 1226, "tag": "USERNAME", "value": "Mis" }, { "context": "\n 'change #order': 'compileQuery'\n\n # XXX (Mispy): This is a bit messy and redundant\n # with the ", "end": 1231, "score": 0.500387966632843, "start": 1229, "tag": "NAME", "value": "py" } ]
app/assets/javascripts/search.js.coffee
marwahaha/scirate
0
class View.Search extends Backbone.View initialize: -> # Compute preset date ranges @ranges = {} now = moment() @ranges.week = @compileDateRange(now.clone().subtract('weeks', 1), now) @ranges.month = @compileDateRange(now.clone().subtract('months', 1), now) @ranges.year = @compileDateRange(now.clone().subtract('years', 1), now) @ranges.custom = null # If this is the result of a previous advanced search # then restore the fields from the query string if FromServer.advanced? && FromServer.advanced.length > 0 @toggleAdvanced() @readQuery(FromServer.advanced) engine = new Bloodhound( datumTokenizer: ((d) -> Bloodhound.tokenizers.whitespace(d.uid)) queryTokenizer: Bloodhound.tokenizers.whitespace local: FromServer.feeds.map((f) -> { uid: f }) ) engine.initialize() $('#category').typeahead({ highlight: true }, displayKey: 'uid', source: engine.ttAdapter()) @compileQuery() $(window).click => @compileQuery() events: 'click #toggleAdvanced': 'toggleAdvanced' 'change input': 'compileQuery' 'keyup input': 'compileQuery' 'change #date': 'changeDate' 'change #order': 'compileQuery' # XXX (Mispy): This is a bit messy and redundant # with the server-side code. Perhaps refactor so # we can just pass through the results of server-side # query parsing. psplit: (query) -> split = [] depth = 0 current = "" for ch, i in query if i == query.length-1 split.push current+ch else if ch == ' ' && depth == 0 split.push current current = "" else current += ch if ch == '(' depth += 1 else if ch == ')' depth -= 1 split readQuery: (query) -> authors = [] title = "" abstract = "" category = "" scited_by = "" date = null order = null for term in @psplit(query) [name, content] = term.split(':') if content[0] == '(' && content[-1..-1][0] == ')' content = content[1..-2] console.log @psplit(query) switch name when 'au' then authors.push content when 'ti' then title = content when 'abs' then abstract = content when 'in' then category = content when 'scited_by' then scited_by = content when 'date' date = switch content when @ranges.week then 'week' when @ranges.month then 'month' when @ranges.year then 'year' else @ranges.custom = content 'custom' when 'order' order = content @$('#authors').val authors.join(', ') @$('#title').val title @$('#abstract').val abstract @$('#category').val category @$('#scited_by').val scited_by @$('#date').val date if date? @$('#order').val order if order? showAdvanced: -> @$('#advancedSearch').removeClass('hidden') @$('#advanced').attr('name', 'advanced') @$('#toggleAdvanced i').removeClass('fa-chevron-right').addClass('fa-chevron-down') hideAdvanced: -> @$('#advancedSearch').addClass('hidden') @$('#advanced').attr('name', '') @$('#toggleAdvanced i').removeClass('fa-chevron-down').addClass('fa-chevron-right') toggleAdvanced: -> console.log @$('#advancedSearch') if @$('#advancedSearch').hasClass('hidden') @showAdvanced() else @hideAdvanced() changeDate: -> if @$('#date').val() == 'custom' SciRate.customDateRange (start, end) => @ranges.custom = @compileDateRange(start, end) if @ranges.custom == null @$('#date').val('any') @compileQuery() else @ranges.custom = null @compileQuery() escape: (s) -> if s.indexOf(' ') != -1 s = '(' + s + ')' s compileDateRange: (start, finish) -> if !start.isValid() && !finish.isValid() null else range = "" if start.isValid() then range += start.format('YYYY-MM-DD') range += '..' if finish.isValid() then range += finish.format('YYYY-MM-DD') range compileQuery: -> query = [] @$('#authors').val().split(/,\s*/).forEach (author) => return if author.length == 0 query.push("au:#{@escape(author)}") title = @$('#title').val() query.push("ti:#{@escape(title)}") if title.length > 0 abstract = @$('#abstract').val() query.push("abs:#{@escape(abstract)}") if abstract.length > 0 category = @$('#category').val() query.push("in:#{@escape(category)}") if category.length > 0 scited_by = @$('#scited_by').val() query.push("scited_by:#{@escape(scited_by)}") if scited_by.length > 0 date = @$('#date').val() if date != 'any' && @ranges[date]? query.push "date:#{@ranges[date]}" order = @$('#order').val() if order != "recency" query.push("order:#{order}") query_text = query.join(' ') $('input#advanced').val(query_text) $('#advancedPreview').text(@$('#q').val() + ' ' + query_text) $(document).on 'ready', -> $('#searchPage').each -> new View.Search(el: this) $(document).on 'page:load', -> $('#searchPage').each -> new View.Search(el: this)
42021
class View.Search extends Backbone.View initialize: -> # Compute preset date ranges @ranges = {} now = moment() @ranges.week = @compileDateRange(now.clone().subtract('weeks', 1), now) @ranges.month = @compileDateRange(now.clone().subtract('months', 1), now) @ranges.year = @compileDateRange(now.clone().subtract('years', 1), now) @ranges.custom = null # If this is the result of a previous advanced search # then restore the fields from the query string if FromServer.advanced? && FromServer.advanced.length > 0 @toggleAdvanced() @readQuery(FromServer.advanced) engine = new Bloodhound( datumTokenizer: ((d) -> Bloodhound.tokenizers.whitespace(d.uid)) queryTokenizer: Bloodhound.tokenizers.whitespace local: FromServer.feeds.map((f) -> { uid: f }) ) engine.initialize() $('#category').typeahead({ highlight: true }, displayKey: 'uid', source: engine.ttAdapter()) @compileQuery() $(window).click => @compileQuery() events: 'click #toggleAdvanced': 'toggleAdvanced' 'change input': 'compileQuery' 'keyup input': 'compileQuery' 'change #date': 'changeDate' 'change #order': 'compileQuery' # XXX (Mis<NAME>): This is a bit messy and redundant # with the server-side code. Perhaps refactor so # we can just pass through the results of server-side # query parsing. psplit: (query) -> split = [] depth = 0 current = "" for ch, i in query if i == query.length-1 split.push current+ch else if ch == ' ' && depth == 0 split.push current current = "" else current += ch if ch == '(' depth += 1 else if ch == ')' depth -= 1 split readQuery: (query) -> authors = [] title = "" abstract = "" category = "" scited_by = "" date = null order = null for term in @psplit(query) [name, content] = term.split(':') if content[0] == '(' && content[-1..-1][0] == ')' content = content[1..-2] console.log @psplit(query) switch name when 'au' then authors.push content when 'ti' then title = content when 'abs' then abstract = content when 'in' then category = content when 'scited_by' then scited_by = content when 'date' date = switch content when @ranges.week then 'week' when @ranges.month then 'month' when @ranges.year then 'year' else @ranges.custom = content 'custom' when 'order' order = content @$('#authors').val authors.join(', ') @$('#title').val title @$('#abstract').val abstract @$('#category').val category @$('#scited_by').val scited_by @$('#date').val date if date? @$('#order').val order if order? showAdvanced: -> @$('#advancedSearch').removeClass('hidden') @$('#advanced').attr('name', 'advanced') @$('#toggleAdvanced i').removeClass('fa-chevron-right').addClass('fa-chevron-down') hideAdvanced: -> @$('#advancedSearch').addClass('hidden') @$('#advanced').attr('name', '') @$('#toggleAdvanced i').removeClass('fa-chevron-down').addClass('fa-chevron-right') toggleAdvanced: -> console.log @$('#advancedSearch') if @$('#advancedSearch').hasClass('hidden') @showAdvanced() else @hideAdvanced() changeDate: -> if @$('#date').val() == 'custom' SciRate.customDateRange (start, end) => @ranges.custom = @compileDateRange(start, end) if @ranges.custom == null @$('#date').val('any') @compileQuery() else @ranges.custom = null @compileQuery() escape: (s) -> if s.indexOf(' ') != -1 s = '(' + s + ')' s compileDateRange: (start, finish) -> if !start.isValid() && !finish.isValid() null else range = "" if start.isValid() then range += start.format('YYYY-MM-DD') range += '..' if finish.isValid() then range += finish.format('YYYY-MM-DD') range compileQuery: -> query = [] @$('#authors').val().split(/,\s*/).forEach (author) => return if author.length == 0 query.push("au:#{@escape(author)}") title = @$('#title').val() query.push("ti:#{@escape(title)}") if title.length > 0 abstract = @$('#abstract').val() query.push("abs:#{@escape(abstract)}") if abstract.length > 0 category = @$('#category').val() query.push("in:#{@escape(category)}") if category.length > 0 scited_by = @$('#scited_by').val() query.push("scited_by:#{@escape(scited_by)}") if scited_by.length > 0 date = @$('#date').val() if date != 'any' && @ranges[date]? query.push "date:#{@ranges[date]}" order = @$('#order').val() if order != "recency" query.push("order:#{order}") query_text = query.join(' ') $('input#advanced').val(query_text) $('#advancedPreview').text(@$('#q').val() + ' ' + query_text) $(document).on 'ready', -> $('#searchPage').each -> new View.Search(el: this) $(document).on 'page:load', -> $('#searchPage').each -> new View.Search(el: this)
true
class View.Search extends Backbone.View initialize: -> # Compute preset date ranges @ranges = {} now = moment() @ranges.week = @compileDateRange(now.clone().subtract('weeks', 1), now) @ranges.month = @compileDateRange(now.clone().subtract('months', 1), now) @ranges.year = @compileDateRange(now.clone().subtract('years', 1), now) @ranges.custom = null # If this is the result of a previous advanced search # then restore the fields from the query string if FromServer.advanced? && FromServer.advanced.length > 0 @toggleAdvanced() @readQuery(FromServer.advanced) engine = new Bloodhound( datumTokenizer: ((d) -> Bloodhound.tokenizers.whitespace(d.uid)) queryTokenizer: Bloodhound.tokenizers.whitespace local: FromServer.feeds.map((f) -> { uid: f }) ) engine.initialize() $('#category').typeahead({ highlight: true }, displayKey: 'uid', source: engine.ttAdapter()) @compileQuery() $(window).click => @compileQuery() events: 'click #toggleAdvanced': 'toggleAdvanced' 'change input': 'compileQuery' 'keyup input': 'compileQuery' 'change #date': 'changeDate' 'change #order': 'compileQuery' # XXX (MisPI:NAME:<NAME>END_PI): This is a bit messy and redundant # with the server-side code. Perhaps refactor so # we can just pass through the results of server-side # query parsing. psplit: (query) -> split = [] depth = 0 current = "" for ch, i in query if i == query.length-1 split.push current+ch else if ch == ' ' && depth == 0 split.push current current = "" else current += ch if ch == '(' depth += 1 else if ch == ')' depth -= 1 split readQuery: (query) -> authors = [] title = "" abstract = "" category = "" scited_by = "" date = null order = null for term in @psplit(query) [name, content] = term.split(':') if content[0] == '(' && content[-1..-1][0] == ')' content = content[1..-2] console.log @psplit(query) switch name when 'au' then authors.push content when 'ti' then title = content when 'abs' then abstract = content when 'in' then category = content when 'scited_by' then scited_by = content when 'date' date = switch content when @ranges.week then 'week' when @ranges.month then 'month' when @ranges.year then 'year' else @ranges.custom = content 'custom' when 'order' order = content @$('#authors').val authors.join(', ') @$('#title').val title @$('#abstract').val abstract @$('#category').val category @$('#scited_by').val scited_by @$('#date').val date if date? @$('#order').val order if order? showAdvanced: -> @$('#advancedSearch').removeClass('hidden') @$('#advanced').attr('name', 'advanced') @$('#toggleAdvanced i').removeClass('fa-chevron-right').addClass('fa-chevron-down') hideAdvanced: -> @$('#advancedSearch').addClass('hidden') @$('#advanced').attr('name', '') @$('#toggleAdvanced i').removeClass('fa-chevron-down').addClass('fa-chevron-right') toggleAdvanced: -> console.log @$('#advancedSearch') if @$('#advancedSearch').hasClass('hidden') @showAdvanced() else @hideAdvanced() changeDate: -> if @$('#date').val() == 'custom' SciRate.customDateRange (start, end) => @ranges.custom = @compileDateRange(start, end) if @ranges.custom == null @$('#date').val('any') @compileQuery() else @ranges.custom = null @compileQuery() escape: (s) -> if s.indexOf(' ') != -1 s = '(' + s + ')' s compileDateRange: (start, finish) -> if !start.isValid() && !finish.isValid() null else range = "" if start.isValid() then range += start.format('YYYY-MM-DD') range += '..' if finish.isValid() then range += finish.format('YYYY-MM-DD') range compileQuery: -> query = [] @$('#authors').val().split(/,\s*/).forEach (author) => return if author.length == 0 query.push("au:#{@escape(author)}") title = @$('#title').val() query.push("ti:#{@escape(title)}") if title.length > 0 abstract = @$('#abstract').val() query.push("abs:#{@escape(abstract)}") if abstract.length > 0 category = @$('#category').val() query.push("in:#{@escape(category)}") if category.length > 0 scited_by = @$('#scited_by').val() query.push("scited_by:#{@escape(scited_by)}") if scited_by.length > 0 date = @$('#date').val() if date != 'any' && @ranges[date]? query.push "date:#{@ranges[date]}" order = @$('#order').val() if order != "recency" query.push("order:#{order}") query_text = query.join(' ') $('input#advanced').val(query_text) $('#advancedPreview').text(@$('#q').val() + ' ' + query_text) $(document).on 'ready', -> $('#searchPage').each -> new View.Search(el: this) $(document).on 'page:load', -> $('#searchPage').each -> new View.Search(el: this)
[ { "context": "xtends LayerInfo\n @shouldParse: (key) -> key is 'PtFl'\n\n constructor: (layer, length) ->\n super(lay", "end": 178, "score": 0.9921600818634033, "start": 174, "tag": "KEY", "value": "PtFl" } ]
lib/psd/layer_info/pattern_fill.coffee
Keyang/psd.js
0
LayerInfo = require '../layer_info.coffee' Descriptor = require '../descriptor.coffee' module.exports = class PatternFill extends LayerInfo @shouldParse: (key) -> key is 'PtFl' constructor: (layer, length) -> super(layer, length) parse: -> @file.seek 4, true @data = new Descriptor(@file).parse()
60301
LayerInfo = require '../layer_info.coffee' Descriptor = require '../descriptor.coffee' module.exports = class PatternFill extends LayerInfo @shouldParse: (key) -> key is '<KEY>' constructor: (layer, length) -> super(layer, length) parse: -> @file.seek 4, true @data = new Descriptor(@file).parse()
true
LayerInfo = require '../layer_info.coffee' Descriptor = require '../descriptor.coffee' module.exports = class PatternFill extends LayerInfo @shouldParse: (key) -> key is 'PI:KEY:<KEY>END_PI' constructor: (layer, length) -> super(layer, length) parse: -> @file.seek 4, true @data = new Descriptor(@file).parse()
[ { "context": "ation:\n# process.env.HUBOT_ASGARD_URL or http://127.0.0.1/\n# process.env.HUBOT_ASGARD_REGION or us-east-1", "end": 221, "score": 0.9025506973266602, "start": 212, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "ardUrl = process.env.HUBOT_ASGARD_URL or 'http://127.0.0.1'\nregion = process.env.HUBOT_ASGARD_REGION or 'us-", "end": 1498, "score": 0.7606663703918457, "start": 1490, "tag": "IP_ADDRESS", "value": "27.0.0.1" } ]
scripts/asgard.coffee
danriti/hubot-asgard
0
# Description: # Asgard provides hubot commands for interfacing with a NetflixOSS # Asgard instance via API. # # Dependencies: # eco (>= 1.1.0) # # Configuration: # process.env.HUBOT_ASGARD_URL or http://127.0.0.1/ # process.env.HUBOT_ASGARD_REGION or us-east-1 # # Commands: # asgard ami - List AMIs per region (careful if public enabled) # asgard ami <id> - Show details for ami ID (ami-[a-f0-9]{8}) # asgard application - List applications per region # asgard autoscaling <name> - Show details for autoscaling group <name> # asgard autoscaling <name> <minSize> <maxSize - Change the min/max size for an ASG # asgard autoscaling (activate|deactive|delete) <name> - Enable, disable or delete an ASG # asgard cluster - List clusters per region # asgard cluster <name> - Show details for cluster <name> # asgard instance - List instances per region # asgard instance <app> - List instances per <app> per region # asgard instance <id> - Show details for instance <id> (i-[a-f0-9]{8}) # asgard loadbalancer - List loadbalancers per region # asgard region <region> - Get/set the asgard region # asgard rollingpush <asg> <ami> - Start a rolling push of <ami> into <asg> # asgard next <cluster> <ami> <true|false> - Create the next autoscaling group using <ami> with trafficEnabled true|false. # asgard task <id> - Show details for a given task # asgard url <url> - Get/set the asgard base url # # asgardUrl = process.env.HUBOT_ASGARD_URL or 'http://127.0.0.1' region = process.env.HUBOT_ASGARD_REGION or 'us-east-1' debug = process.env.HUBOT_ASGARD_DEBUG or false async = require "async" eco = require "eco" fs = require "fs" log = (event) -> if debug console.log event getBaseUrl = -> return asgardUrl + region + '/' getAsgardName = (name) -> asgardName = switch when name == 'ami' || name == 'a' then 'image' when name == 'app' then 'application' when name == 'autoscaling' || name == 'as' then 'autoScaling' when name == 'loadbalancer' || name == 'lb' then 'loadBalancer' when name == 'i' then 'instance' when name == 'c' then 'cluster' when name == 't' then 'task' else name return asgardName getTemplate = (templateItem) -> path = "/../templates/asgard-#{templateItem}.eco" return fs.readFileSync __dirname + path, "utf-8" asgardGetData = (msg, path, callback) -> msg.http(getBaseUrl() + path) .get() (err, res, body) -> log body callback null, JSON.parse(body) asgardPostData = (msg, path, params, callback) -> log 'curl -d "'+params+'" '+getBaseUrl() + path msg.http(getBaseUrl() + path) .headers("Accept": "*/*", "Content-Type": "application/x-www-form-urlencoded", "Content-Length": params.length) .post(params) (err, res, body) -> log res callback null, res asgardGet = (msg, path, templateItem) -> msg.http(getBaseUrl() + path) .get() (err, res, body) -> log JSON.parse(body) msg.send response JSON.parse(body), getTemplate templateItem asgardCreateTaskMsg = (msg, location, callback) -> taskId = location.substr(location.lastIndexOf("/")+1) msg.send "'asgard task #{taskId}' or " + getBaseUrl() + "task/show/#{taskId}" callback null, null response = (dataIn, template) -> return eco.render template, data: dataIn module.exports = (robot) -> robot.hear /^(asgard|a) (ami|a|instance|i|application|app|task|t)$/, (msg) -> item = getAsgardName msg.match[2] asgardGet msg, item + '/list.json', item robot.hear /^(asgard|a) (autoscaling|as|cluster|c|loadbalancer|lb)( ([\w\d-]+))?$/, (msg) -> path = tpl = getAsgardName msg.match[2] path += if msg.match[4] then "/show/#{msg.match[4]}.json" else '/list.json' asgardGet msg, path, tpl robot.hear /^(asgard|a) region( ([\w-]+))?$/, (msg) -> if msg.match[3] region = msg.match[3] robot.brain.set 'asgardRegion', region msg.send "Region is #{region}." # Ami robot.hear /^(asgard|a) (ami|a) (ami-[a-f0-9]{8})$/, (msg) -> item = getAsgardName msg.match[2] path = item + "/show/#msg.match[3]}.json" asgardGet msg, path, item # Instance APP (Eureka dependent) robot.hear /^(asgard|a) (instance|i) ([a-zA-Z0-9]+)$/, (msg) -> item = getAsgardName msg.match[2] path = item + "/list/#{msg.match[3]}.json" asgardGet msg, path, item # Instance ID robot.hear /^(asgard|a) (instance|i) (i-[a-f0-9]{8})$/, (msg) -> item = getAsgardName msg.match[2] path = item + "/show/#{msg.match[3]}.json" asgardGet msg, path, item # Task ID robot.hear /^(asgard|a) (task|t) ([\d]+)$/, (msg) -> item = getAsgardName msg.match[2] path = item + "/show/#{msg.match[3]}.json" asgardGet msg, path, item # Autoscaling group min-max update robot.hear /^(asgard|a) (autoscaling|as) ([\w\d-]+) ([\d]+) ([\d]+)$/, (msg) -> path = 'cluster/resize' params = "name=#{msg.match[3]}&minSize=#{msg.match[4]}&maxSize=#{msg.match[5]}" asgardPostData msg, path, params, (err, data) -> if data.statusCode == 302 asgardCreateTaskMsg msg, data.headers.location, (err, data) -> if err log err else msg.send "Oops: #{err}" robot.hear /^(asgard|a) url( (.*))?$/, (msg) -> if msg.match[3] asgardUrl = if (msg.match[3].slice(-1)) == '/' then msg.match[3] else "#{msg.match[3]}/" robot.brain.set 'asgardUrl', asgardUrl msg.send "URL is #{asgardUrl}." robot.hear /^(asgard|a) (rollingpush|rp) ([\w\d-]+) (ami-[a-f0-9]{8})$/, (msg) -> asg = msg.match[3] ami = msg.match[4] path = "autoScaling/show/#{asg}.json" async.waterfall [ (callback) -> asgardGetData msg, path, callback (data, callback) -> sg = "selectedSecurityGroups=" + data.launchConfiguration.securityGroups.join("&selectedSecurityGroups=") params = "name=#{asg}&appName=#{data.app.name}&imageId=#{ami}&instanceType=#{data.launchConfiguration.instanceType}&keyName=#{data.launchConfiguration.keyName}&#{sg}&relaunchCount=#{data.group.desiredCapacity}&concurrentRelaunches=1&newestFirst=false&checkHealth=on&afterBootWait=30" path = "push/startRolling" asgardPostData msg, path, params, callback (data, callback) -> if data.statusCode == 302 asgardCreateTaskMsg msg, data.headers.location, callback else callback "Unexpected result data: #{data}", null ], (err, result) -> if err console.log err robot.hear /^(asgard|a) (next) ([\w\d-]+) (ami-[a-f0-9]{8})( (true|false))?$/, (msg) -> cluster = msg.match[3] ami = msg.match[4] traffic = if (msg.match[6] && msg.match[6] == true) then "&trafficAllowed=true" else '' params = "name=#{cluster}&imageId=#{ami}&checkHealth=true#{traffic}" path = "cluster/createNextGroup" async.waterfall [ (callback) -> asgardPostData msg, path, params, callback (data, callback) -> if data.statusCode == 302 asgardCreateTaskMsg msg, data.headers.location, callback else callback "Unexpected result statusCode: #{data}", null ], (err, result) -> if err console.log err robot.hear /^(asgard|a) (autoscaling|as) (activate|deactivate|delete) ([\w\d-]+)$/, (msg) -> asg = msg.match[4] params = "name=#{asg}" path = "cluster/#{msg.match[3]}" async.waterfall [ (callback) -> asgardPostData msg, path, params, callback (data, callback) -> if data.statusCode == 302 asgardCreateTaskMsg msg, data.headers.location, callback else callback "Unexpected result statusCode: #{data}", null ], (err, result) -> if err console.log err
100147
# Description: # Asgard provides hubot commands for interfacing with a NetflixOSS # Asgard instance via API. # # Dependencies: # eco (>= 1.1.0) # # Configuration: # process.env.HUBOT_ASGARD_URL or http://127.0.0.1/ # process.env.HUBOT_ASGARD_REGION or us-east-1 # # Commands: # asgard ami - List AMIs per region (careful if public enabled) # asgard ami <id> - Show details for ami ID (ami-[a-f0-9]{8}) # asgard application - List applications per region # asgard autoscaling <name> - Show details for autoscaling group <name> # asgard autoscaling <name> <minSize> <maxSize - Change the min/max size for an ASG # asgard autoscaling (activate|deactive|delete) <name> - Enable, disable or delete an ASG # asgard cluster - List clusters per region # asgard cluster <name> - Show details for cluster <name> # asgard instance - List instances per region # asgard instance <app> - List instances per <app> per region # asgard instance <id> - Show details for instance <id> (i-[a-f0-9]{8}) # asgard loadbalancer - List loadbalancers per region # asgard region <region> - Get/set the asgard region # asgard rollingpush <asg> <ami> - Start a rolling push of <ami> into <asg> # asgard next <cluster> <ami> <true|false> - Create the next autoscaling group using <ami> with trafficEnabled true|false. # asgard task <id> - Show details for a given task # asgard url <url> - Get/set the asgard base url # # asgardUrl = process.env.HUBOT_ASGARD_URL or 'http://1172.16.58.3' region = process.env.HUBOT_ASGARD_REGION or 'us-east-1' debug = process.env.HUBOT_ASGARD_DEBUG or false async = require "async" eco = require "eco" fs = require "fs" log = (event) -> if debug console.log event getBaseUrl = -> return asgardUrl + region + '/' getAsgardName = (name) -> asgardName = switch when name == 'ami' || name == 'a' then 'image' when name == 'app' then 'application' when name == 'autoscaling' || name == 'as' then 'autoScaling' when name == 'loadbalancer' || name == 'lb' then 'loadBalancer' when name == 'i' then 'instance' when name == 'c' then 'cluster' when name == 't' then 'task' else name return asgardName getTemplate = (templateItem) -> path = "/../templates/asgard-#{templateItem}.eco" return fs.readFileSync __dirname + path, "utf-8" asgardGetData = (msg, path, callback) -> msg.http(getBaseUrl() + path) .get() (err, res, body) -> log body callback null, JSON.parse(body) asgardPostData = (msg, path, params, callback) -> log 'curl -d "'+params+'" '+getBaseUrl() + path msg.http(getBaseUrl() + path) .headers("Accept": "*/*", "Content-Type": "application/x-www-form-urlencoded", "Content-Length": params.length) .post(params) (err, res, body) -> log res callback null, res asgardGet = (msg, path, templateItem) -> msg.http(getBaseUrl() + path) .get() (err, res, body) -> log JSON.parse(body) msg.send response JSON.parse(body), getTemplate templateItem asgardCreateTaskMsg = (msg, location, callback) -> taskId = location.substr(location.lastIndexOf("/")+1) msg.send "'asgard task #{taskId}' or " + getBaseUrl() + "task/show/#{taskId}" callback null, null response = (dataIn, template) -> return eco.render template, data: dataIn module.exports = (robot) -> robot.hear /^(asgard|a) (ami|a|instance|i|application|app|task|t)$/, (msg) -> item = getAsgardName msg.match[2] asgardGet msg, item + '/list.json', item robot.hear /^(asgard|a) (autoscaling|as|cluster|c|loadbalancer|lb)( ([\w\d-]+))?$/, (msg) -> path = tpl = getAsgardName msg.match[2] path += if msg.match[4] then "/show/#{msg.match[4]}.json" else '/list.json' asgardGet msg, path, tpl robot.hear /^(asgard|a) region( ([\w-]+))?$/, (msg) -> if msg.match[3] region = msg.match[3] robot.brain.set 'asgardRegion', region msg.send "Region is #{region}." # Ami robot.hear /^(asgard|a) (ami|a) (ami-[a-f0-9]{8})$/, (msg) -> item = getAsgardName msg.match[2] path = item + "/show/#msg.match[3]}.json" asgardGet msg, path, item # Instance APP (Eureka dependent) robot.hear /^(asgard|a) (instance|i) ([a-zA-Z0-9]+)$/, (msg) -> item = getAsgardName msg.match[2] path = item + "/list/#{msg.match[3]}.json" asgardGet msg, path, item # Instance ID robot.hear /^(asgard|a) (instance|i) (i-[a-f0-9]{8})$/, (msg) -> item = getAsgardName msg.match[2] path = item + "/show/#{msg.match[3]}.json" asgardGet msg, path, item # Task ID robot.hear /^(asgard|a) (task|t) ([\d]+)$/, (msg) -> item = getAsgardName msg.match[2] path = item + "/show/#{msg.match[3]}.json" asgardGet msg, path, item # Autoscaling group min-max update robot.hear /^(asgard|a) (autoscaling|as) ([\w\d-]+) ([\d]+) ([\d]+)$/, (msg) -> path = 'cluster/resize' params = "name=#{msg.match[3]}&minSize=#{msg.match[4]}&maxSize=#{msg.match[5]}" asgardPostData msg, path, params, (err, data) -> if data.statusCode == 302 asgardCreateTaskMsg msg, data.headers.location, (err, data) -> if err log err else msg.send "Oops: #{err}" robot.hear /^(asgard|a) url( (.*))?$/, (msg) -> if msg.match[3] asgardUrl = if (msg.match[3].slice(-1)) == '/' then msg.match[3] else "#{msg.match[3]}/" robot.brain.set 'asgardUrl', asgardUrl msg.send "URL is #{asgardUrl}." robot.hear /^(asgard|a) (rollingpush|rp) ([\w\d-]+) (ami-[a-f0-9]{8})$/, (msg) -> asg = msg.match[3] ami = msg.match[4] path = "autoScaling/show/#{asg}.json" async.waterfall [ (callback) -> asgardGetData msg, path, callback (data, callback) -> sg = "selectedSecurityGroups=" + data.launchConfiguration.securityGroups.join("&selectedSecurityGroups=") params = "name=#{asg}&appName=#{data.app.name}&imageId=#{ami}&instanceType=#{data.launchConfiguration.instanceType}&keyName=#{data.launchConfiguration.keyName}&#{sg}&relaunchCount=#{data.group.desiredCapacity}&concurrentRelaunches=1&newestFirst=false&checkHealth=on&afterBootWait=30" path = "push/startRolling" asgardPostData msg, path, params, callback (data, callback) -> if data.statusCode == 302 asgardCreateTaskMsg msg, data.headers.location, callback else callback "Unexpected result data: #{data}", null ], (err, result) -> if err console.log err robot.hear /^(asgard|a) (next) ([\w\d-]+) (ami-[a-f0-9]{8})( (true|false))?$/, (msg) -> cluster = msg.match[3] ami = msg.match[4] traffic = if (msg.match[6] && msg.match[6] == true) then "&trafficAllowed=true" else '' params = "name=#{cluster}&imageId=#{ami}&checkHealth=true#{traffic}" path = "cluster/createNextGroup" async.waterfall [ (callback) -> asgardPostData msg, path, params, callback (data, callback) -> if data.statusCode == 302 asgardCreateTaskMsg msg, data.headers.location, callback else callback "Unexpected result statusCode: #{data}", null ], (err, result) -> if err console.log err robot.hear /^(asgard|a) (autoscaling|as) (activate|deactivate|delete) ([\w\d-]+)$/, (msg) -> asg = msg.match[4] params = "name=#{asg}" path = "cluster/#{msg.match[3]}" async.waterfall [ (callback) -> asgardPostData msg, path, params, callback (data, callback) -> if data.statusCode == 302 asgardCreateTaskMsg msg, data.headers.location, callback else callback "Unexpected result statusCode: #{data}", null ], (err, result) -> if err console.log err
true
# Description: # Asgard provides hubot commands for interfacing with a NetflixOSS # Asgard instance via API. # # Dependencies: # eco (>= 1.1.0) # # Configuration: # process.env.HUBOT_ASGARD_URL or http://127.0.0.1/ # process.env.HUBOT_ASGARD_REGION or us-east-1 # # Commands: # asgard ami - List AMIs per region (careful if public enabled) # asgard ami <id> - Show details for ami ID (ami-[a-f0-9]{8}) # asgard application - List applications per region # asgard autoscaling <name> - Show details for autoscaling group <name> # asgard autoscaling <name> <minSize> <maxSize - Change the min/max size for an ASG # asgard autoscaling (activate|deactive|delete) <name> - Enable, disable or delete an ASG # asgard cluster - List clusters per region # asgard cluster <name> - Show details for cluster <name> # asgard instance - List instances per region # asgard instance <app> - List instances per <app> per region # asgard instance <id> - Show details for instance <id> (i-[a-f0-9]{8}) # asgard loadbalancer - List loadbalancers per region # asgard region <region> - Get/set the asgard region # asgard rollingpush <asg> <ami> - Start a rolling push of <ami> into <asg> # asgard next <cluster> <ami> <true|false> - Create the next autoscaling group using <ami> with trafficEnabled true|false. # asgard task <id> - Show details for a given task # asgard url <url> - Get/set the asgard base url # # asgardUrl = process.env.HUBOT_ASGARD_URL or 'http://1PI:IP_ADDRESS:172.16.58.3END_PI' region = process.env.HUBOT_ASGARD_REGION or 'us-east-1' debug = process.env.HUBOT_ASGARD_DEBUG or false async = require "async" eco = require "eco" fs = require "fs" log = (event) -> if debug console.log event getBaseUrl = -> return asgardUrl + region + '/' getAsgardName = (name) -> asgardName = switch when name == 'ami' || name == 'a' then 'image' when name == 'app' then 'application' when name == 'autoscaling' || name == 'as' then 'autoScaling' when name == 'loadbalancer' || name == 'lb' then 'loadBalancer' when name == 'i' then 'instance' when name == 'c' then 'cluster' when name == 't' then 'task' else name return asgardName getTemplate = (templateItem) -> path = "/../templates/asgard-#{templateItem}.eco" return fs.readFileSync __dirname + path, "utf-8" asgardGetData = (msg, path, callback) -> msg.http(getBaseUrl() + path) .get() (err, res, body) -> log body callback null, JSON.parse(body) asgardPostData = (msg, path, params, callback) -> log 'curl -d "'+params+'" '+getBaseUrl() + path msg.http(getBaseUrl() + path) .headers("Accept": "*/*", "Content-Type": "application/x-www-form-urlencoded", "Content-Length": params.length) .post(params) (err, res, body) -> log res callback null, res asgardGet = (msg, path, templateItem) -> msg.http(getBaseUrl() + path) .get() (err, res, body) -> log JSON.parse(body) msg.send response JSON.parse(body), getTemplate templateItem asgardCreateTaskMsg = (msg, location, callback) -> taskId = location.substr(location.lastIndexOf("/")+1) msg.send "'asgard task #{taskId}' or " + getBaseUrl() + "task/show/#{taskId}" callback null, null response = (dataIn, template) -> return eco.render template, data: dataIn module.exports = (robot) -> robot.hear /^(asgard|a) (ami|a|instance|i|application|app|task|t)$/, (msg) -> item = getAsgardName msg.match[2] asgardGet msg, item + '/list.json', item robot.hear /^(asgard|a) (autoscaling|as|cluster|c|loadbalancer|lb)( ([\w\d-]+))?$/, (msg) -> path = tpl = getAsgardName msg.match[2] path += if msg.match[4] then "/show/#{msg.match[4]}.json" else '/list.json' asgardGet msg, path, tpl robot.hear /^(asgard|a) region( ([\w-]+))?$/, (msg) -> if msg.match[3] region = msg.match[3] robot.brain.set 'asgardRegion', region msg.send "Region is #{region}." # Ami robot.hear /^(asgard|a) (ami|a) (ami-[a-f0-9]{8})$/, (msg) -> item = getAsgardName msg.match[2] path = item + "/show/#msg.match[3]}.json" asgardGet msg, path, item # Instance APP (Eureka dependent) robot.hear /^(asgard|a) (instance|i) ([a-zA-Z0-9]+)$/, (msg) -> item = getAsgardName msg.match[2] path = item + "/list/#{msg.match[3]}.json" asgardGet msg, path, item # Instance ID robot.hear /^(asgard|a) (instance|i) (i-[a-f0-9]{8})$/, (msg) -> item = getAsgardName msg.match[2] path = item + "/show/#{msg.match[3]}.json" asgardGet msg, path, item # Task ID robot.hear /^(asgard|a) (task|t) ([\d]+)$/, (msg) -> item = getAsgardName msg.match[2] path = item + "/show/#{msg.match[3]}.json" asgardGet msg, path, item # Autoscaling group min-max update robot.hear /^(asgard|a) (autoscaling|as) ([\w\d-]+) ([\d]+) ([\d]+)$/, (msg) -> path = 'cluster/resize' params = "name=#{msg.match[3]}&minSize=#{msg.match[4]}&maxSize=#{msg.match[5]}" asgardPostData msg, path, params, (err, data) -> if data.statusCode == 302 asgardCreateTaskMsg msg, data.headers.location, (err, data) -> if err log err else msg.send "Oops: #{err}" robot.hear /^(asgard|a) url( (.*))?$/, (msg) -> if msg.match[3] asgardUrl = if (msg.match[3].slice(-1)) == '/' then msg.match[3] else "#{msg.match[3]}/" robot.brain.set 'asgardUrl', asgardUrl msg.send "URL is #{asgardUrl}." robot.hear /^(asgard|a) (rollingpush|rp) ([\w\d-]+) (ami-[a-f0-9]{8})$/, (msg) -> asg = msg.match[3] ami = msg.match[4] path = "autoScaling/show/#{asg}.json" async.waterfall [ (callback) -> asgardGetData msg, path, callback (data, callback) -> sg = "selectedSecurityGroups=" + data.launchConfiguration.securityGroups.join("&selectedSecurityGroups=") params = "name=#{asg}&appName=#{data.app.name}&imageId=#{ami}&instanceType=#{data.launchConfiguration.instanceType}&keyName=#{data.launchConfiguration.keyName}&#{sg}&relaunchCount=#{data.group.desiredCapacity}&concurrentRelaunches=1&newestFirst=false&checkHealth=on&afterBootWait=30" path = "push/startRolling" asgardPostData msg, path, params, callback (data, callback) -> if data.statusCode == 302 asgardCreateTaskMsg msg, data.headers.location, callback else callback "Unexpected result data: #{data}", null ], (err, result) -> if err console.log err robot.hear /^(asgard|a) (next) ([\w\d-]+) (ami-[a-f0-9]{8})( (true|false))?$/, (msg) -> cluster = msg.match[3] ami = msg.match[4] traffic = if (msg.match[6] && msg.match[6] == true) then "&trafficAllowed=true" else '' params = "name=#{cluster}&imageId=#{ami}&checkHealth=true#{traffic}" path = "cluster/createNextGroup" async.waterfall [ (callback) -> asgardPostData msg, path, params, callback (data, callback) -> if data.statusCode == 302 asgardCreateTaskMsg msg, data.headers.location, callback else callback "Unexpected result statusCode: #{data}", null ], (err, result) -> if err console.log err robot.hear /^(asgard|a) (autoscaling|as) (activate|deactivate|delete) ([\w\d-]+)$/, (msg) -> asg = msg.match[4] params = "name=#{asg}" path = "cluster/#{msg.match[3]}" async.waterfall [ (callback) -> asgardPostData msg, path, params, callback (data, callback) -> if data.statusCode == 302 asgardCreateTaskMsg msg, data.headers.location, callback else callback "Unexpected result statusCode: #{data}", null ], (err, result) -> if err console.log err
[ { "context": "\n return unless data.playId?\n\n data.key = impamp.pads.escapeKey(data.key)\n\n # Find the pad\n $page", "end": 693, "score": 0.5358166694641113, "start": 693, "tag": "KEY", "value": "" }, { "context": "turn unless data.playId?\n\n data.key = impamp.pads.escapeKey(data.key)\n\n # Find the pad\n $page = $(\"#page", "end": 705, "score": 0.5368890762329102, "start": 699, "tag": "KEY", "value": "escape" } ]
source/javascripts/collaboration.coffee
EdinburghUniversityTheatreCompany/ImpAmp
1
impamp = window.impamp impamp.collaboration = {} impamp.collaboration.colour = localStorage["collaboration.colour"] if localStorage? $ -> $colourInput = $('#colourBtn input') $colourInput.val(impamp.collaboration.colour) $colourInput.on "change", -> impamp.collaboration.colour = $colourInput.val() localStorage["collaboration.colour"] = impamp.collaboration.colour errorCount = 0 es = new EventSource('/c/stream') es.onerror = -> errorCount += 1 if errorCount > 10 # Give up. It's not happening. Probably because the server doesn't # support it. es.close() es.onmessage = (e) -> data = JSON.parse(e.data) return unless data.playId? data.key = impamp.pads.escapeKey(data.key) # Find the pad $page = $("#page_#{data.page}") $pad = $page.find(".pad [data-shortcut='#{data.key}']").closest(".pad") return if data.playId == $pad.data "playId" audioElement = $pad.find("audio")[0] $progress = $pad.find(".progress") $progress_bar = $pad.find(".progress .bar") switch data.type when "play", "timeupdate" if $(".now-playing-item[data-playId='#{data.playId.replace("\\", "\\\\")}']").length == 0 impamp.addNowCollaborating($pad, data.playId, data.colour) setTimeout( -> # If it doesn't get the stop message, fade out 5 seconds after it # was meant to. $progress.hide() impamp.removeNowCollaborating(data.playId) , (audioElement.duration + 5) * 1000) impamp.updateNowCollaborating($pad, data.playId, data.time) return unless audioElement.paused # Show the pad's progress bar in the remote colour if data.colour? bottomColour = data.colour topColour = impamp.increaseBrightness(data.colour) gradient = "linear-gradient(to bottom, #{topColour}, #{bottomColour})" $progress_bar.css("background-image", gradient) else $progress_bar.addClass "bar-grey" $progress.show() $progress_bar.css width: impamp.pads.getPercent($pad, audioElement, data.time) + "%" $progress_text = $pad.find(".progress > span") $progress_text.text impamp.pads.getRemaining($pad, audioElement, data.time) when "pause" impamp.removeNowCollaborating(data.playId) return unless audioElement.paused $progress.hide() impamp.collaboration.play = (page, key, playId, time) -> $.post "/c/play", page: page key: key playId: playId time: time colour: impamp.collaboration.colour lastUpdate = null impamp.collaboration.timeupdate = (page, key, playId, time) -> now = new Date() # Update max twice a second return if (now - lastUpdate) < 500 lastUpdate = now $.post "/c/timeupdate", page: page key: key playId: playId time: time colour: impamp.collaboration.colour impamp.collaboration.pause = (page, key, playId, time) -> $.post "/c/pause", page: page key: key playId: playId time: time colour: impamp.collaboration.colour
72903
impamp = window.impamp impamp.collaboration = {} impamp.collaboration.colour = localStorage["collaboration.colour"] if localStorage? $ -> $colourInput = $('#colourBtn input') $colourInput.val(impamp.collaboration.colour) $colourInput.on "change", -> impamp.collaboration.colour = $colourInput.val() localStorage["collaboration.colour"] = impamp.collaboration.colour errorCount = 0 es = new EventSource('/c/stream') es.onerror = -> errorCount += 1 if errorCount > 10 # Give up. It's not happening. Probably because the server doesn't # support it. es.close() es.onmessage = (e) -> data = JSON.parse(e.data) return unless data.playId? data.key = impamp<KEY>.pads.<KEY>Key(data.key) # Find the pad $page = $("#page_#{data.page}") $pad = $page.find(".pad [data-shortcut='#{data.key}']").closest(".pad") return if data.playId == $pad.data "playId" audioElement = $pad.find("audio")[0] $progress = $pad.find(".progress") $progress_bar = $pad.find(".progress .bar") switch data.type when "play", "timeupdate" if $(".now-playing-item[data-playId='#{data.playId.replace("\\", "\\\\")}']").length == 0 impamp.addNowCollaborating($pad, data.playId, data.colour) setTimeout( -> # If it doesn't get the stop message, fade out 5 seconds after it # was meant to. $progress.hide() impamp.removeNowCollaborating(data.playId) , (audioElement.duration + 5) * 1000) impamp.updateNowCollaborating($pad, data.playId, data.time) return unless audioElement.paused # Show the pad's progress bar in the remote colour if data.colour? bottomColour = data.colour topColour = impamp.increaseBrightness(data.colour) gradient = "linear-gradient(to bottom, #{topColour}, #{bottomColour})" $progress_bar.css("background-image", gradient) else $progress_bar.addClass "bar-grey" $progress.show() $progress_bar.css width: impamp.pads.getPercent($pad, audioElement, data.time) + "%" $progress_text = $pad.find(".progress > span") $progress_text.text impamp.pads.getRemaining($pad, audioElement, data.time) when "pause" impamp.removeNowCollaborating(data.playId) return unless audioElement.paused $progress.hide() impamp.collaboration.play = (page, key, playId, time) -> $.post "/c/play", page: page key: key playId: playId time: time colour: impamp.collaboration.colour lastUpdate = null impamp.collaboration.timeupdate = (page, key, playId, time) -> now = new Date() # Update max twice a second return if (now - lastUpdate) < 500 lastUpdate = now $.post "/c/timeupdate", page: page key: key playId: playId time: time colour: impamp.collaboration.colour impamp.collaboration.pause = (page, key, playId, time) -> $.post "/c/pause", page: page key: key playId: playId time: time colour: impamp.collaboration.colour
true
impamp = window.impamp impamp.collaboration = {} impamp.collaboration.colour = localStorage["collaboration.colour"] if localStorage? $ -> $colourInput = $('#colourBtn input') $colourInput.val(impamp.collaboration.colour) $colourInput.on "change", -> impamp.collaboration.colour = $colourInput.val() localStorage["collaboration.colour"] = impamp.collaboration.colour errorCount = 0 es = new EventSource('/c/stream') es.onerror = -> errorCount += 1 if errorCount > 10 # Give up. It's not happening. Probably because the server doesn't # support it. es.close() es.onmessage = (e) -> data = JSON.parse(e.data) return unless data.playId? data.key = impampPI:KEY:<KEY>END_PI.pads.PI:KEY:<KEY>END_PIKey(data.key) # Find the pad $page = $("#page_#{data.page}") $pad = $page.find(".pad [data-shortcut='#{data.key}']").closest(".pad") return if data.playId == $pad.data "playId" audioElement = $pad.find("audio")[0] $progress = $pad.find(".progress") $progress_bar = $pad.find(".progress .bar") switch data.type when "play", "timeupdate" if $(".now-playing-item[data-playId='#{data.playId.replace("\\", "\\\\")}']").length == 0 impamp.addNowCollaborating($pad, data.playId, data.colour) setTimeout( -> # If it doesn't get the stop message, fade out 5 seconds after it # was meant to. $progress.hide() impamp.removeNowCollaborating(data.playId) , (audioElement.duration + 5) * 1000) impamp.updateNowCollaborating($pad, data.playId, data.time) return unless audioElement.paused # Show the pad's progress bar in the remote colour if data.colour? bottomColour = data.colour topColour = impamp.increaseBrightness(data.colour) gradient = "linear-gradient(to bottom, #{topColour}, #{bottomColour})" $progress_bar.css("background-image", gradient) else $progress_bar.addClass "bar-grey" $progress.show() $progress_bar.css width: impamp.pads.getPercent($pad, audioElement, data.time) + "%" $progress_text = $pad.find(".progress > span") $progress_text.text impamp.pads.getRemaining($pad, audioElement, data.time) when "pause" impamp.removeNowCollaborating(data.playId) return unless audioElement.paused $progress.hide() impamp.collaboration.play = (page, key, playId, time) -> $.post "/c/play", page: page key: key playId: playId time: time colour: impamp.collaboration.colour lastUpdate = null impamp.collaboration.timeupdate = (page, key, playId, time) -> now = new Date() # Update max twice a second return if (now - lastUpdate) < 500 lastUpdate = now $.post "/c/timeupdate", page: page key: key playId: playId time: time colour: impamp.collaboration.colour impamp.collaboration.pause = (page, key, playId, time) -> $.post "/c/pause", page: page key: key playId: playId time: time colour: impamp.collaboration.colour
[ { "context": "ll send location header\n ## https://github.com/letsencrypt/boulder/issues/1135\n err = \"did not receive lo", "end": 1619, "score": 0.9990965723991394, "start": 1608, "tag": "USERNAME", "value": "letsencrypt" }, { "context": "ional = [\n {name: \"challengePassword\", value: password}\n {name: \"unstructuredName\", value: unstruct", "end": 6152, "score": 0.980300784111023, "start": 6144, "tag": "PASSWORD", "value": "password" } ]
src/models/letsencrypt.coffee
nextorigin/ten-ply-crest
21
Acme = require "rawacme" Keygen = require "rsa-keygen" Forge = require "node-forge" Flannel = require "flannel" errify = require "errify" class LetsEncrypt logPrefix: "(LetsEncrypt)" @intermediateCert: (callback) -> ideally = errify callback https = require "https" url = require "url" certurl = "https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem" data = [] await https.get (url.parse certurl), defer res res.on "data", (chunk) -> data.push chunk res.on "error", callback await res.on "end", ideally defer() binary = Buffer.concat data callback null, binary.toString() @createKeypair: (bit = 2048) -> result = Keygen.generate bit keypair = publicKey: result.public_key privateKey: result.private_key constructor: ({@keypair, @url, @Flannel}) -> @Flannel or= Flannel.init Console: level: "debug" @Flannel.shirt this @info "initializing" @url = Acme.LETSENCRYPT_URL if @url is "production" @url or= Acme.LETSENCRYPT_STAGING_URL setup: (callback) -> @info "setting up" ideally = errify callback await Acme.createClient {@url}, ideally defer @acme callback() createAccount: (emails, callback) -> @info "creating account for #{emails}" ideally = errify callback emails = [emails] unless Array.isArray emails mailto = ("mailto:#{email}" for email in emails) await @acme.newReg {contact: mailto}, @keypair, ideally defer {headers} ## might return 409 for a duplicate reg, but will still send location header ## https://github.com/letsencrypt/boulder/issues/1135 err = "did not receive location" unless location = headers.location callback err, location getReg: (location, body = {}, callback) -> ideally = errify callback body.resource = "reg" await @acme.post location, body, @keypair, ideally defer res callback null, res getAccount: (location, callback) -> @info "getting account for #{location}" ideally = errify callback await @getReg location, null, ideally defer {body} callback null, body getTosLink: (location, callback) -> @info "getting TOS link for #{location}" ideally = errify callback await @getReg location, null, ideally defer {headers} err = "did not receive link" unless link = headers.link ## comes in format: ## <http://...>; rel=next, <http://...>; rel=..., [next, tos] = link.split "," [str, rel] = tos.split ";" url = (str.split ";")[0].trim().replace /[<>]/g, "" callback err, url agreeToTos: (location, link, callback) -> @info "agreeing to tos at #{link}" @getReg location, {Agreement: link}, callback authorize: (domain, callback) -> @info "authorizing #{domain}" ideally = errify callback await @acme.newAuthz (@makeAuthRequest domain), @keypair, ideally defer {body, headers} return callback "did not receive location" unless location = headers.location {challenges} = body return callback "did not receive challenges" unless challenges preferred = "http-01" selected = challenge for challenge in challenges when challenge.type is preferred unless selected? then return callback "unable to select preferred challenge: #{preferred}" callback null, selected, location # selected has both token and uri makeAuthRequest: (domain) -> identifier: type: "dns" value: domain acceptChallenge: (challenge, callback) -> @info "accepting challenge to #{challenge.uri}" ideally = errify callback await @acme.post challenge.uri, (@makeChallengeResponse challenge), @keypair, ideally defer {body} callback null, body makeChallengeResponse: (challenge) -> LetsEncrypt.makeChallengeResponse challenge, @keypair makeKeyAuth: (challenge) -> LetsEncrypt.makeKeyAuth challenge, @keypair @makeChallengeResponse: (challenge, keypair) -> resource: "challenge" keyAuthorization: @makeKeyAuth challenge, keypair @makeKeyAuth: (challenge, keypair) -> Acme.keyAuthz challenge.token, keypair.publicKey waitForValidation: (location, callback) -> @info "waiting for validation from #{location}" ideally = errify callback getValidation = (multiplier = 1) => callback "retries exceeded" if multiplier > 128 @info "polling for validation from #{location}" await @acme.get location, @keypair, ideally defer {body} {status} = body? and body if status is "pending" return setTimeout (-> getValidation multiplier * 2), multiplier * 500 return callback (new Error status), body unless status is "valid" @info "validated #{location}" callback null, body getValidation() signedCsr: ({bit, key, domain, country, country_short, locality, organization, organization_short, password, unstructured, subject_alt_names}) -> if key privateKey = key else bit or= 2048 {publicKey, privateKey} = LetsEncrypt.createKeypair bit forge_privateKey = Forge.pki.privateKeyFromPem privateKey publicKey or= Forge.pki.publicKeyToPem Forge.pki.setRsaPublicKey forge_privateKey.n, forge_privateKey.e csr = @createCsr {publicKey, domain, country, country_short, locality, organization, organization_short, password, unstructured, subject_alt_names} csr.sign forge_privateKey csr.verify() {csr, publicKey, privateKey} createCsr: ({publicKey, domain, country, country_short, locality, organization, organization_short, password, unstructured, subject_alt_names}) -> csr = Forge.pki.createCertificationRequest() csr.publicKey = Forge.pki.publicKeyFromPem publicKey potential = [ {name: "commonName", value: domain}, {name: "countryName", value: country}, {shortName: "ST", value: country_short}, {name: "localityName", value: locality}, {name: "organizationName", value: organization}, {shortName: "OU", value: organization_short} ] actual = (pair for pair in potential when pair.value?) csr.setSubject actual optional = [ {name: "challengePassword", value: password} {name: "unstructuredName", value: unstructured} ] attributes = (pair for pair in optional when pair.value?) if subject_alt_names extensions = [ name: "subjectAltName" altNames: ({type: 2, value: alt_name} for alt_name in subject_alt_names) ] attributes.push {name: "extensionRequest", extensions} csr.setAttributes attributes if attributes.length csr requestSigning: (csr, domain, callback) -> @info "requesting signing for #{domain}" ideally = errify callback await @acme.newCert (@makeCertRequest csr, 90), @keypair, ideally defer {headers, body} err = "did not receive location" unless location = headers.location err = body if (status = body.status) and status >= 400 callback err, location makeCertRequest: (csr, days = 90) -> now = new Date later = new Date later.setDate now.getDate() + days csr: Acme.base64.encode Acme.toDer Forge.pki.certificationRequestToPem csr notBefore: now.toISOString() notAfter: later.toISOString() waitForCert: (location, callback) -> @info "waiting for cert from #{location}" ideally = errify callback getCert = (multiplier = 1) => callback "retries exceeded" if multiplier > 128 @info "polling for cert from #{location}" await @acme.get location, @keypair, ideally defer {body} unless body? return setTimeout (-> getCert multiplier * 2), multiplier * 500 cert = Acme.fromDer "CERTIFICATE", body @info "retrieved cert from #{location}" callback null, cert getCert() module.exports = LetsEncrypt
25369
Acme = require "rawacme" Keygen = require "rsa-keygen" Forge = require "node-forge" Flannel = require "flannel" errify = require "errify" class LetsEncrypt logPrefix: "(LetsEncrypt)" @intermediateCert: (callback) -> ideally = errify callback https = require "https" url = require "url" certurl = "https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem" data = [] await https.get (url.parse certurl), defer res res.on "data", (chunk) -> data.push chunk res.on "error", callback await res.on "end", ideally defer() binary = Buffer.concat data callback null, binary.toString() @createKeypair: (bit = 2048) -> result = Keygen.generate bit keypair = publicKey: result.public_key privateKey: result.private_key constructor: ({@keypair, @url, @Flannel}) -> @Flannel or= Flannel.init Console: level: "debug" @Flannel.shirt this @info "initializing" @url = Acme.LETSENCRYPT_URL if @url is "production" @url or= Acme.LETSENCRYPT_STAGING_URL setup: (callback) -> @info "setting up" ideally = errify callback await Acme.createClient {@url}, ideally defer @acme callback() createAccount: (emails, callback) -> @info "creating account for #{emails}" ideally = errify callback emails = [emails] unless Array.isArray emails mailto = ("mailto:#{email}" for email in emails) await @acme.newReg {contact: mailto}, @keypair, ideally defer {headers} ## might return 409 for a duplicate reg, but will still send location header ## https://github.com/letsencrypt/boulder/issues/1135 err = "did not receive location" unless location = headers.location callback err, location getReg: (location, body = {}, callback) -> ideally = errify callback body.resource = "reg" await @acme.post location, body, @keypair, ideally defer res callback null, res getAccount: (location, callback) -> @info "getting account for #{location}" ideally = errify callback await @getReg location, null, ideally defer {body} callback null, body getTosLink: (location, callback) -> @info "getting TOS link for #{location}" ideally = errify callback await @getReg location, null, ideally defer {headers} err = "did not receive link" unless link = headers.link ## comes in format: ## <http://...>; rel=next, <http://...>; rel=..., [next, tos] = link.split "," [str, rel] = tos.split ";" url = (str.split ";")[0].trim().replace /[<>]/g, "" callback err, url agreeToTos: (location, link, callback) -> @info "agreeing to tos at #{link}" @getReg location, {Agreement: link}, callback authorize: (domain, callback) -> @info "authorizing #{domain}" ideally = errify callback await @acme.newAuthz (@makeAuthRequest domain), @keypair, ideally defer {body, headers} return callback "did not receive location" unless location = headers.location {challenges} = body return callback "did not receive challenges" unless challenges preferred = "http-01" selected = challenge for challenge in challenges when challenge.type is preferred unless selected? then return callback "unable to select preferred challenge: #{preferred}" callback null, selected, location # selected has both token and uri makeAuthRequest: (domain) -> identifier: type: "dns" value: domain acceptChallenge: (challenge, callback) -> @info "accepting challenge to #{challenge.uri}" ideally = errify callback await @acme.post challenge.uri, (@makeChallengeResponse challenge), @keypair, ideally defer {body} callback null, body makeChallengeResponse: (challenge) -> LetsEncrypt.makeChallengeResponse challenge, @keypair makeKeyAuth: (challenge) -> LetsEncrypt.makeKeyAuth challenge, @keypair @makeChallengeResponse: (challenge, keypair) -> resource: "challenge" keyAuthorization: @makeKeyAuth challenge, keypair @makeKeyAuth: (challenge, keypair) -> Acme.keyAuthz challenge.token, keypair.publicKey waitForValidation: (location, callback) -> @info "waiting for validation from #{location}" ideally = errify callback getValidation = (multiplier = 1) => callback "retries exceeded" if multiplier > 128 @info "polling for validation from #{location}" await @acme.get location, @keypair, ideally defer {body} {status} = body? and body if status is "pending" return setTimeout (-> getValidation multiplier * 2), multiplier * 500 return callback (new Error status), body unless status is "valid" @info "validated #{location}" callback null, body getValidation() signedCsr: ({bit, key, domain, country, country_short, locality, organization, organization_short, password, unstructured, subject_alt_names}) -> if key privateKey = key else bit or= 2048 {publicKey, privateKey} = LetsEncrypt.createKeypair bit forge_privateKey = Forge.pki.privateKeyFromPem privateKey publicKey or= Forge.pki.publicKeyToPem Forge.pki.setRsaPublicKey forge_privateKey.n, forge_privateKey.e csr = @createCsr {publicKey, domain, country, country_short, locality, organization, organization_short, password, unstructured, subject_alt_names} csr.sign forge_privateKey csr.verify() {csr, publicKey, privateKey} createCsr: ({publicKey, domain, country, country_short, locality, organization, organization_short, password, unstructured, subject_alt_names}) -> csr = Forge.pki.createCertificationRequest() csr.publicKey = Forge.pki.publicKeyFromPem publicKey potential = [ {name: "commonName", value: domain}, {name: "countryName", value: country}, {shortName: "ST", value: country_short}, {name: "localityName", value: locality}, {name: "organizationName", value: organization}, {shortName: "OU", value: organization_short} ] actual = (pair for pair in potential when pair.value?) csr.setSubject actual optional = [ {name: "challengePassword", value: <PASSWORD>} {name: "unstructuredName", value: unstructured} ] attributes = (pair for pair in optional when pair.value?) if subject_alt_names extensions = [ name: "subjectAltName" altNames: ({type: 2, value: alt_name} for alt_name in subject_alt_names) ] attributes.push {name: "extensionRequest", extensions} csr.setAttributes attributes if attributes.length csr requestSigning: (csr, domain, callback) -> @info "requesting signing for #{domain}" ideally = errify callback await @acme.newCert (@makeCertRequest csr, 90), @keypair, ideally defer {headers, body} err = "did not receive location" unless location = headers.location err = body if (status = body.status) and status >= 400 callback err, location makeCertRequest: (csr, days = 90) -> now = new Date later = new Date later.setDate now.getDate() + days csr: Acme.base64.encode Acme.toDer Forge.pki.certificationRequestToPem csr notBefore: now.toISOString() notAfter: later.toISOString() waitForCert: (location, callback) -> @info "waiting for cert from #{location}" ideally = errify callback getCert = (multiplier = 1) => callback "retries exceeded" if multiplier > 128 @info "polling for cert from #{location}" await @acme.get location, @keypair, ideally defer {body} unless body? return setTimeout (-> getCert multiplier * 2), multiplier * 500 cert = Acme.fromDer "CERTIFICATE", body @info "retrieved cert from #{location}" callback null, cert getCert() module.exports = LetsEncrypt
true
Acme = require "rawacme" Keygen = require "rsa-keygen" Forge = require "node-forge" Flannel = require "flannel" errify = require "errify" class LetsEncrypt logPrefix: "(LetsEncrypt)" @intermediateCert: (callback) -> ideally = errify callback https = require "https" url = require "url" certurl = "https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem" data = [] await https.get (url.parse certurl), defer res res.on "data", (chunk) -> data.push chunk res.on "error", callback await res.on "end", ideally defer() binary = Buffer.concat data callback null, binary.toString() @createKeypair: (bit = 2048) -> result = Keygen.generate bit keypair = publicKey: result.public_key privateKey: result.private_key constructor: ({@keypair, @url, @Flannel}) -> @Flannel or= Flannel.init Console: level: "debug" @Flannel.shirt this @info "initializing" @url = Acme.LETSENCRYPT_URL if @url is "production" @url or= Acme.LETSENCRYPT_STAGING_URL setup: (callback) -> @info "setting up" ideally = errify callback await Acme.createClient {@url}, ideally defer @acme callback() createAccount: (emails, callback) -> @info "creating account for #{emails}" ideally = errify callback emails = [emails] unless Array.isArray emails mailto = ("mailto:#{email}" for email in emails) await @acme.newReg {contact: mailto}, @keypair, ideally defer {headers} ## might return 409 for a duplicate reg, but will still send location header ## https://github.com/letsencrypt/boulder/issues/1135 err = "did not receive location" unless location = headers.location callback err, location getReg: (location, body = {}, callback) -> ideally = errify callback body.resource = "reg" await @acme.post location, body, @keypair, ideally defer res callback null, res getAccount: (location, callback) -> @info "getting account for #{location}" ideally = errify callback await @getReg location, null, ideally defer {body} callback null, body getTosLink: (location, callback) -> @info "getting TOS link for #{location}" ideally = errify callback await @getReg location, null, ideally defer {headers} err = "did not receive link" unless link = headers.link ## comes in format: ## <http://...>; rel=next, <http://...>; rel=..., [next, tos] = link.split "," [str, rel] = tos.split ";" url = (str.split ";")[0].trim().replace /[<>]/g, "" callback err, url agreeToTos: (location, link, callback) -> @info "agreeing to tos at #{link}" @getReg location, {Agreement: link}, callback authorize: (domain, callback) -> @info "authorizing #{domain}" ideally = errify callback await @acme.newAuthz (@makeAuthRequest domain), @keypair, ideally defer {body, headers} return callback "did not receive location" unless location = headers.location {challenges} = body return callback "did not receive challenges" unless challenges preferred = "http-01" selected = challenge for challenge in challenges when challenge.type is preferred unless selected? then return callback "unable to select preferred challenge: #{preferred}" callback null, selected, location # selected has both token and uri makeAuthRequest: (domain) -> identifier: type: "dns" value: domain acceptChallenge: (challenge, callback) -> @info "accepting challenge to #{challenge.uri}" ideally = errify callback await @acme.post challenge.uri, (@makeChallengeResponse challenge), @keypair, ideally defer {body} callback null, body makeChallengeResponse: (challenge) -> LetsEncrypt.makeChallengeResponse challenge, @keypair makeKeyAuth: (challenge) -> LetsEncrypt.makeKeyAuth challenge, @keypair @makeChallengeResponse: (challenge, keypair) -> resource: "challenge" keyAuthorization: @makeKeyAuth challenge, keypair @makeKeyAuth: (challenge, keypair) -> Acme.keyAuthz challenge.token, keypair.publicKey waitForValidation: (location, callback) -> @info "waiting for validation from #{location}" ideally = errify callback getValidation = (multiplier = 1) => callback "retries exceeded" if multiplier > 128 @info "polling for validation from #{location}" await @acme.get location, @keypair, ideally defer {body} {status} = body? and body if status is "pending" return setTimeout (-> getValidation multiplier * 2), multiplier * 500 return callback (new Error status), body unless status is "valid" @info "validated #{location}" callback null, body getValidation() signedCsr: ({bit, key, domain, country, country_short, locality, organization, organization_short, password, unstructured, subject_alt_names}) -> if key privateKey = key else bit or= 2048 {publicKey, privateKey} = LetsEncrypt.createKeypair bit forge_privateKey = Forge.pki.privateKeyFromPem privateKey publicKey or= Forge.pki.publicKeyToPem Forge.pki.setRsaPublicKey forge_privateKey.n, forge_privateKey.e csr = @createCsr {publicKey, domain, country, country_short, locality, organization, organization_short, password, unstructured, subject_alt_names} csr.sign forge_privateKey csr.verify() {csr, publicKey, privateKey} createCsr: ({publicKey, domain, country, country_short, locality, organization, organization_short, password, unstructured, subject_alt_names}) -> csr = Forge.pki.createCertificationRequest() csr.publicKey = Forge.pki.publicKeyFromPem publicKey potential = [ {name: "commonName", value: domain}, {name: "countryName", value: country}, {shortName: "ST", value: country_short}, {name: "localityName", value: locality}, {name: "organizationName", value: organization}, {shortName: "OU", value: organization_short} ] actual = (pair for pair in potential when pair.value?) csr.setSubject actual optional = [ {name: "challengePassword", value: PI:PASSWORD:<PASSWORD>END_PI} {name: "unstructuredName", value: unstructured} ] attributes = (pair for pair in optional when pair.value?) if subject_alt_names extensions = [ name: "subjectAltName" altNames: ({type: 2, value: alt_name} for alt_name in subject_alt_names) ] attributes.push {name: "extensionRequest", extensions} csr.setAttributes attributes if attributes.length csr requestSigning: (csr, domain, callback) -> @info "requesting signing for #{domain}" ideally = errify callback await @acme.newCert (@makeCertRequest csr, 90), @keypair, ideally defer {headers, body} err = "did not receive location" unless location = headers.location err = body if (status = body.status) and status >= 400 callback err, location makeCertRequest: (csr, days = 90) -> now = new Date later = new Date later.setDate now.getDate() + days csr: Acme.base64.encode Acme.toDer Forge.pki.certificationRequestToPem csr notBefore: now.toISOString() notAfter: later.toISOString() waitForCert: (location, callback) -> @info "waiting for cert from #{location}" ideally = errify callback getCert = (multiplier = 1) => callback "retries exceeded" if multiplier > 128 @info "polling for cert from #{location}" await @acme.get location, @keypair, ideally defer {body} unless body? return setTimeout (-> getCert multiplier * 2), multiplier * 500 cert = Acme.fromDer "CERTIFICATE", body @info "retrieved cert from #{location}" callback null, cert getCert() module.exports = LetsEncrypt
[ { "context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http://o", "end": 67, "score": 0.8885626196861267, "start": 62, "tag": "NAME", "value": "Hatio" } ]
src/advice.coffee
heartyoh/dou
1
# ========================================== # Copyright 2014 Hatio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ './compose' ], (compose) -> "use strict" advice = around: (base, wrapped) -> -> # unpacking arguments by hand benchmarked faster l = arguments.length args = new Array(l + 1) args[0] = base.bind(this) args[i + 1] = arguments[i] for el, i in args wrapped.apply this, args before: (base, before) -> beforeFn = if typeof before == 'function' then before else before.obj[before.fnName] -> beforeFn.apply this, arguments base.apply this, arguments after: (base, after) -> afterFn = (if typeof after == 'function' then after else after.obj[after.fnName]) -> res = (base.unbound || base).apply(this, arguments) afterFn.apply this, arguments res # a mixin that allows other mixins to augment existing functions by adding additional # code before, after or around. withAdvice: -> ['before', 'after', 'around'].forEach (m) -> this[m] = (method, fn) -> compose.unlockProperty this, method, -> if(typeof this[method] is 'function') this[method] = advice[m] this[method], fn else this[method] = fn this[method] , this advice
48541
# ========================================== # Copyright 2014 <NAME>, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ './compose' ], (compose) -> "use strict" advice = around: (base, wrapped) -> -> # unpacking arguments by hand benchmarked faster l = arguments.length args = new Array(l + 1) args[0] = base.bind(this) args[i + 1] = arguments[i] for el, i in args wrapped.apply this, args before: (base, before) -> beforeFn = if typeof before == 'function' then before else before.obj[before.fnName] -> beforeFn.apply this, arguments base.apply this, arguments after: (base, after) -> afterFn = (if typeof after == 'function' then after else after.obj[after.fnName]) -> res = (base.unbound || base).apply(this, arguments) afterFn.apply this, arguments res # a mixin that allows other mixins to augment existing functions by adding additional # code before, after or around. withAdvice: -> ['before', 'after', 'around'].forEach (m) -> this[m] = (method, fn) -> compose.unlockProperty this, method, -> if(typeof this[method] is 'function') this[method] = advice[m] this[method], fn else this[method] = fn this[method] , this advice
true
# ========================================== # Copyright 2014 PI:NAME:<NAME>END_PI, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ './compose' ], (compose) -> "use strict" advice = around: (base, wrapped) -> -> # unpacking arguments by hand benchmarked faster l = arguments.length args = new Array(l + 1) args[0] = base.bind(this) args[i + 1] = arguments[i] for el, i in args wrapped.apply this, args before: (base, before) -> beforeFn = if typeof before == 'function' then before else before.obj[before.fnName] -> beforeFn.apply this, arguments base.apply this, arguments after: (base, after) -> afterFn = (if typeof after == 'function' then after else after.obj[after.fnName]) -> res = (base.unbound || base).apply(this, arguments) afterFn.apply this, arguments res # a mixin that allows other mixins to augment existing functions by adding additional # code before, after or around. withAdvice: -> ['before', 'after', 'around'].forEach (m) -> this[m] = (method, fn) -> compose.unlockProperty this, method, -> if(typeof this[method] is 'function') this[method] = advice[m] this[method], fn else this[method] = fn this[method] , this advice
[ { "context": "_KEY>'\n\ncio.identify '50b896ddc814556766000001', 'fab@bizzby.com', {created_at:new Date()}, (err, res) ->\n\n if er", "end": 158, "score": 0.9999216198921204, "start": 144, "tag": "EMAIL", "value": "fab@bizzby.com" } ]
example/identify.coffee
Bizzby/customer.io
1
Customerio = require '../src/Customerio' cio = new Customerio '<YOUR_SITE_ID>', '<YOUR_SECRET_KEY>' cio.identify '50b896ddc814556766000001', 'fab@bizzby.com', {created_at:new Date()}, (err, res) -> if err? console.log 'ERROR', err console.log 'response headers', res.headers console.log 'status code', res.statusCode
8547
Customerio = require '../src/Customerio' cio = new Customerio '<YOUR_SITE_ID>', '<YOUR_SECRET_KEY>' cio.identify '50b896ddc814556766000001', '<EMAIL>', {created_at:new Date()}, (err, res) -> if err? console.log 'ERROR', err console.log 'response headers', res.headers console.log 'status code', res.statusCode
true
Customerio = require '../src/Customerio' cio = new Customerio '<YOUR_SITE_ID>', '<YOUR_SECRET_KEY>' cio.identify '50b896ddc814556766000001', 'PI:EMAIL:<EMAIL>END_PI', {created_at:new Date()}, (err, res) -> if err? console.log 'ERROR', err console.log 'response headers', res.headers console.log 'status code', res.statusCode
[ { "context": "config.signerChain\r\n\t\t\t\trootCert = @CM.blankCert \"root@clearpathnet.com\",\"email:copy\",\"StormTracker Root Signer\", signerC", "end": 803, "score": 0.9999033212661743, "start": 782, "tag": "EMAIL", "value": "root@clearpathnet.com" } ]
src/http/certs.coffee
chandrashekharh/stormtracker
1
certainly = require("security/certainly") uuid = require("node-uuid") CertificateRegistry = require("security/certificate").CertificateRegistry auth = require("http/auth").authenticate util = require "util" class CertificateFactory constructor:(db)-> @db = db @CM = new CertificateManager __dirname+"/../../"+global.config.folders.config, global.config.folders.tmp,@db init: ()-> @db.on "ready",=> console.log "Finding the previously created signer chain "+global.config.stormsigner stormsigner = @db.get global.config.stormsigner console.log "Signer:"+ stormsigner if stormsigner? util.log "Signer chain already exists..skipping creation" return else signerChain = global.config.signerChain rootCert = @CM.blankCert "root@clearpathnet.com","email:copy","StormTracker Root Signer", signerChain.days,true,true rootCert.id= global.config.stormsigner @CM.create rootCert, (err,cert)-> util.log JSON.stringify err if err? util.log "Signer chain created" class CertificateManager constructor: (config,temp,db) -> certainly.init config, temp @db = db loadSigners: (cert) -> root = cert while root? root.signer = @db.get root.signer root = root.signer cert unloadSigners: (cert) -> root = cert while root.signer? acert = root.signer root.signer = acert.id root = acert cert get: (id) -> @db.get id list: () -> certs =[] @db.forEach (key,val)-> certs.push {"id":val.id,"subject": val.subject,"signer":val.signer} certs resolveSigners : (cert) -> certs = [cert] if not cert? return certs else signer = @db.get cert.signer if signer? certs = certs.concat(@resolveSigners(signer)) certs signerBundle : (id) -> cert = @db.get id if cert? cabundle = "" for c in @resolveSigners(cert) cabundle +=c.cert cabundle else return null blankCert : (email,SAN,CN,days,isCA,selfSigned) -> return certobj = "subject": "emailAddress": email "subjectAltName": SAN "nsComment": "UUID:"+uuid.v4() "pathlen": -1 "C": "US" "O": "ClearPath Networks" "OU": "VSP" "CA": isCA "CN": CN "L": "El Segundo" "ST": "CA" "daysValidFor": days "selfSigned": selfSigned "upstream" : false "downstream" : false signCSR: (csr, callback) -> certainly.signCSR csr, (err, cert) => return callback err if err? cert = @unloadSigners cert callback null, cert create: (cert,callback) -> if cert.selfSigned cert.signer="" console.log "Creating self signed cert" certainly.genCA cert, (err,cert) => return callback err if err? try @db.add cert.id,cert catch error callback error, null callback null,cert else console.log "Creating signed cert by "+cert.signer certainly.genKey cert,(err,ocert) => return callback err if err? ocert = @loadSigners ocert certainly.newCSR ocert,(err,csr) => return callback err if err? csr.signer = ocert.signer certainly.signCSR csr,(err,cert)=> return callback err if err? cert = @unloadSigners cert try @db.add cert.id, cert catch error callback error,null callback null, cert passport = require("passport") @include = -> CM = @settings.agent.CF.CM @post "/cert" : -> Response = @response CM.create @body, (err,cert)=> return @response.send 400,err if err? @response.send cert @get "/cert", auth, -> @send CM.list() @get "/cert/:id/signerBundle" : -> bundle = CM.signerBundle @params.id if not bundle? @send 404 return @response.set "ContentType","application/x-pem-file" @response.set "Content-Disposition", "attachment; filename=caBundle.pem" @send bundle @get "/cert/:id/publicKey" : -> cert = CM.get @params.id if cert? @response.set "ContentType","application/x-pem-file" @response.set "Content-Disposition", "attachment; filename=private.pem" @send cert.cert else @send 404 @get "/cert/:id/privateKey" : -> cert = CM.get @params.id if cert? @response.set "ContentType","application/x-pem-file" @response.set "Content-Disposition", "attachment; filename=private.pem" @send cert.privateKey else @send 404 @get "/cert/:id" : -> cert = CM.get @params.id if cert? @send cert else @send 404 exports.CertificateManager = CertificateManager exports.CertificateFactory = CertificateFactory
84572
certainly = require("security/certainly") uuid = require("node-uuid") CertificateRegistry = require("security/certificate").CertificateRegistry auth = require("http/auth").authenticate util = require "util" class CertificateFactory constructor:(db)-> @db = db @CM = new CertificateManager __dirname+"/../../"+global.config.folders.config, global.config.folders.tmp,@db init: ()-> @db.on "ready",=> console.log "Finding the previously created signer chain "+global.config.stormsigner stormsigner = @db.get global.config.stormsigner console.log "Signer:"+ stormsigner if stormsigner? util.log "Signer chain already exists..skipping creation" return else signerChain = global.config.signerChain rootCert = @CM.blankCert "<EMAIL>","email:copy","StormTracker Root Signer", signerChain.days,true,true rootCert.id= global.config.stormsigner @CM.create rootCert, (err,cert)-> util.log JSON.stringify err if err? util.log "Signer chain created" class CertificateManager constructor: (config,temp,db) -> certainly.init config, temp @db = db loadSigners: (cert) -> root = cert while root? root.signer = @db.get root.signer root = root.signer cert unloadSigners: (cert) -> root = cert while root.signer? acert = root.signer root.signer = acert.id root = acert cert get: (id) -> @db.get id list: () -> certs =[] @db.forEach (key,val)-> certs.push {"id":val.id,"subject": val.subject,"signer":val.signer} certs resolveSigners : (cert) -> certs = [cert] if not cert? return certs else signer = @db.get cert.signer if signer? certs = certs.concat(@resolveSigners(signer)) certs signerBundle : (id) -> cert = @db.get id if cert? cabundle = "" for c in @resolveSigners(cert) cabundle +=c.cert cabundle else return null blankCert : (email,SAN,CN,days,isCA,selfSigned) -> return certobj = "subject": "emailAddress": email "subjectAltName": SAN "nsComment": "UUID:"+uuid.v4() "pathlen": -1 "C": "US" "O": "ClearPath Networks" "OU": "VSP" "CA": isCA "CN": CN "L": "El Segundo" "ST": "CA" "daysValidFor": days "selfSigned": selfSigned "upstream" : false "downstream" : false signCSR: (csr, callback) -> certainly.signCSR csr, (err, cert) => return callback err if err? cert = @unloadSigners cert callback null, cert create: (cert,callback) -> if cert.selfSigned cert.signer="" console.log "Creating self signed cert" certainly.genCA cert, (err,cert) => return callback err if err? try @db.add cert.id,cert catch error callback error, null callback null,cert else console.log "Creating signed cert by "+cert.signer certainly.genKey cert,(err,ocert) => return callback err if err? ocert = @loadSigners ocert certainly.newCSR ocert,(err,csr) => return callback err if err? csr.signer = ocert.signer certainly.signCSR csr,(err,cert)=> return callback err if err? cert = @unloadSigners cert try @db.add cert.id, cert catch error callback error,null callback null, cert passport = require("passport") @include = -> CM = @settings.agent.CF.CM @post "/cert" : -> Response = @response CM.create @body, (err,cert)=> return @response.send 400,err if err? @response.send cert @get "/cert", auth, -> @send CM.list() @get "/cert/:id/signerBundle" : -> bundle = CM.signerBundle @params.id if not bundle? @send 404 return @response.set "ContentType","application/x-pem-file" @response.set "Content-Disposition", "attachment; filename=caBundle.pem" @send bundle @get "/cert/:id/publicKey" : -> cert = CM.get @params.id if cert? @response.set "ContentType","application/x-pem-file" @response.set "Content-Disposition", "attachment; filename=private.pem" @send cert.cert else @send 404 @get "/cert/:id/privateKey" : -> cert = CM.get @params.id if cert? @response.set "ContentType","application/x-pem-file" @response.set "Content-Disposition", "attachment; filename=private.pem" @send cert.privateKey else @send 404 @get "/cert/:id" : -> cert = CM.get @params.id if cert? @send cert else @send 404 exports.CertificateManager = CertificateManager exports.CertificateFactory = CertificateFactory
true
certainly = require("security/certainly") uuid = require("node-uuid") CertificateRegistry = require("security/certificate").CertificateRegistry auth = require("http/auth").authenticate util = require "util" class CertificateFactory constructor:(db)-> @db = db @CM = new CertificateManager __dirname+"/../../"+global.config.folders.config, global.config.folders.tmp,@db init: ()-> @db.on "ready",=> console.log "Finding the previously created signer chain "+global.config.stormsigner stormsigner = @db.get global.config.stormsigner console.log "Signer:"+ stormsigner if stormsigner? util.log "Signer chain already exists..skipping creation" return else signerChain = global.config.signerChain rootCert = @CM.blankCert "PI:EMAIL:<EMAIL>END_PI","email:copy","StormTracker Root Signer", signerChain.days,true,true rootCert.id= global.config.stormsigner @CM.create rootCert, (err,cert)-> util.log JSON.stringify err if err? util.log "Signer chain created" class CertificateManager constructor: (config,temp,db) -> certainly.init config, temp @db = db loadSigners: (cert) -> root = cert while root? root.signer = @db.get root.signer root = root.signer cert unloadSigners: (cert) -> root = cert while root.signer? acert = root.signer root.signer = acert.id root = acert cert get: (id) -> @db.get id list: () -> certs =[] @db.forEach (key,val)-> certs.push {"id":val.id,"subject": val.subject,"signer":val.signer} certs resolveSigners : (cert) -> certs = [cert] if not cert? return certs else signer = @db.get cert.signer if signer? certs = certs.concat(@resolveSigners(signer)) certs signerBundle : (id) -> cert = @db.get id if cert? cabundle = "" for c in @resolveSigners(cert) cabundle +=c.cert cabundle else return null blankCert : (email,SAN,CN,days,isCA,selfSigned) -> return certobj = "subject": "emailAddress": email "subjectAltName": SAN "nsComment": "UUID:"+uuid.v4() "pathlen": -1 "C": "US" "O": "ClearPath Networks" "OU": "VSP" "CA": isCA "CN": CN "L": "El Segundo" "ST": "CA" "daysValidFor": days "selfSigned": selfSigned "upstream" : false "downstream" : false signCSR: (csr, callback) -> certainly.signCSR csr, (err, cert) => return callback err if err? cert = @unloadSigners cert callback null, cert create: (cert,callback) -> if cert.selfSigned cert.signer="" console.log "Creating self signed cert" certainly.genCA cert, (err,cert) => return callback err if err? try @db.add cert.id,cert catch error callback error, null callback null,cert else console.log "Creating signed cert by "+cert.signer certainly.genKey cert,(err,ocert) => return callback err if err? ocert = @loadSigners ocert certainly.newCSR ocert,(err,csr) => return callback err if err? csr.signer = ocert.signer certainly.signCSR csr,(err,cert)=> return callback err if err? cert = @unloadSigners cert try @db.add cert.id, cert catch error callback error,null callback null, cert passport = require("passport") @include = -> CM = @settings.agent.CF.CM @post "/cert" : -> Response = @response CM.create @body, (err,cert)=> return @response.send 400,err if err? @response.send cert @get "/cert", auth, -> @send CM.list() @get "/cert/:id/signerBundle" : -> bundle = CM.signerBundle @params.id if not bundle? @send 404 return @response.set "ContentType","application/x-pem-file" @response.set "Content-Disposition", "attachment; filename=caBundle.pem" @send bundle @get "/cert/:id/publicKey" : -> cert = CM.get @params.id if cert? @response.set "ContentType","application/x-pem-file" @response.set "Content-Disposition", "attachment; filename=private.pem" @send cert.cert else @send 404 @get "/cert/:id/privateKey" : -> cert = CM.get @params.id if cert? @response.set "ContentType","application/x-pem-file" @response.set "Content-Disposition", "attachment; filename=private.pem" @send cert.privateKey else @send 404 @get "/cert/:id" : -> cert = CM.get @params.id if cert? @send cert else @send 404 exports.CertificateManager = CertificateManager exports.CertificateFactory = CertificateFactory
[ { "context": "sName in [\"header\", \"content\", \"actions\"]\n\t\t\tkey = \"_#{className}\"\n\t\t\tif @[key]?.length\n\t\t\t\t@_makeInternalDom(classN", "end": 592, "score": 0.9944722652435303, "start": 577, "tag": "KEY", "value": "\"_#{className}\"" } ]
test/src/widget/layout/modal.coffee
AlexTong/grunt-dorado-build
0
class dorado.Modal extends dorado.Widget @CLASS_NAME: "modal" @ATTRIBUTES: context: null header: setter: (value)-> @_serInternal(value, "header") return @ content: setter: (value)-> @_serInternal(value, "content") return @ actions: setter: (value)-> @_serInternal(value, "actions") return @ @EVENTS: onShow: null onVisible: null onHide: null onHidden: null onApprove: null onDeny: null _setDom: (dom, parseChild)-> super(dom, parseChild) @_doms ?= {} for className in ["header", "content", "actions"] key = "_#{className}" if @[key]?.length @_makeInternalDom(className) unless @_doms[className] @_render(el, className) for el in @[key] fireEvent = (eventName)=> arg = event: window.event @fire(eventName, @, arg) settings = { closable: false onShow: ()-> fireEvent("onShow") onVisible: ()-> fireEvent("onVisible") onHide: ()-> fireEvent("onHide") onHidden: ()-> fireEvent("onHidden") onApprove: ()-> fireEvent("onApprove") return false onDeny: ()-> fireEvent("onDeny") return false } settings.context = $(@_context) if @_context @get$Dom().modal(settings) return _parseElement: (element)-> result = null if typeof element == "string" result = $.xCreate({ tagName: "SPAN" content: element }) else if element.constructor == Object.prototype.constructor and element.$type widget = dorado.widget(element) result = widget else if element instanceof dorado.Widget result = element else result = $.xCreate(element) return result _clearInternal: (target)-> old = @["_#{target}"] if old for el in old el.destroy() if el instanceof dorado.widget @["_#{target}"] = [] @_doms ?= {} $(@_doms[target]).empty()if @_doms[target] return _serInternal: (value, target)-> @_clearInternal(target) if value instanceof Array for el in value result = @_parseElement(el) @_addInternalElement(result, target) if result else result = @_parseElement(el) @_addInternalElement(result, target) if result return _makeInternalDom: (target)-> @_doms ?= {} dom = document.createElement("div") dom.className = target if target is "content" if @_doms["actions"] $(@_doms["actions"]).before(dom) else @_dom.appendChild(dom) else if target is "header" afterEl = @_doms["content"] || @_doms["actions"] if afterEl $(afterEl).before(dom) else @_dom.appendChild(dom) else @_dom.appendChild(dom) @_doms[target] = dom return dom _addInternalElement: (element, target)-> name = "_#{target}" @[name] ?= [] targetList = @[name] dom = null if element instanceof dorado.Widget targetList.push(element) dom = element.getDom() if @_dom else if element.nodeType == 1 targetList.push(element) dom = element @_render(dom, target) if dom and @_dom return _render: (node, target)-> @_doms ?= {} @_makeInternalDom(target) unless @_doms[target] dom = node if node instanceof dorado.Widget dom = node.getDom() @_doms[target].appendChild(dom) if dom.parentNode isnt @_doms[target] return _parseDom: (dom)-> @_doms ?= {} _parseChild = (node, target)=> childNode = node.firstChild while childNode if childNode.nodeType == 1 widget = dorado.widget(childNode) @_addInternalElement(widget or childNode, target) childNode = childNode.nextSibling return child = dom.firstChild while child if child.nodeType == 1 if child.nodeName is "I" @_doms.icon = child @_icon ?= child.className else $child = $(child) for className in ["header", "content", "actions"] continue unless $child.hasClass(className) @_doms[className] = child _parseChild(child, className) break child = child.nextSibling return show: ()-> @get$Dom().modal("show") return @ hide: ()-> @get$Dom().modal("hide") return @ setContext: (selector)-> @get$Dom().modal("setting context", $(selector)) return @
66338
class dorado.Modal extends dorado.Widget @CLASS_NAME: "modal" @ATTRIBUTES: context: null header: setter: (value)-> @_serInternal(value, "header") return @ content: setter: (value)-> @_serInternal(value, "content") return @ actions: setter: (value)-> @_serInternal(value, "actions") return @ @EVENTS: onShow: null onVisible: null onHide: null onHidden: null onApprove: null onDeny: null _setDom: (dom, parseChild)-> super(dom, parseChild) @_doms ?= {} for className in ["header", "content", "actions"] key = <KEY> if @[key]?.length @_makeInternalDom(className) unless @_doms[className] @_render(el, className) for el in @[key] fireEvent = (eventName)=> arg = event: window.event @fire(eventName, @, arg) settings = { closable: false onShow: ()-> fireEvent("onShow") onVisible: ()-> fireEvent("onVisible") onHide: ()-> fireEvent("onHide") onHidden: ()-> fireEvent("onHidden") onApprove: ()-> fireEvent("onApprove") return false onDeny: ()-> fireEvent("onDeny") return false } settings.context = $(@_context) if @_context @get$Dom().modal(settings) return _parseElement: (element)-> result = null if typeof element == "string" result = $.xCreate({ tagName: "SPAN" content: element }) else if element.constructor == Object.prototype.constructor and element.$type widget = dorado.widget(element) result = widget else if element instanceof dorado.Widget result = element else result = $.xCreate(element) return result _clearInternal: (target)-> old = @["_#{target}"] if old for el in old el.destroy() if el instanceof dorado.widget @["_#{target}"] = [] @_doms ?= {} $(@_doms[target]).empty()if @_doms[target] return _serInternal: (value, target)-> @_clearInternal(target) if value instanceof Array for el in value result = @_parseElement(el) @_addInternalElement(result, target) if result else result = @_parseElement(el) @_addInternalElement(result, target) if result return _makeInternalDom: (target)-> @_doms ?= {} dom = document.createElement("div") dom.className = target if target is "content" if @_doms["actions"] $(@_doms["actions"]).before(dom) else @_dom.appendChild(dom) else if target is "header" afterEl = @_doms["content"] || @_doms["actions"] if afterEl $(afterEl).before(dom) else @_dom.appendChild(dom) else @_dom.appendChild(dom) @_doms[target] = dom return dom _addInternalElement: (element, target)-> name = "_#{target}" @[name] ?= [] targetList = @[name] dom = null if element instanceof dorado.Widget targetList.push(element) dom = element.getDom() if @_dom else if element.nodeType == 1 targetList.push(element) dom = element @_render(dom, target) if dom and @_dom return _render: (node, target)-> @_doms ?= {} @_makeInternalDom(target) unless @_doms[target] dom = node if node instanceof dorado.Widget dom = node.getDom() @_doms[target].appendChild(dom) if dom.parentNode isnt @_doms[target] return _parseDom: (dom)-> @_doms ?= {} _parseChild = (node, target)=> childNode = node.firstChild while childNode if childNode.nodeType == 1 widget = dorado.widget(childNode) @_addInternalElement(widget or childNode, target) childNode = childNode.nextSibling return child = dom.firstChild while child if child.nodeType == 1 if child.nodeName is "I" @_doms.icon = child @_icon ?= child.className else $child = $(child) for className in ["header", "content", "actions"] continue unless $child.hasClass(className) @_doms[className] = child _parseChild(child, className) break child = child.nextSibling return show: ()-> @get$Dom().modal("show") return @ hide: ()-> @get$Dom().modal("hide") return @ setContext: (selector)-> @get$Dom().modal("setting context", $(selector)) return @
true
class dorado.Modal extends dorado.Widget @CLASS_NAME: "modal" @ATTRIBUTES: context: null header: setter: (value)-> @_serInternal(value, "header") return @ content: setter: (value)-> @_serInternal(value, "content") return @ actions: setter: (value)-> @_serInternal(value, "actions") return @ @EVENTS: onShow: null onVisible: null onHide: null onHidden: null onApprove: null onDeny: null _setDom: (dom, parseChild)-> super(dom, parseChild) @_doms ?= {} for className in ["header", "content", "actions"] key = PI:KEY:<KEY>END_PI if @[key]?.length @_makeInternalDom(className) unless @_doms[className] @_render(el, className) for el in @[key] fireEvent = (eventName)=> arg = event: window.event @fire(eventName, @, arg) settings = { closable: false onShow: ()-> fireEvent("onShow") onVisible: ()-> fireEvent("onVisible") onHide: ()-> fireEvent("onHide") onHidden: ()-> fireEvent("onHidden") onApprove: ()-> fireEvent("onApprove") return false onDeny: ()-> fireEvent("onDeny") return false } settings.context = $(@_context) if @_context @get$Dom().modal(settings) return _parseElement: (element)-> result = null if typeof element == "string" result = $.xCreate({ tagName: "SPAN" content: element }) else if element.constructor == Object.prototype.constructor and element.$type widget = dorado.widget(element) result = widget else if element instanceof dorado.Widget result = element else result = $.xCreate(element) return result _clearInternal: (target)-> old = @["_#{target}"] if old for el in old el.destroy() if el instanceof dorado.widget @["_#{target}"] = [] @_doms ?= {} $(@_doms[target]).empty()if @_doms[target] return _serInternal: (value, target)-> @_clearInternal(target) if value instanceof Array for el in value result = @_parseElement(el) @_addInternalElement(result, target) if result else result = @_parseElement(el) @_addInternalElement(result, target) if result return _makeInternalDom: (target)-> @_doms ?= {} dom = document.createElement("div") dom.className = target if target is "content" if @_doms["actions"] $(@_doms["actions"]).before(dom) else @_dom.appendChild(dom) else if target is "header" afterEl = @_doms["content"] || @_doms["actions"] if afterEl $(afterEl).before(dom) else @_dom.appendChild(dom) else @_dom.appendChild(dom) @_doms[target] = dom return dom _addInternalElement: (element, target)-> name = "_#{target}" @[name] ?= [] targetList = @[name] dom = null if element instanceof dorado.Widget targetList.push(element) dom = element.getDom() if @_dom else if element.nodeType == 1 targetList.push(element) dom = element @_render(dom, target) if dom and @_dom return _render: (node, target)-> @_doms ?= {} @_makeInternalDom(target) unless @_doms[target] dom = node if node instanceof dorado.Widget dom = node.getDom() @_doms[target].appendChild(dom) if dom.parentNode isnt @_doms[target] return _parseDom: (dom)-> @_doms ?= {} _parseChild = (node, target)=> childNode = node.firstChild while childNode if childNode.nodeType == 1 widget = dorado.widget(childNode) @_addInternalElement(widget or childNode, target) childNode = childNode.nextSibling return child = dom.firstChild while child if child.nodeType == 1 if child.nodeName is "I" @_doms.icon = child @_icon ?= child.className else $child = $(child) for className in ["header", "content", "actions"] continue unless $child.hasClass(className) @_doms[className] = child _parseChild(child, className) break child = child.nextSibling return show: ()-> @get$Dom().modal("show") return @ hide: ()-> @get$Dom().modal("hide") return @ setContext: (selector)-> @get$Dom().modal("setting context", $(selector)) return @
[ { "context": " 2e3\n result.body.should.equal \"King's Landing\"\n result._id.toString().should.equal someM", "end": 5827, "score": 0.564323365688324, "start": 5824, "tag": "NAME", "value": "ing" } ]
test/submodel.coffee
OpenCubes/Nap
1
chai = require('chai') should = chai.should() chai.use(require('chai-things')) index = require('../index') mongoose = require("mongoose-q")() SubModel = require "../src/submodel" Model = require "../src/model" Q = require "q" _ = require "lodash" mongoose.model "Ticket", { title: String body: String likes: Number comments: [{ body: String upvotes: Number downvotes: Number }] } Comment = new SubModel model: mongoose.model "Ticket" collection: "tickets" location: "comments" paths: ['body','upvotes','downvotes'] link: "ticket" Ticket = new Model model: mongoose.model "Ticket" collection: "tickets" likes: "Number" user = {} someModel = undefined mongoose.connection.collections.users.drop -> mongoose.connection.collections.stories.drop -> FS = require("q-io/fs") aTicket = {} describe 'SubModel', -> it 'is a constructor ', -> Model.should.be.a 'function' it 'can mount fixtures', (done) -> FS.read('test/fixtures03.json').then (data) -> fixtures = JSON.parse data promises = [] for fixture in fixtures.tickets promises.push Ticket.create fixture Q.allSettled promises .then -> done() .fail done describe "#find()", -> before (done) -> Ticket.find(likes: 42).then (tickets) -> aTicket = tickets[0] done() .fail done it 'supports no parameter', (done) -> @timeout 5000 Comment.find(ticket: aTicket._id , true, user).then (comments) -> comments.should.have.length 2 done() .fail done it 'supports `sort` parameter', (done) -> Comment.find(sort: "upvotes", ticket: aTicket._id, true, user).then (comments) -> oldUpvotes = 0 for comment in comments oldUpvotes.should.be.at.most comment.upvotes oldUpvotes = comment.upvotes done() .fail done it 'supports `limit` parameter', (done) -> Comment.find(limit: 1, ticket: aTicket._id, true, user).then (stories)-> stories.should.have.length 1 done() .fail done it 'supports `skip` parameter', (done) -> Comment.find(offset: 1, ticket: aTicket._id, true, user).then (stories)-> stories.should.have.length 1 done() .fail done it 'supports `select` parameter', (done) -> Comment.find(select: 'upvotes', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 2 for comment in comments should.not.exist comment.title should.not.exist comment.downvotes should.exist comment.upvotes Comment.find(select: '-upvotes', ticket: aTicket._id) .then (comments)-> comments.should.have.length 2 for comment in comments should.exist comment.body should.exist comment.downvotes should.not.exist comment.upvotes done() .fail done describe 'where', -> it 'supports `=`', (done) -> Comment.find(upvotes: '2', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 comments.should.all.have.property 'upvotes', 2 done() .fail done it 'supports `<`', (done) -> Comment.find(upvotes: '<3', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 for comment in comments comment.upvotes.should.be.below 3 done() .fail done it 'supports `<=`', (done) -> Comment.find(upvotes: '<=2', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 for comment in comments comment.upvotes.should.be.most 2 done() .fail done it 'supports `>`', (done) -> Comment.find(upvotes: '>3', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 for comment in comments comment.upvotes.should.be.above 3 done() .fail done it 'supports `>=`', (done) -> Comment.find(upvotes: '>=5', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 for comment in comments comment.upvotes.should.be.least 5 someModel = comments[0] done() .fail done describe '#findById()', -> it 'supports finding one doc', (done) -> Comment.findById(someModel._id, true , user).then (other) -> someModel._id = someModel._id?.toString() other.should.deep.equal someModel done() .fail done # it 'supports finding one doc with `select`', (done) -> # # Comment.findById(someModel._id, select: 'upvotes').then (other) -> # should.not.exist other.downvotes # should.not.exist other.body # done() # .fail done describe '#create()', -> it 'can create a submodel', (done) -> props = body: "This is a long bodddddyyyyyyyyyyyy" upvotes: 2e5 downvotes: 2e2 ticket: aTicket._id Comment.create(props, true, user).then (comment) -> someModel = _.clone comment delete comment._id delete props.ticket comment.should.deep.equal props done() .fail done describe '#set()' ,-> it 'can set some properties', (done) -> Comment.set(someModel._id, upvotes: 2e3 body: "King's Landing" , true, user).then (result) -> result.upvotes.should.equal 2e3 result.body.should.equal "King's Landing" result._id.toString().should.equal someModel._id.toString() Comment.findById someModel._id, true, user .then (result) -> result.upvotes.should.equal 2e3 result.body.should.equal "King's Landing" result._id.toString().should.equal someModel._id.toString() done() .fail done describe '#delete()', -> it 'can delete a comment', (done) -> Comment.delete(someModel._id, true, user).then -> Comment.findById someModel._id .then (comment) -> comment.should.deep.equal {} done() .fail done
44552
chai = require('chai') should = chai.should() chai.use(require('chai-things')) index = require('../index') mongoose = require("mongoose-q")() SubModel = require "../src/submodel" Model = require "../src/model" Q = require "q" _ = require "lodash" mongoose.model "Ticket", { title: String body: String likes: Number comments: [{ body: String upvotes: Number downvotes: Number }] } Comment = new SubModel model: mongoose.model "Ticket" collection: "tickets" location: "comments" paths: ['body','upvotes','downvotes'] link: "ticket" Ticket = new Model model: mongoose.model "Ticket" collection: "tickets" likes: "Number" user = {} someModel = undefined mongoose.connection.collections.users.drop -> mongoose.connection.collections.stories.drop -> FS = require("q-io/fs") aTicket = {} describe 'SubModel', -> it 'is a constructor ', -> Model.should.be.a 'function' it 'can mount fixtures', (done) -> FS.read('test/fixtures03.json').then (data) -> fixtures = JSON.parse data promises = [] for fixture in fixtures.tickets promises.push Ticket.create fixture Q.allSettled promises .then -> done() .fail done describe "#find()", -> before (done) -> Ticket.find(likes: 42).then (tickets) -> aTicket = tickets[0] done() .fail done it 'supports no parameter', (done) -> @timeout 5000 Comment.find(ticket: aTicket._id , true, user).then (comments) -> comments.should.have.length 2 done() .fail done it 'supports `sort` parameter', (done) -> Comment.find(sort: "upvotes", ticket: aTicket._id, true, user).then (comments) -> oldUpvotes = 0 for comment in comments oldUpvotes.should.be.at.most comment.upvotes oldUpvotes = comment.upvotes done() .fail done it 'supports `limit` parameter', (done) -> Comment.find(limit: 1, ticket: aTicket._id, true, user).then (stories)-> stories.should.have.length 1 done() .fail done it 'supports `skip` parameter', (done) -> Comment.find(offset: 1, ticket: aTicket._id, true, user).then (stories)-> stories.should.have.length 1 done() .fail done it 'supports `select` parameter', (done) -> Comment.find(select: 'upvotes', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 2 for comment in comments should.not.exist comment.title should.not.exist comment.downvotes should.exist comment.upvotes Comment.find(select: '-upvotes', ticket: aTicket._id) .then (comments)-> comments.should.have.length 2 for comment in comments should.exist comment.body should.exist comment.downvotes should.not.exist comment.upvotes done() .fail done describe 'where', -> it 'supports `=`', (done) -> Comment.find(upvotes: '2', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 comments.should.all.have.property 'upvotes', 2 done() .fail done it 'supports `<`', (done) -> Comment.find(upvotes: '<3', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 for comment in comments comment.upvotes.should.be.below 3 done() .fail done it 'supports `<=`', (done) -> Comment.find(upvotes: '<=2', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 for comment in comments comment.upvotes.should.be.most 2 done() .fail done it 'supports `>`', (done) -> Comment.find(upvotes: '>3', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 for comment in comments comment.upvotes.should.be.above 3 done() .fail done it 'supports `>=`', (done) -> Comment.find(upvotes: '>=5', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 for comment in comments comment.upvotes.should.be.least 5 someModel = comments[0] done() .fail done describe '#findById()', -> it 'supports finding one doc', (done) -> Comment.findById(someModel._id, true , user).then (other) -> someModel._id = someModel._id?.toString() other.should.deep.equal someModel done() .fail done # it 'supports finding one doc with `select`', (done) -> # # Comment.findById(someModel._id, select: 'upvotes').then (other) -> # should.not.exist other.downvotes # should.not.exist other.body # done() # .fail done describe '#create()', -> it 'can create a submodel', (done) -> props = body: "This is a long bodddddyyyyyyyyyyyy" upvotes: 2e5 downvotes: 2e2 ticket: aTicket._id Comment.create(props, true, user).then (comment) -> someModel = _.clone comment delete comment._id delete props.ticket comment.should.deep.equal props done() .fail done describe '#set()' ,-> it 'can set some properties', (done) -> Comment.set(someModel._id, upvotes: 2e3 body: "King's Landing" , true, user).then (result) -> result.upvotes.should.equal 2e3 result.body.should.equal "King's Landing" result._id.toString().should.equal someModel._id.toString() Comment.findById someModel._id, true, user .then (result) -> result.upvotes.should.equal 2e3 result.body.should.equal "King's Land<NAME>" result._id.toString().should.equal someModel._id.toString() done() .fail done describe '#delete()', -> it 'can delete a comment', (done) -> Comment.delete(someModel._id, true, user).then -> Comment.findById someModel._id .then (comment) -> comment.should.deep.equal {} done() .fail done
true
chai = require('chai') should = chai.should() chai.use(require('chai-things')) index = require('../index') mongoose = require("mongoose-q")() SubModel = require "../src/submodel" Model = require "../src/model" Q = require "q" _ = require "lodash" mongoose.model "Ticket", { title: String body: String likes: Number comments: [{ body: String upvotes: Number downvotes: Number }] } Comment = new SubModel model: mongoose.model "Ticket" collection: "tickets" location: "comments" paths: ['body','upvotes','downvotes'] link: "ticket" Ticket = new Model model: mongoose.model "Ticket" collection: "tickets" likes: "Number" user = {} someModel = undefined mongoose.connection.collections.users.drop -> mongoose.connection.collections.stories.drop -> FS = require("q-io/fs") aTicket = {} describe 'SubModel', -> it 'is a constructor ', -> Model.should.be.a 'function' it 'can mount fixtures', (done) -> FS.read('test/fixtures03.json').then (data) -> fixtures = JSON.parse data promises = [] for fixture in fixtures.tickets promises.push Ticket.create fixture Q.allSettled promises .then -> done() .fail done describe "#find()", -> before (done) -> Ticket.find(likes: 42).then (tickets) -> aTicket = tickets[0] done() .fail done it 'supports no parameter', (done) -> @timeout 5000 Comment.find(ticket: aTicket._id , true, user).then (comments) -> comments.should.have.length 2 done() .fail done it 'supports `sort` parameter', (done) -> Comment.find(sort: "upvotes", ticket: aTicket._id, true, user).then (comments) -> oldUpvotes = 0 for comment in comments oldUpvotes.should.be.at.most comment.upvotes oldUpvotes = comment.upvotes done() .fail done it 'supports `limit` parameter', (done) -> Comment.find(limit: 1, ticket: aTicket._id, true, user).then (stories)-> stories.should.have.length 1 done() .fail done it 'supports `skip` parameter', (done) -> Comment.find(offset: 1, ticket: aTicket._id, true, user).then (stories)-> stories.should.have.length 1 done() .fail done it 'supports `select` parameter', (done) -> Comment.find(select: 'upvotes', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 2 for comment in comments should.not.exist comment.title should.not.exist comment.downvotes should.exist comment.upvotes Comment.find(select: '-upvotes', ticket: aTicket._id) .then (comments)-> comments.should.have.length 2 for comment in comments should.exist comment.body should.exist comment.downvotes should.not.exist comment.upvotes done() .fail done describe 'where', -> it 'supports `=`', (done) -> Comment.find(upvotes: '2', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 comments.should.all.have.property 'upvotes', 2 done() .fail done it 'supports `<`', (done) -> Comment.find(upvotes: '<3', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 for comment in comments comment.upvotes.should.be.below 3 done() .fail done it 'supports `<=`', (done) -> Comment.find(upvotes: '<=2', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 for comment in comments comment.upvotes.should.be.most 2 done() .fail done it 'supports `>`', (done) -> Comment.find(upvotes: '>3', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 for comment in comments comment.upvotes.should.be.above 3 done() .fail done it 'supports `>=`', (done) -> Comment.find(upvotes: '>=5', ticket: aTicket._id, true, user).then (comments)-> comments.should.have.length 1 for comment in comments comment.upvotes.should.be.least 5 someModel = comments[0] done() .fail done describe '#findById()', -> it 'supports finding one doc', (done) -> Comment.findById(someModel._id, true , user).then (other) -> someModel._id = someModel._id?.toString() other.should.deep.equal someModel done() .fail done # it 'supports finding one doc with `select`', (done) -> # # Comment.findById(someModel._id, select: 'upvotes').then (other) -> # should.not.exist other.downvotes # should.not.exist other.body # done() # .fail done describe '#create()', -> it 'can create a submodel', (done) -> props = body: "This is a long bodddddyyyyyyyyyyyy" upvotes: 2e5 downvotes: 2e2 ticket: aTicket._id Comment.create(props, true, user).then (comment) -> someModel = _.clone comment delete comment._id delete props.ticket comment.should.deep.equal props done() .fail done describe '#set()' ,-> it 'can set some properties', (done) -> Comment.set(someModel._id, upvotes: 2e3 body: "King's Landing" , true, user).then (result) -> result.upvotes.should.equal 2e3 result.body.should.equal "King's Landing" result._id.toString().should.equal someModel._id.toString() Comment.findById someModel._id, true, user .then (result) -> result.upvotes.should.equal 2e3 result.body.should.equal "King's LandPI:NAME:<NAME>END_PI" result._id.toString().should.equal someModel._id.toString() done() .fail done describe '#delete()', -> it 'can delete a comment', (done) -> Comment.delete(someModel._id, true, user).then -> Comment.findById someModel._id .then (comment) -> comment.should.deep.equal {} done() .fail done
[ { "context": "eason\n return failureCause if failureCause\n\n# 'sbacanu@hubspot.com' => 'sbacanu'\n# 'seb' => 'seb'\nHa", "end": 5466, "score": 0.9999241828918457, "start": 5447, "tag": "EMAIL", "value": "sbacanu@hubspot.com" }, { "context": "ause if failureCause\n\n# 'sbacanu@hubspot.com' => 'sbacanu'\n# 'seb' => 'seb'\nHandlebars.r", "end": 5476, "score": 0.9732885360717773, "start": 5472, "tag": "USERNAME", "value": "sbac" } ]
Chapter4/Singularity/SingularityUI/app/handlebarsHelpers.coffee
HussainK72/Mastering-Mesos
11
Handlebars = require 'handlebars' moment = require 'moment' Utils = require './utils' Handlebars.registerHelper 'appRoot', -> config.appRoot Handlebars.registerHelper 'apiDocs', -> config.apiDocs Handlebars.registerHelper 'ifEqual', (v1, v2, options) -> if v1 is v2 then options.fn @ else options.inverse @ Handlebars.registerHelper 'ifNotEqual', (v1, v2, options) -> if v1 isnt v2 then options.fn @ else options.inverse @ Handlebars.registerHelper 'ifLT', (v1, v2, options) -> if v1 < v2 then options.fn @ else options.inverse @ Handlebars.registerHelper 'ifGT', (v1, v2, options) -> if v1 > v2 then options.fn @ else options.inverse @ Handlebars.registerHelper "ifAll", (conditions..., options)-> for condition in conditions return options.inverse @ unless condition? options.fn @ Handlebars.registerHelper 'percentageOf', (v1, v2) -> (v1/v2) * 100 # Override decimal rounding: {{fixedDecimal data.cpuUsage place="4"}} Handlebars.registerHelper 'fixedDecimal', (value, options) -> if options.hash.place then place = options.hash.place else place = 2 +(value).toFixed(place) Handlebars.registerHelper 'ifTaskInList', (list, task, options) -> for t in list if t.id == task return options.fn @ return options.inverse @ Handlebars.registerHelper 'ifInSubFilter', (needle, haystack, options) -> return options.fn @ if haystack is 'all' if haystack.indexOf(needle) isnt -1 options.fn @ else options.inverse @ Handlebars.registerHelper 'unlessInSubFilter', (needle, haystack, options) -> return options.inverse @ if haystack is 'all' if haystack.indexOf(needle) is -1 options.fn @ else options.inverse @ # {{#withLast [1, 2, 3]}} # {{! this = 3 }} # {{/withLast}} Handlebars.registerHelper 'withLast', (list, options) -> options.fn _.last list # {{#withFirst [1, 2, 3]}} # {{! this = 1 }} # {{/withFirst}} Handlebars.registerHelper 'withFirst', (list, options) -> options.fn list[0] # 1234567890 => 20 minutes ago Handlebars.registerHelper 'timestampFromNow', (timestamp) -> return '' if not timestamp timeObject = moment timestamp "#{timeObject.fromNow()} (#{ timeObject.format window.config.timestampFormat})" Handlebars.registerHelper 'ifTimestampInPast', (timestamp, options) -> return options.inverse @ if not timestamp timeObject = moment timestamp now = moment() if timeObject.isBefore(now) options.fn @ else options.inverse @ Handlebars.registerHelper 'ifTimestampSecondsInPast', (timestamp, seconds, options) -> return options.inverse @ if not timestamp timeObject = moment timestamp past = moment().subtract(seconds, "seconds") if timeObject.isBefore(past) options.fn @ else options.inverse @ Handlebars.registerHelper 'ifTimestampSecondsInFuture', (timestamp, seconds, options) -> return options.inverse @ if not timestamp timeObject = moment timestamp future = moment().add(seconds, "seconds") if timeObject.isAfter(future) options.fn @ else options.inverse @ # 12345 => 12 seconds Handlebars.registerHelper 'timestampDuration', (timestamp) -> return '' if not timestamp moment.duration(timestamp).humanize() # 1234567890 => 1 Aug 1991 15:00 Handlebars.registerHelper 'timestampFormatted', (timestamp) -> return '' if not timestamp timeObject = moment timestamp timeObject.format window.config.timestampFormat Handlebars.registerHelper 'timestampFormattedWithSeconds', (timestamp) -> return '' if not timestamp timeObject = moment timestamp timeObject.format window.config.timestampWithSecondsFormat # 'DRIVER_NOT_RUNNING' => 'Driver not running' Handlebars.registerHelper 'humanizeText', (text) -> return '' if not text text = text.replace /_/g, ' ' text = text.toLowerCase() text = text[0].toUpperCase() + text.substr 1 text # 2121 => '2 KB' Handlebars.registerHelper 'humanizeFileSize', (bytes) -> k = 1024 sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] return '0 B' if bytes is 0 i = Math.min(Math.floor(Math.log(bytes) / Math.log(k)), sizes.length-1) return +(bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i] Handlebars.registerHelper 'ifCauseOfFailure', (task, deploy, options) -> thisTaskFailedTheDeploy = false deploy.deployResult.deployFailures.map (failure) -> if failure.taskId and failure.taskId.id is task.taskId thisTaskFailedTheDeploy = true if thisTaskFailedTheDeploy options.fn @ else options.inverse @ Handlebars.registerHelper 'ifDeployFailureCausedTaskToBeKilled', (task, options) -> deployFailed = false taskKilled = false task.taskUpdates.map (update) -> if update.statusMessage and update.statusMessage.indexOf 'DEPLOY_FAILED' isnt -1 deployFailed = true if update.taskState is 'TASK_KILLED' taskKilled = true if deployFailed and taskKilled options.fn @ else options.inverse @ Handlebars.registerHelper 'causeOfDeployFailure', (task, deploy) -> failureCause = '' deploy.deployResult.deployFailures.map (failure) -> if failure.taskId and failure.taskId.id is task.taskId failureCause = Handlebars.helpers.humanizeText failure.reason return failureCause if failureCause # 'sbacanu@hubspot.com' => 'sbacanu' # 'seb' => 'seb' Handlebars.registerHelper 'usernameFromEmail', (email) -> return '' if not email email.split('@')[0] Handlebars.registerHelper 'substituteTaskId', (value, taskId) -> value.replace('$TASK_ID', taskId) Handlebars.registerHelper 'filename', (value) -> Utils.fileName(value) Handlebars.registerHelper 'getLabelClass', (state) -> Utils.getLabelClassFromTaskState state Handlebars.registerHelper 'trimS3File', (filename, taskId) -> unless config.taskS3LogOmitPrefix return filename finalRegex = config.taskS3LogOmitPrefix.replace('%taskId', taskId.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).replace('%index', '[0-9]+').replace('%s', '[0-9]+') return filename.replace(new RegExp(finalRegex), '') Handlebars.registerHelper 'isRunningState', (list, options) -> switch _.last(list).taskState when 'TASK_RUNNING' options.fn(@) else options.inverse(@) Handlebars.registerHelper 'isSingularityExecutor', (value, options) -> if value and value.indexOf 'singularity-executor' != -1 options.fn(@) else options.inverse(@) Handlebars.registerHelper 'lastShellRequestStatus', (statuses) -> if statuses.length > 0 statuses[0].updateType Handlebars.registerHelper 'shellRequestOutputFilename', (statuses) -> for status in statuses if status.outputFilename return status.outputFilename Handlebars.registerHelper 'ifShellRequestHasOutputFilename', (statuses, options) -> for status in statuses if status.outputFilename return options.fn @ return options.inverse @
90931
Handlebars = require 'handlebars' moment = require 'moment' Utils = require './utils' Handlebars.registerHelper 'appRoot', -> config.appRoot Handlebars.registerHelper 'apiDocs', -> config.apiDocs Handlebars.registerHelper 'ifEqual', (v1, v2, options) -> if v1 is v2 then options.fn @ else options.inverse @ Handlebars.registerHelper 'ifNotEqual', (v1, v2, options) -> if v1 isnt v2 then options.fn @ else options.inverse @ Handlebars.registerHelper 'ifLT', (v1, v2, options) -> if v1 < v2 then options.fn @ else options.inverse @ Handlebars.registerHelper 'ifGT', (v1, v2, options) -> if v1 > v2 then options.fn @ else options.inverse @ Handlebars.registerHelper "ifAll", (conditions..., options)-> for condition in conditions return options.inverse @ unless condition? options.fn @ Handlebars.registerHelper 'percentageOf', (v1, v2) -> (v1/v2) * 100 # Override decimal rounding: {{fixedDecimal data.cpuUsage place="4"}} Handlebars.registerHelper 'fixedDecimal', (value, options) -> if options.hash.place then place = options.hash.place else place = 2 +(value).toFixed(place) Handlebars.registerHelper 'ifTaskInList', (list, task, options) -> for t in list if t.id == task return options.fn @ return options.inverse @ Handlebars.registerHelper 'ifInSubFilter', (needle, haystack, options) -> return options.fn @ if haystack is 'all' if haystack.indexOf(needle) isnt -1 options.fn @ else options.inverse @ Handlebars.registerHelper 'unlessInSubFilter', (needle, haystack, options) -> return options.inverse @ if haystack is 'all' if haystack.indexOf(needle) is -1 options.fn @ else options.inverse @ # {{#withLast [1, 2, 3]}} # {{! this = 3 }} # {{/withLast}} Handlebars.registerHelper 'withLast', (list, options) -> options.fn _.last list # {{#withFirst [1, 2, 3]}} # {{! this = 1 }} # {{/withFirst}} Handlebars.registerHelper 'withFirst', (list, options) -> options.fn list[0] # 1234567890 => 20 minutes ago Handlebars.registerHelper 'timestampFromNow', (timestamp) -> return '' if not timestamp timeObject = moment timestamp "#{timeObject.fromNow()} (#{ timeObject.format window.config.timestampFormat})" Handlebars.registerHelper 'ifTimestampInPast', (timestamp, options) -> return options.inverse @ if not timestamp timeObject = moment timestamp now = moment() if timeObject.isBefore(now) options.fn @ else options.inverse @ Handlebars.registerHelper 'ifTimestampSecondsInPast', (timestamp, seconds, options) -> return options.inverse @ if not timestamp timeObject = moment timestamp past = moment().subtract(seconds, "seconds") if timeObject.isBefore(past) options.fn @ else options.inverse @ Handlebars.registerHelper 'ifTimestampSecondsInFuture', (timestamp, seconds, options) -> return options.inverse @ if not timestamp timeObject = moment timestamp future = moment().add(seconds, "seconds") if timeObject.isAfter(future) options.fn @ else options.inverse @ # 12345 => 12 seconds Handlebars.registerHelper 'timestampDuration', (timestamp) -> return '' if not timestamp moment.duration(timestamp).humanize() # 1234567890 => 1 Aug 1991 15:00 Handlebars.registerHelper 'timestampFormatted', (timestamp) -> return '' if not timestamp timeObject = moment timestamp timeObject.format window.config.timestampFormat Handlebars.registerHelper 'timestampFormattedWithSeconds', (timestamp) -> return '' if not timestamp timeObject = moment timestamp timeObject.format window.config.timestampWithSecondsFormat # 'DRIVER_NOT_RUNNING' => 'Driver not running' Handlebars.registerHelper 'humanizeText', (text) -> return '' if not text text = text.replace /_/g, ' ' text = text.toLowerCase() text = text[0].toUpperCase() + text.substr 1 text # 2121 => '2 KB' Handlebars.registerHelper 'humanizeFileSize', (bytes) -> k = 1024 sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] return '0 B' if bytes is 0 i = Math.min(Math.floor(Math.log(bytes) / Math.log(k)), sizes.length-1) return +(bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i] Handlebars.registerHelper 'ifCauseOfFailure', (task, deploy, options) -> thisTaskFailedTheDeploy = false deploy.deployResult.deployFailures.map (failure) -> if failure.taskId and failure.taskId.id is task.taskId thisTaskFailedTheDeploy = true if thisTaskFailedTheDeploy options.fn @ else options.inverse @ Handlebars.registerHelper 'ifDeployFailureCausedTaskToBeKilled', (task, options) -> deployFailed = false taskKilled = false task.taskUpdates.map (update) -> if update.statusMessage and update.statusMessage.indexOf 'DEPLOY_FAILED' isnt -1 deployFailed = true if update.taskState is 'TASK_KILLED' taskKilled = true if deployFailed and taskKilled options.fn @ else options.inverse @ Handlebars.registerHelper 'causeOfDeployFailure', (task, deploy) -> failureCause = '' deploy.deployResult.deployFailures.map (failure) -> if failure.taskId and failure.taskId.id is task.taskId failureCause = Handlebars.helpers.humanizeText failure.reason return failureCause if failureCause # '<EMAIL>' => 'sbacanu' # 'seb' => 'seb' Handlebars.registerHelper 'usernameFromEmail', (email) -> return '' if not email email.split('@')[0] Handlebars.registerHelper 'substituteTaskId', (value, taskId) -> value.replace('$TASK_ID', taskId) Handlebars.registerHelper 'filename', (value) -> Utils.fileName(value) Handlebars.registerHelper 'getLabelClass', (state) -> Utils.getLabelClassFromTaskState state Handlebars.registerHelper 'trimS3File', (filename, taskId) -> unless config.taskS3LogOmitPrefix return filename finalRegex = config.taskS3LogOmitPrefix.replace('%taskId', taskId.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).replace('%index', '[0-9]+').replace('%s', '[0-9]+') return filename.replace(new RegExp(finalRegex), '') Handlebars.registerHelper 'isRunningState', (list, options) -> switch _.last(list).taskState when 'TASK_RUNNING' options.fn(@) else options.inverse(@) Handlebars.registerHelper 'isSingularityExecutor', (value, options) -> if value and value.indexOf 'singularity-executor' != -1 options.fn(@) else options.inverse(@) Handlebars.registerHelper 'lastShellRequestStatus', (statuses) -> if statuses.length > 0 statuses[0].updateType Handlebars.registerHelper 'shellRequestOutputFilename', (statuses) -> for status in statuses if status.outputFilename return status.outputFilename Handlebars.registerHelper 'ifShellRequestHasOutputFilename', (statuses, options) -> for status in statuses if status.outputFilename return options.fn @ return options.inverse @
true
Handlebars = require 'handlebars' moment = require 'moment' Utils = require './utils' Handlebars.registerHelper 'appRoot', -> config.appRoot Handlebars.registerHelper 'apiDocs', -> config.apiDocs Handlebars.registerHelper 'ifEqual', (v1, v2, options) -> if v1 is v2 then options.fn @ else options.inverse @ Handlebars.registerHelper 'ifNotEqual', (v1, v2, options) -> if v1 isnt v2 then options.fn @ else options.inverse @ Handlebars.registerHelper 'ifLT', (v1, v2, options) -> if v1 < v2 then options.fn @ else options.inverse @ Handlebars.registerHelper 'ifGT', (v1, v2, options) -> if v1 > v2 then options.fn @ else options.inverse @ Handlebars.registerHelper "ifAll", (conditions..., options)-> for condition in conditions return options.inverse @ unless condition? options.fn @ Handlebars.registerHelper 'percentageOf', (v1, v2) -> (v1/v2) * 100 # Override decimal rounding: {{fixedDecimal data.cpuUsage place="4"}} Handlebars.registerHelper 'fixedDecimal', (value, options) -> if options.hash.place then place = options.hash.place else place = 2 +(value).toFixed(place) Handlebars.registerHelper 'ifTaskInList', (list, task, options) -> for t in list if t.id == task return options.fn @ return options.inverse @ Handlebars.registerHelper 'ifInSubFilter', (needle, haystack, options) -> return options.fn @ if haystack is 'all' if haystack.indexOf(needle) isnt -1 options.fn @ else options.inverse @ Handlebars.registerHelper 'unlessInSubFilter', (needle, haystack, options) -> return options.inverse @ if haystack is 'all' if haystack.indexOf(needle) is -1 options.fn @ else options.inverse @ # {{#withLast [1, 2, 3]}} # {{! this = 3 }} # {{/withLast}} Handlebars.registerHelper 'withLast', (list, options) -> options.fn _.last list # {{#withFirst [1, 2, 3]}} # {{! this = 1 }} # {{/withFirst}} Handlebars.registerHelper 'withFirst', (list, options) -> options.fn list[0] # 1234567890 => 20 minutes ago Handlebars.registerHelper 'timestampFromNow', (timestamp) -> return '' if not timestamp timeObject = moment timestamp "#{timeObject.fromNow()} (#{ timeObject.format window.config.timestampFormat})" Handlebars.registerHelper 'ifTimestampInPast', (timestamp, options) -> return options.inverse @ if not timestamp timeObject = moment timestamp now = moment() if timeObject.isBefore(now) options.fn @ else options.inverse @ Handlebars.registerHelper 'ifTimestampSecondsInPast', (timestamp, seconds, options) -> return options.inverse @ if not timestamp timeObject = moment timestamp past = moment().subtract(seconds, "seconds") if timeObject.isBefore(past) options.fn @ else options.inverse @ Handlebars.registerHelper 'ifTimestampSecondsInFuture', (timestamp, seconds, options) -> return options.inverse @ if not timestamp timeObject = moment timestamp future = moment().add(seconds, "seconds") if timeObject.isAfter(future) options.fn @ else options.inverse @ # 12345 => 12 seconds Handlebars.registerHelper 'timestampDuration', (timestamp) -> return '' if not timestamp moment.duration(timestamp).humanize() # 1234567890 => 1 Aug 1991 15:00 Handlebars.registerHelper 'timestampFormatted', (timestamp) -> return '' if not timestamp timeObject = moment timestamp timeObject.format window.config.timestampFormat Handlebars.registerHelper 'timestampFormattedWithSeconds', (timestamp) -> return '' if not timestamp timeObject = moment timestamp timeObject.format window.config.timestampWithSecondsFormat # 'DRIVER_NOT_RUNNING' => 'Driver not running' Handlebars.registerHelper 'humanizeText', (text) -> return '' if not text text = text.replace /_/g, ' ' text = text.toLowerCase() text = text[0].toUpperCase() + text.substr 1 text # 2121 => '2 KB' Handlebars.registerHelper 'humanizeFileSize', (bytes) -> k = 1024 sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] return '0 B' if bytes is 0 i = Math.min(Math.floor(Math.log(bytes) / Math.log(k)), sizes.length-1) return +(bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i] Handlebars.registerHelper 'ifCauseOfFailure', (task, deploy, options) -> thisTaskFailedTheDeploy = false deploy.deployResult.deployFailures.map (failure) -> if failure.taskId and failure.taskId.id is task.taskId thisTaskFailedTheDeploy = true if thisTaskFailedTheDeploy options.fn @ else options.inverse @ Handlebars.registerHelper 'ifDeployFailureCausedTaskToBeKilled', (task, options) -> deployFailed = false taskKilled = false task.taskUpdates.map (update) -> if update.statusMessage and update.statusMessage.indexOf 'DEPLOY_FAILED' isnt -1 deployFailed = true if update.taskState is 'TASK_KILLED' taskKilled = true if deployFailed and taskKilled options.fn @ else options.inverse @ Handlebars.registerHelper 'causeOfDeployFailure', (task, deploy) -> failureCause = '' deploy.deployResult.deployFailures.map (failure) -> if failure.taskId and failure.taskId.id is task.taskId failureCause = Handlebars.helpers.humanizeText failure.reason return failureCause if failureCause # 'PI:EMAIL:<EMAIL>END_PI' => 'sbacanu' # 'seb' => 'seb' Handlebars.registerHelper 'usernameFromEmail', (email) -> return '' if not email email.split('@')[0] Handlebars.registerHelper 'substituteTaskId', (value, taskId) -> value.replace('$TASK_ID', taskId) Handlebars.registerHelper 'filename', (value) -> Utils.fileName(value) Handlebars.registerHelper 'getLabelClass', (state) -> Utils.getLabelClassFromTaskState state Handlebars.registerHelper 'trimS3File', (filename, taskId) -> unless config.taskS3LogOmitPrefix return filename finalRegex = config.taskS3LogOmitPrefix.replace('%taskId', taskId.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).replace('%index', '[0-9]+').replace('%s', '[0-9]+') return filename.replace(new RegExp(finalRegex), '') Handlebars.registerHelper 'isRunningState', (list, options) -> switch _.last(list).taskState when 'TASK_RUNNING' options.fn(@) else options.inverse(@) Handlebars.registerHelper 'isSingularityExecutor', (value, options) -> if value and value.indexOf 'singularity-executor' != -1 options.fn(@) else options.inverse(@) Handlebars.registerHelper 'lastShellRequestStatus', (statuses) -> if statuses.length > 0 statuses[0].updateType Handlebars.registerHelper 'shellRequestOutputFilename', (statuses) -> for status in statuses if status.outputFilename return status.outputFilename Handlebars.registerHelper 'ifShellRequestHasOutputFilename', (statuses, options) -> for status in statuses if status.outputFilename return options.fn @ return options.inverse @
[ { "context": "npmlog'\n\ndynClient = Dyn({traffic:{customer_name:'yourcustomer',user_name:'youruser',password:'yourpassword'}})\n", "end": 136, "score": 0.9993206262588501, "start": 124, "tag": "USERNAME", "value": "yourcustomer" }, { "context": "{traffic:{customer_name:'yourcustomer',user_name:'youruser',password:'yourpassword'}})\ndynClient.log.level =", "end": 157, "score": 0.9996362924575806, "start": 149, "tag": "USERNAME", "value": "youruser" }, { "context": "ame:'yourcustomer',user_name:'youruser',password:'yourpassword'}})\ndynClient.log.level = 'sil'\n\ndyn = dynClient.", "end": 181, "score": 0.9993070363998413, "start": 169, "tag": "PASSWORD", "value": "yourpassword" }, { "context": "ringify(x)}\"\n x\n -> dyn.zone.create({rname:'admin@example.com',ttl:60}).then (x) ->\n log.info 'RESULT', \"c", "end": 608, "score": 0.9998151659965515, "start": 591, "tag": "EMAIL", "value": "admin@example.com" }, { "context": "d._A.create('local2.example.com',{rdata:{address:'127.0.0.1'}}).then (x) ->\n log.info 'RESULT', \"created", "end": 778, "score": 0.9996938705444336, "start": 769, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
examples/traffic_example.coffee
dyninc/dyn-js
6
Dyn = require '../lib/dyn-js.js' async = require 'async-q' log = require 'npmlog' dynClient = Dyn({traffic:{customer_name:'yourcustomer',user_name:'youruser',password:'yourpassword'}}) dynClient.log.level = 'sil' dyn = dynClient.traffic.withZone('example.com') fail = (bad) -> console.log 'FAIL', arguments async.series([ -> dyn.session.create() -> dyn.zone.list().then (x) -> log.info 'RESULT', "got zones: #{JSON.stringify(x)}" x -> dyn.zone.destroy().then (x) -> log.info 'RESULT', "zone removed: #{JSON.stringify(x)}" x -> dyn.zone.create({rname:'admin@example.com',ttl:60}).then (x) -> log.info 'RESULT', "created new zone: #{JSON.stringify(x)}" x -> dyn.record._A.create('local2.example.com',{rdata:{address:'127.0.0.1'}}).then (x) -> log.info 'RESULT', "created an A record: #{JSON.stringify(x)}" x -> dyn.record._CNAME.create('local.example.com', {rdata:{cname:'locale2.example.com'}}).then (x) -> log.info 'RESULT', "created a CNAME record: #{JSON.stringify(x)}" x -> dyn.http_redirect.create('overhere.example.com',302,"Y",'http://overthere.example.com').then (x) -> log.info 'RESULT', "created a redirect: #{JSON.stringify(x)}" x -> dyn.gslb.create('hello.example.com', {region:{region_code:'global', pool:{address:'hi.example.com'}}}).then (x) -> log.info 'RESULT', "created a gslb service: #{JSON.stringify(x)}" x -> dyn.session.destroy() ]).then -> _(arguments[0]).forEach (x) -> log.info 'RESULT', "finished : #{JSON.stringify(x)}" , fail
214381
Dyn = require '../lib/dyn-js.js' async = require 'async-q' log = require 'npmlog' dynClient = Dyn({traffic:{customer_name:'yourcustomer',user_name:'youruser',password:'<PASSWORD>'}}) dynClient.log.level = 'sil' dyn = dynClient.traffic.withZone('example.com') fail = (bad) -> console.log 'FAIL', arguments async.series([ -> dyn.session.create() -> dyn.zone.list().then (x) -> log.info 'RESULT', "got zones: #{JSON.stringify(x)}" x -> dyn.zone.destroy().then (x) -> log.info 'RESULT', "zone removed: #{JSON.stringify(x)}" x -> dyn.zone.create({rname:'<EMAIL>',ttl:60}).then (x) -> log.info 'RESULT', "created new zone: #{JSON.stringify(x)}" x -> dyn.record._A.create('local2.example.com',{rdata:{address:'127.0.0.1'}}).then (x) -> log.info 'RESULT', "created an A record: #{JSON.stringify(x)}" x -> dyn.record._CNAME.create('local.example.com', {rdata:{cname:'locale2.example.com'}}).then (x) -> log.info 'RESULT', "created a CNAME record: #{JSON.stringify(x)}" x -> dyn.http_redirect.create('overhere.example.com',302,"Y",'http://overthere.example.com').then (x) -> log.info 'RESULT', "created a redirect: #{JSON.stringify(x)}" x -> dyn.gslb.create('hello.example.com', {region:{region_code:'global', pool:{address:'hi.example.com'}}}).then (x) -> log.info 'RESULT', "created a gslb service: #{JSON.stringify(x)}" x -> dyn.session.destroy() ]).then -> _(arguments[0]).forEach (x) -> log.info 'RESULT', "finished : #{JSON.stringify(x)}" , fail
true
Dyn = require '../lib/dyn-js.js' async = require 'async-q' log = require 'npmlog' dynClient = Dyn({traffic:{customer_name:'yourcustomer',user_name:'youruser',password:'PI:PASSWORD:<PASSWORD>END_PI'}}) dynClient.log.level = 'sil' dyn = dynClient.traffic.withZone('example.com') fail = (bad) -> console.log 'FAIL', arguments async.series([ -> dyn.session.create() -> dyn.zone.list().then (x) -> log.info 'RESULT', "got zones: #{JSON.stringify(x)}" x -> dyn.zone.destroy().then (x) -> log.info 'RESULT', "zone removed: #{JSON.stringify(x)}" x -> dyn.zone.create({rname:'PI:EMAIL:<EMAIL>END_PI',ttl:60}).then (x) -> log.info 'RESULT', "created new zone: #{JSON.stringify(x)}" x -> dyn.record._A.create('local2.example.com',{rdata:{address:'127.0.0.1'}}).then (x) -> log.info 'RESULT', "created an A record: #{JSON.stringify(x)}" x -> dyn.record._CNAME.create('local.example.com', {rdata:{cname:'locale2.example.com'}}).then (x) -> log.info 'RESULT', "created a CNAME record: #{JSON.stringify(x)}" x -> dyn.http_redirect.create('overhere.example.com',302,"Y",'http://overthere.example.com').then (x) -> log.info 'RESULT', "created a redirect: #{JSON.stringify(x)}" x -> dyn.gslb.create('hello.example.com', {region:{region_code:'global', pool:{address:'hi.example.com'}}}).then (x) -> log.info 'RESULT', "created a gslb service: #{JSON.stringify(x)}" x -> dyn.session.destroy() ]).then -> _(arguments[0]).forEach (x) -> log.info 'RESULT', "finished : #{JSON.stringify(x)}" , fail
[ { "context": "ipient:\n address: @get('email')\n name: @broadName()\n email_data:\n name: @broadName()\n ", "end": 10268, "score": 0.9635912179946899, "start": 10259, "tag": "USERNAME", "value": "broadName" }, { "context": " name: @broadName()\n email_data:\n name: @broadName()\n verify_link: \"http://codecombat.com/user/", "end": 10309, "score": 0.9075572490692139, "start": 10300, "tag": "USERNAME", "value": "broadName" }, { "context": "er needs a username or email address'))\n\n pwd = @get('password')\n if @get('password')\n @set('passw", "end": 13716, "score": 0.6776083111763, "start": 13713, "tag": "PASSWORD", "value": "get" }, { "context": "eds a username or email address'))\n\n pwd = @get('password')\n if @get('password')\n @set('passwordHash', ", "end": 13726, "score": 0.5684643983840942, "start": 13718, "tag": "PASSWORD", "value": "password" }, { "context": ".statics.hashPassword = (password) ->\n password = password.toLowerCase()\n shasum = crypto.createHash('sha512')\n shasum.u", "end": 14548, "score": 0.9559778571128845, "start": 14528, "tag": "PASSWORD", "value": "password.toLowerCase" }, { "context": "rties = [\n 'permissions', 'email', 'mailChimp', 'firstName', 'lastName', 'gender', 'facebookID',\n 'gplusID'", "end": 14966, "score": 0.9991719722747803, "start": 14957, "tag": "NAME", "value": "firstName" }, { "context": "permissions', 'email', 'mailChimp', 'firstName', 'lastName', 'gender', 'facebookID',\n 'gplusID', 'music', '", "end": 14978, "score": 0.9990789890289307, "start": 14970, "tag": "NAME", "value": "lastName" }, { "context": "sword', 'anonymous', 'wizardColor1', 'volume',\n 'firstName', 'lastName', 'gender', 'ageRange', 'facebookID',", "end": 15426, "score": 0.999088704586029, "start": 15417, "tag": "NAME", "value": "firstName" }, { "context": "ymous', 'wizardColor1', 'volume',\n 'firstName', 'lastName', 'gender', 'ageRange', 'facebookID', 'gplusID', ", "end": 15438, "score": 0.9991835355758667, "start": 15430, "tag": "NAME", "value": "lastName" } ]
server/models/User.coffee
mohancm/codecombat
1
mongoose = require 'mongoose' jsonschema = require '../../app/schemas/models/user' crypto = require 'crypto' {salt, isProduction} = require '../../server_config' mail = require '../commons/mail' log = require 'winston' plugins = require '../plugins/plugins' AnalyticsUsersActive = require './AnalyticsUsersActive' Classroom = require '../models/Classroom' languages = require '../routes/languages' _ = require 'lodash' errors = require '../commons/errors' config = require '../../server_config' stripe = require('stripe')(config.stripe.secretKey) sendwithus = require '../sendwithus' UserSchema = new mongoose.Schema({ dateCreated: type: Date 'default': Date.now }, {strict: false}) UserSchema.index({'dateCreated': 1}) UserSchema.index({'emailLower': 1}, {unique: true, sparse: true, name: 'emailLower_1'}) UserSchema.index({'facebookID': 1}, {sparse: true}) UserSchema.index({'gplusID': 1}, {sparse: true}) UserSchema.index({'iosIdentifierForVendor': 1}, {name: 'iOS identifier for vendor', sparse: true, unique: true}) UserSchema.index({'mailChimp.leid': 1}, {sparse: true}) UserSchema.index({'nameLower': 1}, {sparse: true, name: 'nameLower_1'}) UserSchema.index({'simulatedBy': 1}) UserSchema.index({'slug': 1}, {name: 'slug index', sparse: true, unique: true}) UserSchema.index({'stripe.subscriptionID': 1}, {unique: true, sparse: true}) UserSchema.index({'siteref': 1}, {name: 'siteref index', sparse: true}) UserSchema.index({'schoolName': 1}, {name: 'schoolName index', sparse: true}) UserSchema.index({'country': 1}, {name: 'country index', sparse: true}) UserSchema.index({'role': 1}, {name: 'role index', sparse: true}) UserSchema.index({'coursePrepaid._id': 1}, {name: 'course prepaid id index', sparse: true}) UserSchema.post('init', -> @set('anonymous', false) if @get('email') ) UserSchema.methods.broadName = -> return '(deleted)' if @get('deleted') name = _.filter([@get('firstName'), @get('lastName')]).join(' ') return name if name name = @get('name') return name if name [emailName, emailDomain] = @get('email').split('@') return emailName if emailName return 'Anonymous' UserSchema.methods.isInGodMode = -> p = @get('permissions') return p and 'godmode' in p UserSchema.methods.isAdmin = -> p = @get('permissions') return p and 'admin' in p UserSchema.methods.hasPermission = (neededPermissions) -> permissions = @get('permissions') or [] if _.contains(permissions, 'admin') return true if _.isString(neededPermissions) neededPermissions = [neededPermissions] return _.size(_.intersection(permissions, neededPermissions)) UserSchema.methods.isArtisan = -> p = @get('permissions') return p and 'artisan' in p UserSchema.methods.isAnonymous = -> @get 'anonymous' UserSchema.statics.teacherRoles = ['teacher', 'technology coordinator', 'advisor', 'principal', 'superintendent', 'parent'] UserSchema.methods.isTeacher = -> return @get('role') in User.teacherRoles UserSchema.methods.isStudent = -> return @get('role') is 'student' UserSchema.methods.getUserInfo = -> id: @get('_id') email: if @get('anonymous') then 'Unregistered User' else @get('email') UserSchema.methods.removeFromClassrooms = -> userID = @get('_id') yield Classroom.update( { members: userID } { $addToSet: { deletedMembers: userID } $pull: { members: userID } } { multi: true } ) UserSchema.methods.trackActivity = (activityName, increment) -> now = new Date() increment ?= parseInt increment or 1 increment = Math.max increment, 0 activity = @get('activity') ? {} activity[activityName] ?= {first: now, count: 0} activity[activityName].count += increment activity[activityName].last = now @set 'activity', activity activity UserSchema.statics.search = (term, done) -> utils = require '../lib/utils' if utils.isID(term) query = {_id: mongoose.Types.ObjectId(term)} else term = term.toLowerCase() query = $or: [{nameLower: term}, {emailLower: term}] return User.findOne(query).exec(done) UserSchema.statics.findByEmail = (email, done=_.noop) -> emailLower = email.toLowerCase() User.findOne({emailLower: emailLower}).exec(done) UserSchema.statics.findByName = (name, done=_.noop) -> nameLower = name.toLowerCase() User.findOne({nameLower: nameLower}).exec(done) emailNameMap = generalNews: 'announcement' adventurerNews: 'tester' artisanNews: 'level_creator' archmageNews: 'developer' scribeNews: 'article_editor' diplomatNews: 'translator' ambassadorNews: 'support' anyNotes: 'notification' teacherNews: 'teacher' UserSchema.methods.setEmailSubscription = (newName, enabled) -> oldSubs = _.clone @get('emailSubscriptions') if oldSubs and oldName = emailNameMap[newName] oldSubs = (s for s in oldSubs when s isnt oldName) oldSubs.push(oldName) if enabled @set('emailSubscriptions', oldSubs) newSubs = _.clone(@get('emails') or _.cloneDeep(jsonschema.properties.emails.default)) newSubs[newName] ?= {} newSubs[newName].enabled = enabled @set('emails', newSubs) @newsSubsChanged = true if newName in mail.NEWS_GROUPS UserSchema.methods.gems = -> gemsEarned = @get('earned')?.gems ? 0 gemsEarned = gemsEarned + 100000 if @isInGodMode() gemsPurchased = @get('purchased')?.gems ? 0 gemsSpent = @get('spent') ? 0 gemsEarned + gemsPurchased - gemsSpent UserSchema.methods.isEmailSubscriptionEnabled = (newName) -> emails = @get 'emails' if not emails oldSubs = @get('emailSubscriptions') oldName = emailNameMap[newName] return oldName and oldName in oldSubs if oldSubs emails ?= {} _.defaults emails, _.cloneDeep(jsonschema.properties.emails.default) return emails[newName]?.enabled UserSchema.statics.updateServiceSettings = (doc, callback) -> return callback?() unless isProduction or GLOBAL.testing return callback?() if doc.updatedMailChimp return callback?() unless doc.get('email') return callback?() unless doc.get('dateCreated') accountAgeMinutes = (new Date().getTime() - doc.get('dateCreated').getTime?() ? 0) / 1000 / 60 return callback?() unless accountAgeMinutes > 30 or GLOBAL.testing existingProps = doc.get('mailChimp') emailChanged = (not existingProps) or existingProps?.email isnt doc.get('email') if emailChanged and customerID = doc.get('stripe')?.customerID unless stripe?.customers console.error('Oh my god, Stripe is not imported correctly-how could we have done this (again)?') stripe?.customers?.update customerID, {email:doc.get('email')}, (err, customer) -> console.error('Error updating stripe customer...', err) if err return callback?() unless emailChanged or doc.newsSubsChanged newGroups = [] for [mailchimpEmailGroup, emailGroup] in _.zip(mail.MAILCHIMP_GROUPS, mail.NEWS_GROUPS) newGroups.push(mailchimpEmailGroup) if doc.isEmailSubscriptionEnabled(emailGroup) if (not existingProps) and newGroups.length is 0 return callback?() # don't add totally unsubscribed people to the list params = {} params.id = mail.MAILCHIMP_LIST_ID params.email = if existingProps then {leid: existingProps.leid} else {email: doc.get('email')} params.merge_vars = { groupings: [{id: mail.MAILCHIMP_GROUP_ID, groups: newGroups}] 'new-email': doc.get('email') } params.update_existing = true onSuccess = (data) -> data.email = doc.get('email') # Make sure that we don't spam opt-in emails even if MailChimp doesn't update the email it gets in this object until they have confirmed. doc.set('mailChimp', data) doc.updatedMailChimp = true doc.save() callback?() onFailure = (error) -> log.error 'failed to subscribe', error, callback? doc.updatedMailChimp = true callback?() mc?.lists.subscribe params, onSuccess, onFailure UserSchema.statics.statsMapping = edits: article: 'stats.articleEdits' level: 'stats.levelEdits' 'level.component': 'stats.levelComponentEdits' 'level.system': 'stats.levelSystemEdits' 'thang.type': 'stats.thangTypeEdits' 'Achievement': 'stats.achievementEdits' 'campaign': 'stats.campaignEdits' 'poll': 'stats.pollEdits' translations: article: 'stats.articleTranslationPatches' level: 'stats.levelTranslationPatches' 'level.component': 'stats.levelComponentTranslationPatches' 'level.system': 'stats.levelSystemTranslationPatches' 'thang.type': 'stats.thangTypeTranslationPatches' 'Achievement': 'stats.achievementTranslationPatches' 'campaign': 'stats.campaignTranslationPatches' 'poll': 'stats.pollTranslationPatches' misc: article: 'stats.articleMiscPatches' level: 'stats.levelMiscPatches' 'level.component': 'stats.levelComponentMiscPatches' 'level.system': 'stats.levelSystemMiscPatches' 'thang.type': 'stats.thangTypeMiscPatches' 'Achievement': 'stats.achievementMiscPatches' 'campaign': 'stats.campaignMiscPatches' 'poll': 'stats.pollMiscPatches' UserSchema.statics.incrementStat = (id, statName, done, inc=1) -> id = mongoose.Types.ObjectId id if _.isString id @findById id, (err, user) -> log.error err if err? err = new Error "Could't find user with id '#{id}'" unless user or err return done() if err? user.incrementStat statName, done, inc UserSchema.methods.incrementStat = (statName, done, inc=1) -> if /^concepts\./.test statName # Concept stats are nested a level deeper. concepts = @get('concepts') or {} concept = statName.split('.')[1] concepts[concept] = (concepts[concept] or 0) + inc @set 'concepts', concepts else @set statName, (@get(statName) or 0) + inc @save (err) -> done?(err) UserSchema.statics.unconflictName = unconflictName = (name, done) -> User.findOne {slug: _.str.slugify(name)}, (err, otherUser) -> return done err if err? return done null, name unless otherUser suffix = _.random(0, 9) + '' unconflictName name + suffix, done UserSchema.methods.sendWelcomeEmail = -> return if not @get('email') { welcome_email_student, welcome_email_user } = sendwithus.templates timestamp = (new Date).getTime() data = email_id: if @isStudent() then welcome_email_student else welcome_email_user recipient: address: @get('email') name: @broadName() email_data: name: @broadName() verify_link: "http://codecombat.com/user/#{@_id}/verify/#{@verificationCode(timestamp)}" sendwithus.api.send data, (err, result) -> log.error "sendwithus post-save error: #{err}, result: #{result}" if err UserSchema.methods.hasSubscription = -> return false unless stripeObject = @get('stripe') return true if stripeObject.sponsorID return true if stripeObject.subscriptionID return true if stripeObject.free is true return true if _.isString(stripeObject.free) and new Date() < new Date(stripeObject.free) UserSchema.methods.isPremium = -> return true if @isInGodMode() return true if @isAdmin() return true if @hasSubscription() return false UserSchema.methods.isOnPremiumServer = -> @get('country') in ['china', 'brazil'] UserSchema.methods.level = -> xp = @get('points') or 0 a = 5 b = c = 100 if xp > 0 then Math.floor(a * Math.log((1 / b) * (xp + c))) + 1 else 1 UserSchema.methods.isEnrolled = -> coursePrepaid = @get('coursePrepaid') return false unless coursePrepaid return true unless coursePrepaid.endDate return coursePrepaid.endDate > new Date().toISOString() UserSchema.statics.saveActiveUser = (id, event, done=null) -> # TODO: Disabling this until we know why our app servers CPU grows out of control. return done?() id = mongoose.Types.ObjectId id if _.isString id @findById id, (err, user) -> if err? log.error err else user?.saveActiveUser event done?() UserSchema.methods.saveActiveUser = (event, done=null) -> # TODO: Disabling this until we know why our app servers CPU grows out of control. return done?() try return done?() if @isAdmin() userID = @get('_id') # Create if no active user entry for today today = new Date() minDate = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate())) AnalyticsUsersActive.findOne({created: {$gte: minDate}, creator: mongoose.Types.ObjectId(userID)}).exec (err, activeUser) -> if err? log.error "saveActiveUser error retrieving active users: #{err}" else if not activeUser newActiveUser = new AnalyticsUsersActive() newActiveUser.set 'creator', userID newActiveUser.set 'event', event newActiveUser.save (err) -> log.error "Level session saveActiveUser error saving active user: #{err}" if err? done?() catch err log.error err done?() UserSchema.pre('save', (next) -> if _.isNaN(@get('purchased')?.gems) return next(new errors.InternalServerError('Attempting to save NaN to user')) Classroom = require './Classroom' if @isTeacher() and not @wasTeacher Classroom.update({members: @_id}, {$pull: {members: @_id}}, {multi: true}).exec (err, res) -> if email = @get('email') @set('emailLower', email.toLowerCase()) else @set('email', undefined) @set('emailLower', undefined) if name = @get('name') filter = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,63}$/i # https://news.ycombinator.com/item?id=5763990 if filter.test(name) return next(new errors.UnprocessableEntity('Name may not be an email')) @set('nameLower', name.toLowerCase()) else @set('name', undefined) @set('nameLower', undefined) unless email or name or @get('anonymous') or @get('deleted') return next(new errors.UnprocessableEntity('User needs a username or email address')) pwd = @get('password') if @get('password') @set('passwordHash', User.hashPassword(pwd)) @set('password', undefined) next() ) UserSchema.post 'save', (doc) -> doc.newsSubsChanged = not _.isEqual(_.pick(doc.get('emails'), mail.NEWS_GROUPS), _.pick(doc.startingEmails, mail.NEWS_GROUPS)) UserSchema.statics.updateServiceSettings(doc) UserSchema.post 'init', (doc) -> doc.wasTeacher = doc.isTeacher() doc.startingEmails = _.cloneDeep(doc.get('emails')) if @get('coursePrepaidID') and not @get('coursePrepaid') Prepaid = require './Prepaid' @set('coursePrepaid', { _id: @get('coursePrepaidID') startDate: Prepaid.DEFAULT_START_DATE endDate: Prepaid.DEFAULT_END_DATE }) @set('coursePrepaidID', undefined) UserSchema.statics.hashPassword = (password) -> password = password.toLowerCase() shasum = crypto.createHash('sha512') shasum.update(salt + password) shasum.digest('hex') UserSchema.methods.verificationCode = (timestamp) -> { _id, email } = this.toObject() shasum = crypto.createHash('sha256') hash = shasum.update(timestamp + salt + _id + email).digest('hex') return "#{timestamp}:#{hash}" UserSchema.statics.privateProperties = [ 'permissions', 'email', 'mailChimp', 'firstName', 'lastName', 'gender', 'facebookID', 'gplusID', 'music', 'volume', 'aceConfig', 'employerAt', 'signedEmployerAgreement', 'emailSubscriptions', 'emails', 'activity', 'stripe', 'stripeCustomerID', 'chinaVersion', 'country', 'schoolName', 'ageRange', 'role', 'enrollmentRequestSent' ] UserSchema.statics.jsonSchema = jsonschema UserSchema.statics.editableProperties = [ 'name', 'photoURL', 'password', 'anonymous', 'wizardColor1', 'volume', 'firstName', 'lastName', 'gender', 'ageRange', 'facebookID', 'gplusID', 'emails', 'testGroupNumber', 'music', 'hourOfCode', 'hourOfCodeComplete', 'preferredLanguage', 'wizard', 'aceConfig', 'autocastDelay', 'lastLevel', 'jobProfile', 'savedEmployerFilterAlerts', 'heroConfig', 'iosIdentifierForVendor', 'siteref', 'referrer', 'schoolName', 'role', 'birthday', 'enrollmentRequestSent' ] UserSchema.statics.serverProperties = ['passwordHash', 'emailLower', 'nameLower', 'passwordReset', 'lastIP'] UserSchema.statics.candidateProperties = [ 'jobProfile', 'jobProfileApproved', 'jobProfileNotes'] UserSchema.set('toObject', { transform: (doc, ret, options) -> req = options.req return ret unless req # TODO: Make deleting properties the default, but the consequences are far reaching publicOnly = options.publicOnly delete ret[prop] for prop in User.serverProperties includePrivates = not publicOnly and (req.user and (req.user.isAdmin() or req.user._id.equals(doc._id) or req.session.amActually is doc.id)) if options.includedPrivates excludedPrivates = _.reject User.privateProperties, (prop) -> prop in options.includedPrivates else excludedPrivates = User.privateProperties delete ret[prop] for prop in excludedPrivates unless includePrivates delete ret[prop] for prop in User.candidateProperties return ret }) UserSchema.statics.makeNew = (req) -> user = new User({anonymous: true}) if global.testing # allows tests some control over user id creation newID = _.pad((User.idCounter++).toString(16), 24, '0') user.set('_id', newID) user.set 'testGroupNumber', Math.floor(Math.random() * 256) # also in app/core/auth lang = languages.languageCodeFromAcceptedLanguages req.acceptedLanguages user.set 'preferredLanguage', lang if lang[...2] isnt 'en' user.set 'preferredLanguage', 'pt-BR' if not user.get('preferredLanguage') and /br\.codecombat\.com/.test(req.get('host')) user.set 'preferredLanguage', 'zh-HANS' if not user.get('preferredLanguage') and /cn\.codecombat\.com/.test(req.get('host')) user.set 'lastIP', (req.headers['x-forwarded-for'] or req.connection.remoteAddress)?.split(/,? /)[0] user.set 'country', req.country if req.country user UserSchema.plugin plugins.NamedPlugin module.exports = User = mongoose.model('User', UserSchema) User.idCounter = 0 AchievablePlugin = require '../plugins/achievements' UserSchema.plugin(AchievablePlugin)
32878
mongoose = require 'mongoose' jsonschema = require '../../app/schemas/models/user' crypto = require 'crypto' {salt, isProduction} = require '../../server_config' mail = require '../commons/mail' log = require 'winston' plugins = require '../plugins/plugins' AnalyticsUsersActive = require './AnalyticsUsersActive' Classroom = require '../models/Classroom' languages = require '../routes/languages' _ = require 'lodash' errors = require '../commons/errors' config = require '../../server_config' stripe = require('stripe')(config.stripe.secretKey) sendwithus = require '../sendwithus' UserSchema = new mongoose.Schema({ dateCreated: type: Date 'default': Date.now }, {strict: false}) UserSchema.index({'dateCreated': 1}) UserSchema.index({'emailLower': 1}, {unique: true, sparse: true, name: 'emailLower_1'}) UserSchema.index({'facebookID': 1}, {sparse: true}) UserSchema.index({'gplusID': 1}, {sparse: true}) UserSchema.index({'iosIdentifierForVendor': 1}, {name: 'iOS identifier for vendor', sparse: true, unique: true}) UserSchema.index({'mailChimp.leid': 1}, {sparse: true}) UserSchema.index({'nameLower': 1}, {sparse: true, name: 'nameLower_1'}) UserSchema.index({'simulatedBy': 1}) UserSchema.index({'slug': 1}, {name: 'slug index', sparse: true, unique: true}) UserSchema.index({'stripe.subscriptionID': 1}, {unique: true, sparse: true}) UserSchema.index({'siteref': 1}, {name: 'siteref index', sparse: true}) UserSchema.index({'schoolName': 1}, {name: 'schoolName index', sparse: true}) UserSchema.index({'country': 1}, {name: 'country index', sparse: true}) UserSchema.index({'role': 1}, {name: 'role index', sparse: true}) UserSchema.index({'coursePrepaid._id': 1}, {name: 'course prepaid id index', sparse: true}) UserSchema.post('init', -> @set('anonymous', false) if @get('email') ) UserSchema.methods.broadName = -> return '(deleted)' if @get('deleted') name = _.filter([@get('firstName'), @get('lastName')]).join(' ') return name if name name = @get('name') return name if name [emailName, emailDomain] = @get('email').split('@') return emailName if emailName return 'Anonymous' UserSchema.methods.isInGodMode = -> p = @get('permissions') return p and 'godmode' in p UserSchema.methods.isAdmin = -> p = @get('permissions') return p and 'admin' in p UserSchema.methods.hasPermission = (neededPermissions) -> permissions = @get('permissions') or [] if _.contains(permissions, 'admin') return true if _.isString(neededPermissions) neededPermissions = [neededPermissions] return _.size(_.intersection(permissions, neededPermissions)) UserSchema.methods.isArtisan = -> p = @get('permissions') return p and 'artisan' in p UserSchema.methods.isAnonymous = -> @get 'anonymous' UserSchema.statics.teacherRoles = ['teacher', 'technology coordinator', 'advisor', 'principal', 'superintendent', 'parent'] UserSchema.methods.isTeacher = -> return @get('role') in User.teacherRoles UserSchema.methods.isStudent = -> return @get('role') is 'student' UserSchema.methods.getUserInfo = -> id: @get('_id') email: if @get('anonymous') then 'Unregistered User' else @get('email') UserSchema.methods.removeFromClassrooms = -> userID = @get('_id') yield Classroom.update( { members: userID } { $addToSet: { deletedMembers: userID } $pull: { members: userID } } { multi: true } ) UserSchema.methods.trackActivity = (activityName, increment) -> now = new Date() increment ?= parseInt increment or 1 increment = Math.max increment, 0 activity = @get('activity') ? {} activity[activityName] ?= {first: now, count: 0} activity[activityName].count += increment activity[activityName].last = now @set 'activity', activity activity UserSchema.statics.search = (term, done) -> utils = require '../lib/utils' if utils.isID(term) query = {_id: mongoose.Types.ObjectId(term)} else term = term.toLowerCase() query = $or: [{nameLower: term}, {emailLower: term}] return User.findOne(query).exec(done) UserSchema.statics.findByEmail = (email, done=_.noop) -> emailLower = email.toLowerCase() User.findOne({emailLower: emailLower}).exec(done) UserSchema.statics.findByName = (name, done=_.noop) -> nameLower = name.toLowerCase() User.findOne({nameLower: nameLower}).exec(done) emailNameMap = generalNews: 'announcement' adventurerNews: 'tester' artisanNews: 'level_creator' archmageNews: 'developer' scribeNews: 'article_editor' diplomatNews: 'translator' ambassadorNews: 'support' anyNotes: 'notification' teacherNews: 'teacher' UserSchema.methods.setEmailSubscription = (newName, enabled) -> oldSubs = _.clone @get('emailSubscriptions') if oldSubs and oldName = emailNameMap[newName] oldSubs = (s for s in oldSubs when s isnt oldName) oldSubs.push(oldName) if enabled @set('emailSubscriptions', oldSubs) newSubs = _.clone(@get('emails') or _.cloneDeep(jsonschema.properties.emails.default)) newSubs[newName] ?= {} newSubs[newName].enabled = enabled @set('emails', newSubs) @newsSubsChanged = true if newName in mail.NEWS_GROUPS UserSchema.methods.gems = -> gemsEarned = @get('earned')?.gems ? 0 gemsEarned = gemsEarned + 100000 if @isInGodMode() gemsPurchased = @get('purchased')?.gems ? 0 gemsSpent = @get('spent') ? 0 gemsEarned + gemsPurchased - gemsSpent UserSchema.methods.isEmailSubscriptionEnabled = (newName) -> emails = @get 'emails' if not emails oldSubs = @get('emailSubscriptions') oldName = emailNameMap[newName] return oldName and oldName in oldSubs if oldSubs emails ?= {} _.defaults emails, _.cloneDeep(jsonschema.properties.emails.default) return emails[newName]?.enabled UserSchema.statics.updateServiceSettings = (doc, callback) -> return callback?() unless isProduction or GLOBAL.testing return callback?() if doc.updatedMailChimp return callback?() unless doc.get('email') return callback?() unless doc.get('dateCreated') accountAgeMinutes = (new Date().getTime() - doc.get('dateCreated').getTime?() ? 0) / 1000 / 60 return callback?() unless accountAgeMinutes > 30 or GLOBAL.testing existingProps = doc.get('mailChimp') emailChanged = (not existingProps) or existingProps?.email isnt doc.get('email') if emailChanged and customerID = doc.get('stripe')?.customerID unless stripe?.customers console.error('Oh my god, Stripe is not imported correctly-how could we have done this (again)?') stripe?.customers?.update customerID, {email:doc.get('email')}, (err, customer) -> console.error('Error updating stripe customer...', err) if err return callback?() unless emailChanged or doc.newsSubsChanged newGroups = [] for [mailchimpEmailGroup, emailGroup] in _.zip(mail.MAILCHIMP_GROUPS, mail.NEWS_GROUPS) newGroups.push(mailchimpEmailGroup) if doc.isEmailSubscriptionEnabled(emailGroup) if (not existingProps) and newGroups.length is 0 return callback?() # don't add totally unsubscribed people to the list params = {} params.id = mail.MAILCHIMP_LIST_ID params.email = if existingProps then {leid: existingProps.leid} else {email: doc.get('email')} params.merge_vars = { groupings: [{id: mail.MAILCHIMP_GROUP_ID, groups: newGroups}] 'new-email': doc.get('email') } params.update_existing = true onSuccess = (data) -> data.email = doc.get('email') # Make sure that we don't spam opt-in emails even if MailChimp doesn't update the email it gets in this object until they have confirmed. doc.set('mailChimp', data) doc.updatedMailChimp = true doc.save() callback?() onFailure = (error) -> log.error 'failed to subscribe', error, callback? doc.updatedMailChimp = true callback?() mc?.lists.subscribe params, onSuccess, onFailure UserSchema.statics.statsMapping = edits: article: 'stats.articleEdits' level: 'stats.levelEdits' 'level.component': 'stats.levelComponentEdits' 'level.system': 'stats.levelSystemEdits' 'thang.type': 'stats.thangTypeEdits' 'Achievement': 'stats.achievementEdits' 'campaign': 'stats.campaignEdits' 'poll': 'stats.pollEdits' translations: article: 'stats.articleTranslationPatches' level: 'stats.levelTranslationPatches' 'level.component': 'stats.levelComponentTranslationPatches' 'level.system': 'stats.levelSystemTranslationPatches' 'thang.type': 'stats.thangTypeTranslationPatches' 'Achievement': 'stats.achievementTranslationPatches' 'campaign': 'stats.campaignTranslationPatches' 'poll': 'stats.pollTranslationPatches' misc: article: 'stats.articleMiscPatches' level: 'stats.levelMiscPatches' 'level.component': 'stats.levelComponentMiscPatches' 'level.system': 'stats.levelSystemMiscPatches' 'thang.type': 'stats.thangTypeMiscPatches' 'Achievement': 'stats.achievementMiscPatches' 'campaign': 'stats.campaignMiscPatches' 'poll': 'stats.pollMiscPatches' UserSchema.statics.incrementStat = (id, statName, done, inc=1) -> id = mongoose.Types.ObjectId id if _.isString id @findById id, (err, user) -> log.error err if err? err = new Error "Could't find user with id '#{id}'" unless user or err return done() if err? user.incrementStat statName, done, inc UserSchema.methods.incrementStat = (statName, done, inc=1) -> if /^concepts\./.test statName # Concept stats are nested a level deeper. concepts = @get('concepts') or {} concept = statName.split('.')[1] concepts[concept] = (concepts[concept] or 0) + inc @set 'concepts', concepts else @set statName, (@get(statName) or 0) + inc @save (err) -> done?(err) UserSchema.statics.unconflictName = unconflictName = (name, done) -> User.findOne {slug: _.str.slugify(name)}, (err, otherUser) -> return done err if err? return done null, name unless otherUser suffix = _.random(0, 9) + '' unconflictName name + suffix, done UserSchema.methods.sendWelcomeEmail = -> return if not @get('email') { welcome_email_student, welcome_email_user } = sendwithus.templates timestamp = (new Date).getTime() data = email_id: if @isStudent() then welcome_email_student else welcome_email_user recipient: address: @get('email') name: @broadName() email_data: name: @broadName() verify_link: "http://codecombat.com/user/#{@_id}/verify/#{@verificationCode(timestamp)}" sendwithus.api.send data, (err, result) -> log.error "sendwithus post-save error: #{err}, result: #{result}" if err UserSchema.methods.hasSubscription = -> return false unless stripeObject = @get('stripe') return true if stripeObject.sponsorID return true if stripeObject.subscriptionID return true if stripeObject.free is true return true if _.isString(stripeObject.free) and new Date() < new Date(stripeObject.free) UserSchema.methods.isPremium = -> return true if @isInGodMode() return true if @isAdmin() return true if @hasSubscription() return false UserSchema.methods.isOnPremiumServer = -> @get('country') in ['china', 'brazil'] UserSchema.methods.level = -> xp = @get('points') or 0 a = 5 b = c = 100 if xp > 0 then Math.floor(a * Math.log((1 / b) * (xp + c))) + 1 else 1 UserSchema.methods.isEnrolled = -> coursePrepaid = @get('coursePrepaid') return false unless coursePrepaid return true unless coursePrepaid.endDate return coursePrepaid.endDate > new Date().toISOString() UserSchema.statics.saveActiveUser = (id, event, done=null) -> # TODO: Disabling this until we know why our app servers CPU grows out of control. return done?() id = mongoose.Types.ObjectId id if _.isString id @findById id, (err, user) -> if err? log.error err else user?.saveActiveUser event done?() UserSchema.methods.saveActiveUser = (event, done=null) -> # TODO: Disabling this until we know why our app servers CPU grows out of control. return done?() try return done?() if @isAdmin() userID = @get('_id') # Create if no active user entry for today today = new Date() minDate = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate())) AnalyticsUsersActive.findOne({created: {$gte: minDate}, creator: mongoose.Types.ObjectId(userID)}).exec (err, activeUser) -> if err? log.error "saveActiveUser error retrieving active users: #{err}" else if not activeUser newActiveUser = new AnalyticsUsersActive() newActiveUser.set 'creator', userID newActiveUser.set 'event', event newActiveUser.save (err) -> log.error "Level session saveActiveUser error saving active user: #{err}" if err? done?() catch err log.error err done?() UserSchema.pre('save', (next) -> if _.isNaN(@get('purchased')?.gems) return next(new errors.InternalServerError('Attempting to save NaN to user')) Classroom = require './Classroom' if @isTeacher() and not @wasTeacher Classroom.update({members: @_id}, {$pull: {members: @_id}}, {multi: true}).exec (err, res) -> if email = @get('email') @set('emailLower', email.toLowerCase()) else @set('email', undefined) @set('emailLower', undefined) if name = @get('name') filter = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,63}$/i # https://news.ycombinator.com/item?id=5763990 if filter.test(name) return next(new errors.UnprocessableEntity('Name may not be an email')) @set('nameLower', name.toLowerCase()) else @set('name', undefined) @set('nameLower', undefined) unless email or name or @get('anonymous') or @get('deleted') return next(new errors.UnprocessableEntity('User needs a username or email address')) pwd = @<PASSWORD>('<PASSWORD>') if @get('password') @set('passwordHash', User.hashPassword(pwd)) @set('password', undefined) next() ) UserSchema.post 'save', (doc) -> doc.newsSubsChanged = not _.isEqual(_.pick(doc.get('emails'), mail.NEWS_GROUPS), _.pick(doc.startingEmails, mail.NEWS_GROUPS)) UserSchema.statics.updateServiceSettings(doc) UserSchema.post 'init', (doc) -> doc.wasTeacher = doc.isTeacher() doc.startingEmails = _.cloneDeep(doc.get('emails')) if @get('coursePrepaidID') and not @get('coursePrepaid') Prepaid = require './Prepaid' @set('coursePrepaid', { _id: @get('coursePrepaidID') startDate: Prepaid.DEFAULT_START_DATE endDate: Prepaid.DEFAULT_END_DATE }) @set('coursePrepaidID', undefined) UserSchema.statics.hashPassword = (password) -> password = <PASSWORD>() shasum = crypto.createHash('sha512') shasum.update(salt + password) shasum.digest('hex') UserSchema.methods.verificationCode = (timestamp) -> { _id, email } = this.toObject() shasum = crypto.createHash('sha256') hash = shasum.update(timestamp + salt + _id + email).digest('hex') return "#{timestamp}:#{hash}" UserSchema.statics.privateProperties = [ 'permissions', 'email', 'mailChimp', '<NAME>', '<NAME>', 'gender', 'facebookID', 'gplusID', 'music', 'volume', 'aceConfig', 'employerAt', 'signedEmployerAgreement', 'emailSubscriptions', 'emails', 'activity', 'stripe', 'stripeCustomerID', 'chinaVersion', 'country', 'schoolName', 'ageRange', 'role', 'enrollmentRequestSent' ] UserSchema.statics.jsonSchema = jsonschema UserSchema.statics.editableProperties = [ 'name', 'photoURL', 'password', 'anonymous', 'wizardColor1', 'volume', '<NAME>', '<NAME>', 'gender', 'ageRange', 'facebookID', 'gplusID', 'emails', 'testGroupNumber', 'music', 'hourOfCode', 'hourOfCodeComplete', 'preferredLanguage', 'wizard', 'aceConfig', 'autocastDelay', 'lastLevel', 'jobProfile', 'savedEmployerFilterAlerts', 'heroConfig', 'iosIdentifierForVendor', 'siteref', 'referrer', 'schoolName', 'role', 'birthday', 'enrollmentRequestSent' ] UserSchema.statics.serverProperties = ['passwordHash', 'emailLower', 'nameLower', 'passwordReset', 'lastIP'] UserSchema.statics.candidateProperties = [ 'jobProfile', 'jobProfileApproved', 'jobProfileNotes'] UserSchema.set('toObject', { transform: (doc, ret, options) -> req = options.req return ret unless req # TODO: Make deleting properties the default, but the consequences are far reaching publicOnly = options.publicOnly delete ret[prop] for prop in User.serverProperties includePrivates = not publicOnly and (req.user and (req.user.isAdmin() or req.user._id.equals(doc._id) or req.session.amActually is doc.id)) if options.includedPrivates excludedPrivates = _.reject User.privateProperties, (prop) -> prop in options.includedPrivates else excludedPrivates = User.privateProperties delete ret[prop] for prop in excludedPrivates unless includePrivates delete ret[prop] for prop in User.candidateProperties return ret }) UserSchema.statics.makeNew = (req) -> user = new User({anonymous: true}) if global.testing # allows tests some control over user id creation newID = _.pad((User.idCounter++).toString(16), 24, '0') user.set('_id', newID) user.set 'testGroupNumber', Math.floor(Math.random() * 256) # also in app/core/auth lang = languages.languageCodeFromAcceptedLanguages req.acceptedLanguages user.set 'preferredLanguage', lang if lang[...2] isnt 'en' user.set 'preferredLanguage', 'pt-BR' if not user.get('preferredLanguage') and /br\.codecombat\.com/.test(req.get('host')) user.set 'preferredLanguage', 'zh-HANS' if not user.get('preferredLanguage') and /cn\.codecombat\.com/.test(req.get('host')) user.set 'lastIP', (req.headers['x-forwarded-for'] or req.connection.remoteAddress)?.split(/,? /)[0] user.set 'country', req.country if req.country user UserSchema.plugin plugins.NamedPlugin module.exports = User = mongoose.model('User', UserSchema) User.idCounter = 0 AchievablePlugin = require '../plugins/achievements' UserSchema.plugin(AchievablePlugin)
true
mongoose = require 'mongoose' jsonschema = require '../../app/schemas/models/user' crypto = require 'crypto' {salt, isProduction} = require '../../server_config' mail = require '../commons/mail' log = require 'winston' plugins = require '../plugins/plugins' AnalyticsUsersActive = require './AnalyticsUsersActive' Classroom = require '../models/Classroom' languages = require '../routes/languages' _ = require 'lodash' errors = require '../commons/errors' config = require '../../server_config' stripe = require('stripe')(config.stripe.secretKey) sendwithus = require '../sendwithus' UserSchema = new mongoose.Schema({ dateCreated: type: Date 'default': Date.now }, {strict: false}) UserSchema.index({'dateCreated': 1}) UserSchema.index({'emailLower': 1}, {unique: true, sparse: true, name: 'emailLower_1'}) UserSchema.index({'facebookID': 1}, {sparse: true}) UserSchema.index({'gplusID': 1}, {sparse: true}) UserSchema.index({'iosIdentifierForVendor': 1}, {name: 'iOS identifier for vendor', sparse: true, unique: true}) UserSchema.index({'mailChimp.leid': 1}, {sparse: true}) UserSchema.index({'nameLower': 1}, {sparse: true, name: 'nameLower_1'}) UserSchema.index({'simulatedBy': 1}) UserSchema.index({'slug': 1}, {name: 'slug index', sparse: true, unique: true}) UserSchema.index({'stripe.subscriptionID': 1}, {unique: true, sparse: true}) UserSchema.index({'siteref': 1}, {name: 'siteref index', sparse: true}) UserSchema.index({'schoolName': 1}, {name: 'schoolName index', sparse: true}) UserSchema.index({'country': 1}, {name: 'country index', sparse: true}) UserSchema.index({'role': 1}, {name: 'role index', sparse: true}) UserSchema.index({'coursePrepaid._id': 1}, {name: 'course prepaid id index', sparse: true}) UserSchema.post('init', -> @set('anonymous', false) if @get('email') ) UserSchema.methods.broadName = -> return '(deleted)' if @get('deleted') name = _.filter([@get('firstName'), @get('lastName')]).join(' ') return name if name name = @get('name') return name if name [emailName, emailDomain] = @get('email').split('@') return emailName if emailName return 'Anonymous' UserSchema.methods.isInGodMode = -> p = @get('permissions') return p and 'godmode' in p UserSchema.methods.isAdmin = -> p = @get('permissions') return p and 'admin' in p UserSchema.methods.hasPermission = (neededPermissions) -> permissions = @get('permissions') or [] if _.contains(permissions, 'admin') return true if _.isString(neededPermissions) neededPermissions = [neededPermissions] return _.size(_.intersection(permissions, neededPermissions)) UserSchema.methods.isArtisan = -> p = @get('permissions') return p and 'artisan' in p UserSchema.methods.isAnonymous = -> @get 'anonymous' UserSchema.statics.teacherRoles = ['teacher', 'technology coordinator', 'advisor', 'principal', 'superintendent', 'parent'] UserSchema.methods.isTeacher = -> return @get('role') in User.teacherRoles UserSchema.methods.isStudent = -> return @get('role') is 'student' UserSchema.methods.getUserInfo = -> id: @get('_id') email: if @get('anonymous') then 'Unregistered User' else @get('email') UserSchema.methods.removeFromClassrooms = -> userID = @get('_id') yield Classroom.update( { members: userID } { $addToSet: { deletedMembers: userID } $pull: { members: userID } } { multi: true } ) UserSchema.methods.trackActivity = (activityName, increment) -> now = new Date() increment ?= parseInt increment or 1 increment = Math.max increment, 0 activity = @get('activity') ? {} activity[activityName] ?= {first: now, count: 0} activity[activityName].count += increment activity[activityName].last = now @set 'activity', activity activity UserSchema.statics.search = (term, done) -> utils = require '../lib/utils' if utils.isID(term) query = {_id: mongoose.Types.ObjectId(term)} else term = term.toLowerCase() query = $or: [{nameLower: term}, {emailLower: term}] return User.findOne(query).exec(done) UserSchema.statics.findByEmail = (email, done=_.noop) -> emailLower = email.toLowerCase() User.findOne({emailLower: emailLower}).exec(done) UserSchema.statics.findByName = (name, done=_.noop) -> nameLower = name.toLowerCase() User.findOne({nameLower: nameLower}).exec(done) emailNameMap = generalNews: 'announcement' adventurerNews: 'tester' artisanNews: 'level_creator' archmageNews: 'developer' scribeNews: 'article_editor' diplomatNews: 'translator' ambassadorNews: 'support' anyNotes: 'notification' teacherNews: 'teacher' UserSchema.methods.setEmailSubscription = (newName, enabled) -> oldSubs = _.clone @get('emailSubscriptions') if oldSubs and oldName = emailNameMap[newName] oldSubs = (s for s in oldSubs when s isnt oldName) oldSubs.push(oldName) if enabled @set('emailSubscriptions', oldSubs) newSubs = _.clone(@get('emails') or _.cloneDeep(jsonschema.properties.emails.default)) newSubs[newName] ?= {} newSubs[newName].enabled = enabled @set('emails', newSubs) @newsSubsChanged = true if newName in mail.NEWS_GROUPS UserSchema.methods.gems = -> gemsEarned = @get('earned')?.gems ? 0 gemsEarned = gemsEarned + 100000 if @isInGodMode() gemsPurchased = @get('purchased')?.gems ? 0 gemsSpent = @get('spent') ? 0 gemsEarned + gemsPurchased - gemsSpent UserSchema.methods.isEmailSubscriptionEnabled = (newName) -> emails = @get 'emails' if not emails oldSubs = @get('emailSubscriptions') oldName = emailNameMap[newName] return oldName and oldName in oldSubs if oldSubs emails ?= {} _.defaults emails, _.cloneDeep(jsonschema.properties.emails.default) return emails[newName]?.enabled UserSchema.statics.updateServiceSettings = (doc, callback) -> return callback?() unless isProduction or GLOBAL.testing return callback?() if doc.updatedMailChimp return callback?() unless doc.get('email') return callback?() unless doc.get('dateCreated') accountAgeMinutes = (new Date().getTime() - doc.get('dateCreated').getTime?() ? 0) / 1000 / 60 return callback?() unless accountAgeMinutes > 30 or GLOBAL.testing existingProps = doc.get('mailChimp') emailChanged = (not existingProps) or existingProps?.email isnt doc.get('email') if emailChanged and customerID = doc.get('stripe')?.customerID unless stripe?.customers console.error('Oh my god, Stripe is not imported correctly-how could we have done this (again)?') stripe?.customers?.update customerID, {email:doc.get('email')}, (err, customer) -> console.error('Error updating stripe customer...', err) if err return callback?() unless emailChanged or doc.newsSubsChanged newGroups = [] for [mailchimpEmailGroup, emailGroup] in _.zip(mail.MAILCHIMP_GROUPS, mail.NEWS_GROUPS) newGroups.push(mailchimpEmailGroup) if doc.isEmailSubscriptionEnabled(emailGroup) if (not existingProps) and newGroups.length is 0 return callback?() # don't add totally unsubscribed people to the list params = {} params.id = mail.MAILCHIMP_LIST_ID params.email = if existingProps then {leid: existingProps.leid} else {email: doc.get('email')} params.merge_vars = { groupings: [{id: mail.MAILCHIMP_GROUP_ID, groups: newGroups}] 'new-email': doc.get('email') } params.update_existing = true onSuccess = (data) -> data.email = doc.get('email') # Make sure that we don't spam opt-in emails even if MailChimp doesn't update the email it gets in this object until they have confirmed. doc.set('mailChimp', data) doc.updatedMailChimp = true doc.save() callback?() onFailure = (error) -> log.error 'failed to subscribe', error, callback? doc.updatedMailChimp = true callback?() mc?.lists.subscribe params, onSuccess, onFailure UserSchema.statics.statsMapping = edits: article: 'stats.articleEdits' level: 'stats.levelEdits' 'level.component': 'stats.levelComponentEdits' 'level.system': 'stats.levelSystemEdits' 'thang.type': 'stats.thangTypeEdits' 'Achievement': 'stats.achievementEdits' 'campaign': 'stats.campaignEdits' 'poll': 'stats.pollEdits' translations: article: 'stats.articleTranslationPatches' level: 'stats.levelTranslationPatches' 'level.component': 'stats.levelComponentTranslationPatches' 'level.system': 'stats.levelSystemTranslationPatches' 'thang.type': 'stats.thangTypeTranslationPatches' 'Achievement': 'stats.achievementTranslationPatches' 'campaign': 'stats.campaignTranslationPatches' 'poll': 'stats.pollTranslationPatches' misc: article: 'stats.articleMiscPatches' level: 'stats.levelMiscPatches' 'level.component': 'stats.levelComponentMiscPatches' 'level.system': 'stats.levelSystemMiscPatches' 'thang.type': 'stats.thangTypeMiscPatches' 'Achievement': 'stats.achievementMiscPatches' 'campaign': 'stats.campaignMiscPatches' 'poll': 'stats.pollMiscPatches' UserSchema.statics.incrementStat = (id, statName, done, inc=1) -> id = mongoose.Types.ObjectId id if _.isString id @findById id, (err, user) -> log.error err if err? err = new Error "Could't find user with id '#{id}'" unless user or err return done() if err? user.incrementStat statName, done, inc UserSchema.methods.incrementStat = (statName, done, inc=1) -> if /^concepts\./.test statName # Concept stats are nested a level deeper. concepts = @get('concepts') or {} concept = statName.split('.')[1] concepts[concept] = (concepts[concept] or 0) + inc @set 'concepts', concepts else @set statName, (@get(statName) or 0) + inc @save (err) -> done?(err) UserSchema.statics.unconflictName = unconflictName = (name, done) -> User.findOne {slug: _.str.slugify(name)}, (err, otherUser) -> return done err if err? return done null, name unless otherUser suffix = _.random(0, 9) + '' unconflictName name + suffix, done UserSchema.methods.sendWelcomeEmail = -> return if not @get('email') { welcome_email_student, welcome_email_user } = sendwithus.templates timestamp = (new Date).getTime() data = email_id: if @isStudent() then welcome_email_student else welcome_email_user recipient: address: @get('email') name: @broadName() email_data: name: @broadName() verify_link: "http://codecombat.com/user/#{@_id}/verify/#{@verificationCode(timestamp)}" sendwithus.api.send data, (err, result) -> log.error "sendwithus post-save error: #{err}, result: #{result}" if err UserSchema.methods.hasSubscription = -> return false unless stripeObject = @get('stripe') return true if stripeObject.sponsorID return true if stripeObject.subscriptionID return true if stripeObject.free is true return true if _.isString(stripeObject.free) and new Date() < new Date(stripeObject.free) UserSchema.methods.isPremium = -> return true if @isInGodMode() return true if @isAdmin() return true if @hasSubscription() return false UserSchema.methods.isOnPremiumServer = -> @get('country') in ['china', 'brazil'] UserSchema.methods.level = -> xp = @get('points') or 0 a = 5 b = c = 100 if xp > 0 then Math.floor(a * Math.log((1 / b) * (xp + c))) + 1 else 1 UserSchema.methods.isEnrolled = -> coursePrepaid = @get('coursePrepaid') return false unless coursePrepaid return true unless coursePrepaid.endDate return coursePrepaid.endDate > new Date().toISOString() UserSchema.statics.saveActiveUser = (id, event, done=null) -> # TODO: Disabling this until we know why our app servers CPU grows out of control. return done?() id = mongoose.Types.ObjectId id if _.isString id @findById id, (err, user) -> if err? log.error err else user?.saveActiveUser event done?() UserSchema.methods.saveActiveUser = (event, done=null) -> # TODO: Disabling this until we know why our app servers CPU grows out of control. return done?() try return done?() if @isAdmin() userID = @get('_id') # Create if no active user entry for today today = new Date() minDate = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate())) AnalyticsUsersActive.findOne({created: {$gte: minDate}, creator: mongoose.Types.ObjectId(userID)}).exec (err, activeUser) -> if err? log.error "saveActiveUser error retrieving active users: #{err}" else if not activeUser newActiveUser = new AnalyticsUsersActive() newActiveUser.set 'creator', userID newActiveUser.set 'event', event newActiveUser.save (err) -> log.error "Level session saveActiveUser error saving active user: #{err}" if err? done?() catch err log.error err done?() UserSchema.pre('save', (next) -> if _.isNaN(@get('purchased')?.gems) return next(new errors.InternalServerError('Attempting to save NaN to user')) Classroom = require './Classroom' if @isTeacher() and not @wasTeacher Classroom.update({members: @_id}, {$pull: {members: @_id}}, {multi: true}).exec (err, res) -> if email = @get('email') @set('emailLower', email.toLowerCase()) else @set('email', undefined) @set('emailLower', undefined) if name = @get('name') filter = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,63}$/i # https://news.ycombinator.com/item?id=5763990 if filter.test(name) return next(new errors.UnprocessableEntity('Name may not be an email')) @set('nameLower', name.toLowerCase()) else @set('name', undefined) @set('nameLower', undefined) unless email or name or @get('anonymous') or @get('deleted') return next(new errors.UnprocessableEntity('User needs a username or email address')) pwd = @PI:PASSWORD:<PASSWORD>END_PI('PI:PASSWORD:<PASSWORD>END_PI') if @get('password') @set('passwordHash', User.hashPassword(pwd)) @set('password', undefined) next() ) UserSchema.post 'save', (doc) -> doc.newsSubsChanged = not _.isEqual(_.pick(doc.get('emails'), mail.NEWS_GROUPS), _.pick(doc.startingEmails, mail.NEWS_GROUPS)) UserSchema.statics.updateServiceSettings(doc) UserSchema.post 'init', (doc) -> doc.wasTeacher = doc.isTeacher() doc.startingEmails = _.cloneDeep(doc.get('emails')) if @get('coursePrepaidID') and not @get('coursePrepaid') Prepaid = require './Prepaid' @set('coursePrepaid', { _id: @get('coursePrepaidID') startDate: Prepaid.DEFAULT_START_DATE endDate: Prepaid.DEFAULT_END_DATE }) @set('coursePrepaidID', undefined) UserSchema.statics.hashPassword = (password) -> password = PI:PASSWORD:<PASSWORD>END_PI() shasum = crypto.createHash('sha512') shasum.update(salt + password) shasum.digest('hex') UserSchema.methods.verificationCode = (timestamp) -> { _id, email } = this.toObject() shasum = crypto.createHash('sha256') hash = shasum.update(timestamp + salt + _id + email).digest('hex') return "#{timestamp}:#{hash}" UserSchema.statics.privateProperties = [ 'permissions', 'email', 'mailChimp', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'gender', 'facebookID', 'gplusID', 'music', 'volume', 'aceConfig', 'employerAt', 'signedEmployerAgreement', 'emailSubscriptions', 'emails', 'activity', 'stripe', 'stripeCustomerID', 'chinaVersion', 'country', 'schoolName', 'ageRange', 'role', 'enrollmentRequestSent' ] UserSchema.statics.jsonSchema = jsonschema UserSchema.statics.editableProperties = [ 'name', 'photoURL', 'password', 'anonymous', 'wizardColor1', 'volume', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'gender', 'ageRange', 'facebookID', 'gplusID', 'emails', 'testGroupNumber', 'music', 'hourOfCode', 'hourOfCodeComplete', 'preferredLanguage', 'wizard', 'aceConfig', 'autocastDelay', 'lastLevel', 'jobProfile', 'savedEmployerFilterAlerts', 'heroConfig', 'iosIdentifierForVendor', 'siteref', 'referrer', 'schoolName', 'role', 'birthday', 'enrollmentRequestSent' ] UserSchema.statics.serverProperties = ['passwordHash', 'emailLower', 'nameLower', 'passwordReset', 'lastIP'] UserSchema.statics.candidateProperties = [ 'jobProfile', 'jobProfileApproved', 'jobProfileNotes'] UserSchema.set('toObject', { transform: (doc, ret, options) -> req = options.req return ret unless req # TODO: Make deleting properties the default, but the consequences are far reaching publicOnly = options.publicOnly delete ret[prop] for prop in User.serverProperties includePrivates = not publicOnly and (req.user and (req.user.isAdmin() or req.user._id.equals(doc._id) or req.session.amActually is doc.id)) if options.includedPrivates excludedPrivates = _.reject User.privateProperties, (prop) -> prop in options.includedPrivates else excludedPrivates = User.privateProperties delete ret[prop] for prop in excludedPrivates unless includePrivates delete ret[prop] for prop in User.candidateProperties return ret }) UserSchema.statics.makeNew = (req) -> user = new User({anonymous: true}) if global.testing # allows tests some control over user id creation newID = _.pad((User.idCounter++).toString(16), 24, '0') user.set('_id', newID) user.set 'testGroupNumber', Math.floor(Math.random() * 256) # also in app/core/auth lang = languages.languageCodeFromAcceptedLanguages req.acceptedLanguages user.set 'preferredLanguage', lang if lang[...2] isnt 'en' user.set 'preferredLanguage', 'pt-BR' if not user.get('preferredLanguage') and /br\.codecombat\.com/.test(req.get('host')) user.set 'preferredLanguage', 'zh-HANS' if not user.get('preferredLanguage') and /cn\.codecombat\.com/.test(req.get('host')) user.set 'lastIP', (req.headers['x-forwarded-for'] or req.connection.remoteAddress)?.split(/,? /)[0] user.set 'country', req.country if req.country user UserSchema.plugin plugins.NamedPlugin module.exports = User = mongoose.model('User', UserSchema) User.idCounter = 0 AchievablePlugin = require '../plugins/achievements' UserSchema.plugin(AchievablePlugin)
[ { "context": "godb Plugin', ->\n before ->\n @turtleNames = ['Donatello', 'Leonardo', 'Michelangelo', 'Raphael']\n\n befor", "end": 210, "score": 0.9998538494110107, "start": 201, "tag": "NAME", "value": "Donatello" }, { "context": " ->\n before ->\n @turtleNames = ['Donatello', 'Leonardo', 'Michelangelo', 'Raphael']\n\n beforeEach ->\n ", "end": 222, "score": 0.9998103976249695, "start": 214, "tag": "NAME", "value": "Leonardo" }, { "context": " ->\n @turtleNames = ['Donatello', 'Leonardo', 'Michelangelo', 'Raphael']\n\n beforeEach ->\n @turtles = for ", "end": 238, "score": 0.9998420476913452, "start": 226, "tag": "NAME", "value": "Michelangelo" }, { "context": "ames = ['Donatello', 'Leonardo', 'Michelangelo', 'Raphael']\n\n beforeEach ->\n @turtles = for name, i in ", "end": 249, "score": 0.9998385906219482, "start": 242, "tag": "NAME", "value": "Raphael" }, { "context": "->\n resource = 'beatles'\n data = name: 'John Lennon'\n req = resource: resource\n res = resul", "end": 2228, "score": 0.9998605251312256, "start": 2217, "tag": "NAME", "value": "John Lennon" } ]
test/test_plugin_mongodb.coffee
kr1sp1n/hotcoffee-mongodb
0
# file: test/test_plugin_mongodb.coffee should = require 'should' sinon = require 'sinon' EventEmitter = require('events').EventEmitter describe 'mongodb Plugin', -> before -> @turtleNames = ['Donatello', 'Leonardo', 'Michelangelo', 'Raphael'] beforeEach -> @turtles = for name, i in @turtleNames { _id: i+1, props: { name: name, id: i+1 }, links: [] } @links = {} for name1, i in @turtleNames @links[name1] = [] for name2, j in @turtleNames if name1 != name2 @links[name1].push { rel: 'brother', href: "link to #{name2}", type: 'application/json' } @app = new EventEmitter() @app.db = {} @db = collectionNames: sinon.stub() collection: sinon.stub() @collection = find: sinon.stub() toArray: sinon.stub() insert: sinon.stub() update: sinon.stub() remove: sinon.stub() @collection.toArray.yields null, @turtles @collection.find.returns @collection @db.collection.returns @collection @db.collectionNames.callsArgWith 0, null, [{name:'testdb.turtle'}] @client = connect: sinon.stub() @client.connect.callsArgWith 1, null, @db # stub callback @opts = url: "fake_mongodb_url" client: @client @plugin = require("#{__dirname}/../index")(@app, @opts) it 'should expose its right name', -> @plugin.name.should.equal 'mongodb' describe 'connect(done)', -> it 'should connect to MongoDB if opts.url is set', (done)-> @plugin.connect (err)=> done err it 'should return an error if no MongoDB URL was set', (done)-> @plugin.opts.url = null @plugin.connect (err)=> should(err).be.ok err.message.should.equal "No MongoDB URL set" done null describe 'loadCollection(resource)', -> it 'should load MongoDB collections in the app DB', -> resource = 'turtle' @plugin.loadCollection resource @db.collection.called.should.be.ok @db.collection.calledWith(resource).should.be.ok @app.db[resource].should.equal @turtles describe 'registerEvents()', -> it 'should listen on "POST" events from the app', -> resource = 'beatles' data = name: 'John Lennon' req = resource: resource res = result: [data] @plugin.registerEvents() @app.emit 'POST', req, res @db.collection.calledWith(resource).should.be.ok @collection.insert.called.should.be.ok @collection.insert.calledWith(data).should.be.ok it 'should listen on "PATCH" events from the app', -> resource = 'turtle' items = @turtles data = status: 'hungry' req = resource: resource, body: data res = result: items @plugin.registerEvents() @app.emit 'PATCH', req, res @collection.update.called.should.be.ok it 'should listen on "DELETE" events from the app', -> resource = 'turtle' items = @turtles req = resource: resource res = result: items @plugin.registerEvents() @app.emit 'DELETE', req, res @collection.remove.called.should.be.ok it 'should listen on "PUT" events from the app', -> resource = 'turtle' items = @turtles data = links: [ { rel: 'master', href: 'link to Splinter', type: 'application/json' } ] req = resource: resource, body: data res = result: items @plugin.registerEvents() @app.emit 'PUT', req, res @collection.update.called.should.be.ok
46742
# file: test/test_plugin_mongodb.coffee should = require 'should' sinon = require 'sinon' EventEmitter = require('events').EventEmitter describe 'mongodb Plugin', -> before -> @turtleNames = ['<NAME>', '<NAME>', '<NAME>', '<NAME>'] beforeEach -> @turtles = for name, i in @turtleNames { _id: i+1, props: { name: name, id: i+1 }, links: [] } @links = {} for name1, i in @turtleNames @links[name1] = [] for name2, j in @turtleNames if name1 != name2 @links[name1].push { rel: 'brother', href: "link to #{name2}", type: 'application/json' } @app = new EventEmitter() @app.db = {} @db = collectionNames: sinon.stub() collection: sinon.stub() @collection = find: sinon.stub() toArray: sinon.stub() insert: sinon.stub() update: sinon.stub() remove: sinon.stub() @collection.toArray.yields null, @turtles @collection.find.returns @collection @db.collection.returns @collection @db.collectionNames.callsArgWith 0, null, [{name:'testdb.turtle'}] @client = connect: sinon.stub() @client.connect.callsArgWith 1, null, @db # stub callback @opts = url: "fake_mongodb_url" client: @client @plugin = require("#{__dirname}/../index")(@app, @opts) it 'should expose its right name', -> @plugin.name.should.equal 'mongodb' describe 'connect(done)', -> it 'should connect to MongoDB if opts.url is set', (done)-> @plugin.connect (err)=> done err it 'should return an error if no MongoDB URL was set', (done)-> @plugin.opts.url = null @plugin.connect (err)=> should(err).be.ok err.message.should.equal "No MongoDB URL set" done null describe 'loadCollection(resource)', -> it 'should load MongoDB collections in the app DB', -> resource = 'turtle' @plugin.loadCollection resource @db.collection.called.should.be.ok @db.collection.calledWith(resource).should.be.ok @app.db[resource].should.equal @turtles describe 'registerEvents()', -> it 'should listen on "POST" events from the app', -> resource = 'beatles' data = name: '<NAME>' req = resource: resource res = result: [data] @plugin.registerEvents() @app.emit 'POST', req, res @db.collection.calledWith(resource).should.be.ok @collection.insert.called.should.be.ok @collection.insert.calledWith(data).should.be.ok it 'should listen on "PATCH" events from the app', -> resource = 'turtle' items = @turtles data = status: 'hungry' req = resource: resource, body: data res = result: items @plugin.registerEvents() @app.emit 'PATCH', req, res @collection.update.called.should.be.ok it 'should listen on "DELETE" events from the app', -> resource = 'turtle' items = @turtles req = resource: resource res = result: items @plugin.registerEvents() @app.emit 'DELETE', req, res @collection.remove.called.should.be.ok it 'should listen on "PUT" events from the app', -> resource = 'turtle' items = @turtles data = links: [ { rel: 'master', href: 'link to Splinter', type: 'application/json' } ] req = resource: resource, body: data res = result: items @plugin.registerEvents() @app.emit 'PUT', req, res @collection.update.called.should.be.ok
true
# file: test/test_plugin_mongodb.coffee should = require 'should' sinon = require 'sinon' EventEmitter = require('events').EventEmitter describe 'mongodb Plugin', -> before -> @turtleNames = ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] beforeEach -> @turtles = for name, i in @turtleNames { _id: i+1, props: { name: name, id: i+1 }, links: [] } @links = {} for name1, i in @turtleNames @links[name1] = [] for name2, j in @turtleNames if name1 != name2 @links[name1].push { rel: 'brother', href: "link to #{name2}", type: 'application/json' } @app = new EventEmitter() @app.db = {} @db = collectionNames: sinon.stub() collection: sinon.stub() @collection = find: sinon.stub() toArray: sinon.stub() insert: sinon.stub() update: sinon.stub() remove: sinon.stub() @collection.toArray.yields null, @turtles @collection.find.returns @collection @db.collection.returns @collection @db.collectionNames.callsArgWith 0, null, [{name:'testdb.turtle'}] @client = connect: sinon.stub() @client.connect.callsArgWith 1, null, @db # stub callback @opts = url: "fake_mongodb_url" client: @client @plugin = require("#{__dirname}/../index")(@app, @opts) it 'should expose its right name', -> @plugin.name.should.equal 'mongodb' describe 'connect(done)', -> it 'should connect to MongoDB if opts.url is set', (done)-> @plugin.connect (err)=> done err it 'should return an error if no MongoDB URL was set', (done)-> @plugin.opts.url = null @plugin.connect (err)=> should(err).be.ok err.message.should.equal "No MongoDB URL set" done null describe 'loadCollection(resource)', -> it 'should load MongoDB collections in the app DB', -> resource = 'turtle' @plugin.loadCollection resource @db.collection.called.should.be.ok @db.collection.calledWith(resource).should.be.ok @app.db[resource].should.equal @turtles describe 'registerEvents()', -> it 'should listen on "POST" events from the app', -> resource = 'beatles' data = name: 'PI:NAME:<NAME>END_PI' req = resource: resource res = result: [data] @plugin.registerEvents() @app.emit 'POST', req, res @db.collection.calledWith(resource).should.be.ok @collection.insert.called.should.be.ok @collection.insert.calledWith(data).should.be.ok it 'should listen on "PATCH" events from the app', -> resource = 'turtle' items = @turtles data = status: 'hungry' req = resource: resource, body: data res = result: items @plugin.registerEvents() @app.emit 'PATCH', req, res @collection.update.called.should.be.ok it 'should listen on "DELETE" events from the app', -> resource = 'turtle' items = @turtles req = resource: resource res = result: items @plugin.registerEvents() @app.emit 'DELETE', req, res @collection.remove.called.should.be.ok it 'should listen on "PUT" events from the app', -> resource = 'turtle' items = @turtles data = links: [ { rel: 'master', href: 'link to Splinter', type: 'application/json' } ] req = resource: resource, body: data res = result: items @plugin.registerEvents() @app.emit 'PUT', req, res @collection.update.called.should.be.ok
[ { "context": "(\"service:session\"))\n i.userParams =\n email: \"test@test.test\"\n password: \"password123\"\n Cookies.remove \"_a", "end": 213, "score": 0.9999059438705444, "start": 199, "tag": "EMAIL", "value": "test@test.test" }, { "context": "rams =\n email: \"test@test.test\"\n password: \"password123\"\n Cookies.remove \"_apiv4_key\"\n Cookies.remove \"", "end": 241, "score": 0.9992067217826843, "start": 230, "tag": "PASSWORD", "value": "password123" } ]
tests/helpers/apiv4-fixtures.coffee
simwms/apiv4
2
store = (i) -> i.application.__container__.lookup("service:store") loginAccount = (i) -> i.session = (session = i.application.__container__.lookup("service:session")) i.userParams = email: "test@test.test" password: "password123" Cookies.remove "_apiv4_key" Cookies.remove "remember-token" i.session.login(i.userParams) .then => i.session .get("model") .get("user") .then (user) => i.user = user user.get("accounts") .then (accounts) => i.account = (account = accounts.objectAt(0)) session.update({account}) createCompany = (i) -> i.company = store(i).createRecord "company", name: "Test Co. #{Math.random()}" i.company.save() i.company createAppointment = (i) -> company = i.company ? createCompany(i) i.appointment = store(i).createRecord "appointment", company: company externalReference: "scaffold-test-#{Math.random()}" description: "this is a test of the appointment creation system" i.appointment.save() i.appointment createTruck = (i) -> appointment = i.appointment ? createAppointment(i) i.truck = store(i).createRecord "truck", {appointment} i.truck.save() i.truck `export {loginAccount, createCompany, createAppointment, createTruck, store}`
77165
store = (i) -> i.application.__container__.lookup("service:store") loginAccount = (i) -> i.session = (session = i.application.__container__.lookup("service:session")) i.userParams = email: "<EMAIL>" password: "<PASSWORD>" Cookies.remove "_apiv4_key" Cookies.remove "remember-token" i.session.login(i.userParams) .then => i.session .get("model") .get("user") .then (user) => i.user = user user.get("accounts") .then (accounts) => i.account = (account = accounts.objectAt(0)) session.update({account}) createCompany = (i) -> i.company = store(i).createRecord "company", name: "Test Co. #{Math.random()}" i.company.save() i.company createAppointment = (i) -> company = i.company ? createCompany(i) i.appointment = store(i).createRecord "appointment", company: company externalReference: "scaffold-test-#{Math.random()}" description: "this is a test of the appointment creation system" i.appointment.save() i.appointment createTruck = (i) -> appointment = i.appointment ? createAppointment(i) i.truck = store(i).createRecord "truck", {appointment} i.truck.save() i.truck `export {loginAccount, createCompany, createAppointment, createTruck, store}`
true
store = (i) -> i.application.__container__.lookup("service:store") loginAccount = (i) -> i.session = (session = i.application.__container__.lookup("service:session")) i.userParams = email: "PI:EMAIL:<EMAIL>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" Cookies.remove "_apiv4_key" Cookies.remove "remember-token" i.session.login(i.userParams) .then => i.session .get("model") .get("user") .then (user) => i.user = user user.get("accounts") .then (accounts) => i.account = (account = accounts.objectAt(0)) session.update({account}) createCompany = (i) -> i.company = store(i).createRecord "company", name: "Test Co. #{Math.random()}" i.company.save() i.company createAppointment = (i) -> company = i.company ? createCompany(i) i.appointment = store(i).createRecord "appointment", company: company externalReference: "scaffold-test-#{Math.random()}" description: "this is a test of the appointment creation system" i.appointment.save() i.appointment createTruck = (i) -> appointment = i.appointment ? createAppointment(i) i.truck = store(i).createRecord "truck", {appointment} i.truck.save() i.truck `export {loginAccount, createCompany, createAppointment, createTruck, store}`
[ { "context": "ude default font: ###\n continue if psname is 'Iosevka-Slab'\n ### !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "end": 17567, "score": 0.6795914769172668, "start": 17556, "tag": "NAME", "value": "osevka-Slab" } ]
dev/kitty-font-config-writer-kfcw/src/main.coffee
loveencounterflow/hengist
0
# portals! 'use strict' ############################################################################################################ CND = require 'cnd' badge = 'kittyfonts' rpr = CND.rpr log = CND.get_logger 'plain', badge info = CND.get_logger 'info', badge whisper = CND.get_logger 'whisper', badge alert = CND.get_logger 'alert', badge debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge echo = CND.echo.bind CND #........................................................................................................... PATH = require 'path' FS = require 'fs' OS = require 'os' FS = require 'fs' hex = ( n ) -> ( n.toString 16 ).toUpperCase().padStart 4, '0' LAP = require '../../../apps/interlap' { type_of isa validate equals } = LAP.types.export() #----------------------------------------------------------------------------------------------------------- to_width = ( text, width ) -> ### TAINT use `to_width` module ### validate.text text validate.positive_integer width return text[ .. width ].padEnd width, ' ' #=========================================================================================================== # PERTAINING TO SPECIFIC SETTINGS / FONT CHOICES #----------------------------------------------------------------------------------------------------------- S = use_disjunct_ranges: false write_pua_sample: true write_ranges_sample: true write_special_interest_sample: true # source_path: '../../../assets/write-font-configuration-for-kitty-terminal.sample-data.json' paths: # configured_cid_ranges: '../../../../ucdb/cfg/styles-codepoints-and-fontnicks.txt' configured_cid_ranges: '../../../assets/ucdb/styles-codepoints-and-fontnicks.short.txt' cid_ranges_by_rsgs: '../../../../ucdb/cfg/rsgs-and-blocks.txt' kitty_fonts_conf: '~/.config/kitty/kitty-fonts.conf' psname_by_fontnicks: babelstonehan: 'BabelStoneHan' cwtexqheibold: 'cwTeXQHei-Bold' dejavuserif: 'DejaVuSerif' hanaminaotf: 'HanaMinA' hanaminbotf: 'HanaMinB' hanamina: 'HanaMinA' hanaminb: 'HanaMinB' ipamp: 'IPAPMincho' jizurathreeb: 'jizura3b' nanummyeongjo: 'NanumMyeongjo' sunexta: 'Sun-ExtA' thtshynpone: 'TH-Tshyn-P1' thtshynptwo: 'TH-Tshyn-P2' thtshynpzero: 'TH-Tshyn-P0' umingttcone: 'UMingCN' takaopgothic: 'TakaoGothic' # @default # asanamath ebgaramondtwelveregular: 'Iosevka-Slab' # hanaminexatwootf: '' lmromantenregular: 'Iosevka-Slab' iosevkaslab: 'Iosevka-Slab' # sourcehanserifheavytaiwan: '' # unifonttwelve: '' lastresort: 'LastResort' illegal_codepoints: null # illegal_codepoints: [ # see https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Special_code_points # [ 0x0000, 0x0000, ] # zero # [ 0x0001, 0x001f, ] # lower controls # [ 0x007f, 0x009f, ] # higher controls # [ 0xd800, 0xdfff, ] # surrogates # [ 0xfdd0, 0xfdef, ] # [ 0xfffe, 0xffff, ] # [ 0x1fffe, 0x1ffff, ] # [ 0x2fffe, 0x2ffff, ] # [ 0x3fffe, 0x3ffff, ] # [ 0x4fffe, 0x4ffff, ] # [ 0x5fffe, 0x5ffff, ] # [ 0x6fffe, 0x6ffff, ] # [ 0x7fffe, 0x7ffff, ] # [ 0x8fffe, 0x8ffff, ] # [ 0x9fffe, 0x9ffff, ] # [ 0xafffe, 0xaffff, ] # [ 0xbfffe, 0xbffff, ] # [ 0xcfffe, 0xcffff, ] # [ 0xdfffe, 0xdffff, ] # [ 0xefffe, 0xeffff, ] # [ 0xffffe, 0xfffff, ] # [ 0x10fffe, 0x10ffff, ] ] illegal_codepoint_patterns: [ ///^\p{Cc}$///u # Control ///^\p{Cs}$///u # Surrogate # ///^\p{Cn}$///u # Unassigned ] #=========================================================================================================== # GENERIC STUFF #----------------------------------------------------------------------------------------------------------- cid_range_pattern = ///^ 0x (?<first_cid_txt> [0-9a-fA-F]+ ) \.\. 0x (?<last_cid_txt> [0-9a-fA-F]+ ) $ /// parse_cid_hex_range_txt = ( cid_range_txt ) -> unless ( match = cid_range_txt.match cid_range_pattern )? throw new Error "^33736^ unable to parse CID range #{rpr cid_range_txt}" { first_cid_txt last_cid_txt } = match.groups first_cid = parseInt first_cid_txt, 16 last_cid = parseInt last_cid_txt, 16 return [ first_cid, last_cid, ] #----------------------------------------------------------------------------------------------------------- segment_from_cid_hex_range_txt = ( cid_range_txt ) -> new LAP.Segment parse_cid_hex_range_txt cid_range_txt #----------------------------------------------------------------------------------------------------------- @_read_cid_ranges_by_rsgs = ( settings ) -> return R if ( R = settings.cid_ranges_by_rsgs )? R = settings.cid_ranges_by_rsgs = {} source_path = PATH.resolve PATH.join __dirname, settings.paths.cid_ranges_by_rsgs lines = ( FS.readFileSync source_path, { encoding: 'utf-8', } ).split '\n' for line, line_idx in lines line = line.replace /^\s+$/g, '' continue if ( line.length is 0 ) or ( /^\s*#/.test line ) [ icgroup, rsg, is_cjk_txt, cid_range_txt, range_name..., ] = line.split /\s+/ continue if rsg.startsWith 'u-x-' try R[ rsg ] = segment_from_cid_hex_range_txt cid_range_txt catch error throw new Error "^4445^ illegal line: #{error.message}, line_nr: #{line_idx + 1}, line: #{rpr line}" return R # #----------------------------------------------------------------------------------------------------------- # @_read_illegal_codepoints = ( settings ) -> # return R if isa.interlap ( R = settings.illegal_codepoints ) # R = settings.illegal_codepoints = new LAP.Interlap settings.illegal_codepoints # return R #----------------------------------------------------------------------------------------------------------- @_segment_from_cid_literal = ( settings, cid_literal ) -> cid_ranges_by_rsgs = @_read_cid_ranges_by_rsgs settings #....................................................................................................... if cid_literal is '*' return new LAP.Segment [ 0x000000, 0x10ffff, ] #....................................................................................................... else if ( cid_literal.startsWith "'" ) and ( cid_literal.endsWith "'" ) validate.chr chr = cid_literal[ 1 ... cid_literal.length - 1 ] first_cid = chr.codePointAt 0 last_cid = first_cid return new LAP.Segment [ first_cid, last_cid, ] #....................................................................................................... else if ( cid_literal.startsWith 'rsg:' ) rsg = cid_literal[ 4 .. ] validate.nonempty_text rsg unless ( segment = cid_ranges_by_rsgs[ rsg ] )? throw new Error "^4445^ illegal line: unknown rsg: #{rpr rsg}, line_nr: #{line_nr}, line: #{rpr line}" return segment #....................................................................................................... else try return segment_from_cid_hex_range_txt cid_literal catch error throw new Error "^4445^ illegal line: #{error.message}, line_nr: #{line_nr}, line: #{rpr line}" #....................................................................................................... throw new Error "^4445^ illegal line: unable to parse CID range; line_nr: #{line_nr}, line: #{rpr line}" return null #----------------------------------------------------------------------------------------------------------- @_read_configured_cid_ranges = ( settings ) -> R = settings.configured_cid_ranges = [] source_path = PATH.resolve PATH.join __dirname, settings.paths.configured_cid_ranges lines = ( FS.readFileSync source_path, { encoding: 'utf-8', } ).split '\n' unknown_fontnicks = new Set() for line, line_idx in lines line_nr = line_idx + 1 line = line.replace /^\s+$/g, '' continue if ( line.length is 0 ) or ( /^\s*#/.test line ) [ styletag, cid_literal, fontnick, glyphstyle..., ] = line.split /\s+/ glyphstyle = glyphstyle.join ' ' validate.nonempty_text styletag validate.nonempty_text cid_literal validate.nonempty_text fontnick validate.text glyphstyle # continue unless fontnick? # continue unless first_cid? # continue unless last_cid? #....................................................................................................... unless styletag is '+style:ming' whisper "^776^ skipping line_nr: #{line_nr} b/c of styletag: #{rpr styletag}" continue #....................................................................................................... if glyphstyle? and /\bglyph\b/.test glyphstyle whisper "^776^ skipping line_nr: #{line_nr} b/c of glyphstyle: #{rpr glyphstyle}" continue #....................................................................................................... unless ( psname = settings.psname_by_fontnicks[ fontnick ] )? unless unknown_fontnicks.has fontnick unknown_fontnicks.add fontnick warn "unknown fontnick #{rpr fontnick} on linenr: #{line_nr} (only noting first occurrence)" continue #....................................................................................................... if cid_literal is '*' debug '^778^', { styletag, cid_literal, fontnick, } settings.default_fontnick ?= fontnick settings.default_psname ?= psname continue #....................................................................................................... segment = @_segment_from_cid_literal settings, cid_literal #....................................................................................................... ### NOTE for this particular file format, we could use segments instead of laps since there can be only one segment per record; however, for consistency with those cases where several disjunct segments per record are allowed, we use laps. ### ### TAINT consider to use a non-committal name like `cids` instead of `lap`, which is bound to a particular data type; allow to use segments and laps for this and similar attributes. ### lap = new LAP.Interlap segment R.push { fontnick, psname, lap, } return R #----------------------------------------------------------------------------------------------------------- @_read_configured_cid_ranges_as_laps = ( settings ) -> R = [] for { fontnick, psname, lap, } in @_read_configured_cid_ranges settings for segment in lap R.push { fontnick, psname, segment, } return R #----------------------------------------------------------------------------------------------------------- @_read_disjunct_cid_ranges = ( settings ) -> overlaps = @_read_configured_cid_ranges settings R = settings.disjunct_cid_ranges = [] org_by_fontnicks = {} exclusion = @_read_illegal_codepoints settings for idx in [ overlaps.length - 1 .. 0 ] by -1 rule = overlaps[ idx ] { fontnick psname lap } = rule disjunct = LAP.difference lap, exclusion exclusion = LAP.union lap, exclusion R.unshift { fontnick, psname, lap: disjunct, } return R #----------------------------------------------------------------------------------------------------------- @_read_disjunct_cid_segments = ( settings ) -> R = [] for disjunct_range in @_read_disjunct_cid_ranges settings { fontnick psname lap } = disjunct_range for segment in lap continue if segment.size is 0 # should never happen R.push { fontnick, psname, segment, } R.sort ( a, b ) -> return -1 if a.segment.lo < b.segment.lo return +1 if a.segment.lo < b.segment.lo return 0 return R #----------------------------------------------------------------------------------------------------------- @_write_method_from_path = ( settings, path = null ) -> return echo unless path? validate.nonempty_text path path = PATH.join OS.homedir(), path.replace /^~/, '' try FS.statSync path catch error throw error unless error.code is 'ENOENT' warn "^729^target path #{rpr path} does not exist" throw error FS.writeFileSync path, '' return write = ( line ) -> validate.text line FS.appendFileSync path, line + '\n' #----------------------------------------------------------------------------------------------------------- @_write_ranges_sample = ( settings, write ) -> for disjunct_range in settings.fontnicks_and_segments { fontnick psname segment } = disjunct_range # help fontnick, LAP.as_unicode_range lap unicode_range_txt = ( LAP.as_unicode_range segment ).padEnd 30 sample = ( String.fromCodePoint c for c in [ segment.lo .. segment.hi ][ .. 30 ] ) sample_txt = sample.join '' sample_txt = sample_txt.replace /[\x00-\x20]+/g, '' sample_txt = sample_txt.replace /[\x80-\x9f]+/g, '' sample_txt = sample_txt.replace /[\u2000-\u200f]+/g, '' sample_txt = sample_txt.replace /\s+/g, '' psname_txt = psname.padEnd 30 write "# symbol_map #{unicode_range_txt} #{psname_txt} # #{sample_txt}" #----------------------------------------------------------------------------------------------------------- @_write_pua_sample = ( settings, write ) -> for row_cid in [ 0xe000 .. 0xe3a0 ] by 0x10 row = [] for col_cid in [ 0x00 .. 0x0f ] cid = row_cid + col_cid row.push String.fromCodePoint cid row_cid_txt = "U+#{( row_cid.toString 16 ).padStart 4, '0'}" write "# #{row_cid_txt} #{row.join ''}" #----------------------------------------------------------------------------------------------------------- @_write_special_interest_sample = ( settings, write ) -> write '# x𒇷x' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' write '# x﷽x' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' write '# x𒇷 x' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' write '# x﷽ x' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' write '# ' write '# ' write '#  (32 chrs)' write '# | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |' write '# 豈更車賈滑串句龜龜契金喇奈懶癩羅蘿螺裸邏樂洛烙珞落酪駱亂卵欄爛金 (32 chrs)' write '# ■□▢▣▤▥▦▧▨▩▪▫▬▭▮▯▰▱▲' write '# ԀԁԂԃԄԅԆԇԈԉԊԋԌԍԎԏԐԑԒԓԔԕԖԗԘԙԚԛԜԝԞ' write '# ⤀⤁⤂⤃⤄⤅⤆⤇⤈⤉⤊⤋⤌⤍⤎⤏⤐⤑⤒⤓⤔⤕⤖⤗⤘⤙⤚⤛⤜⤝⤞' write '# ℀℁ℂ℃℄℅℆ℇ℈℉ℊℋℌℍℎℏℐℑℒℓ℔ℕ№℗℘ℙℚℛℜℝ℞' write '# ℀℁ℂ℃ ℄℅℆ℇ℈℉ℊℋℌℍℎℏℐℑℒℓ℔ℕ№℗℘ℙℚℛℜℝ℞' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' #----------------------------------------------------------------------------------------------------------- @write_font_configuration_for_kitty_terminal = ( settings ) -> write = @_write_method_from_path settings, settings.paths.kitty_fonts_conf #......................................................................................................... if settings.use_disjunct_ranges ? false settings.fontnicks_and_segments = @_read_disjunct_cid_segments settings else settings.fontnicks_and_segments = @_read_configured_cid_ranges_as_laps settings #......................................................................................................... @_write_special_interest_sample settings, write if settings.write_special_interest_sample ? false @_write_ranges_sample settings, write if settings.write_ranges_sample ? false @_write_pua_sample settings, write if settings.write_pua_sample ? false #......................................................................................................... unless settings.default_psname? warn "^334^ no default font configured" urge "^334^ add settings.default_fontnick" urge "^334^ or add CID range with asterisk in #{PATH.resolve settings.paths.configured_cid_ranges}" else write "font_family #{settings.default_psname}" write "bold_font auto" write "italic_font auto" write "bold_italic_font auto" #......................................................................................................... for disjunct_range in settings.fontnicks_and_segments { fontnick psname segment } = disjunct_range ### !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ### ### exclude default font: ### continue if psname is 'Iosevka-Slab' ### !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ### unicode_range_txt = ( LAP.as_unicode_range segment ).padEnd 30 write "symbol_map #{unicode_range_txt} #{psname}" #......................................................................................................... return null #----------------------------------------------------------------------------------------------------------- @write_whisk_character_tunnel = ( settings ) -> # https://www.aivosto.com/articles/control-characters.html#APC chr_ranges = "[\\ue000-\\uefff]" source = """#!/usr/bin/env node const pattern = /(#{chr_ranges})/g; const rl = require( 'readline' ).createInterface({ input: process.stdin, output: process.stdout, terminal: false }) rl.on( 'line', ( line ) => { return process.stdout.write( line.replace( pattern, '$1 ' ) + '\\n' ); } ); """ # #!/usr/bin/env node # const pattern_2 = /([\ue000-\uefff])/ug; # const pattern_3 = /([\ufb50-\ufdff])/ug; # const pattern_7 = /([\u{12000}-\u{123ff}])/ug; # const rl = require( 'readline' ).createInterface({ # input: process.stdin, # output: process.stdout, # terminal: false }) # rl.on( 'line', ( line ) => { # return process.stdout.write( # line # .replace( pattern_2, '$1 ' ) # .replace( pattern_3, '$1 ' ) # .replace( pattern_7, '$1 ' ) # + '\n' ); } ); echo() echo source echo() # path = ??? # FS.writeFileSync path, source return null #=========================================================================================================== # DATA STRUCTURE DEMOS #----------------------------------------------------------------------------------------------------------- @demo_cid_ranges_by_rsgs = -> echo CND.steel CND.reverse "CID Ranges by RSGs".padEnd 108 for rsg, segment of @_read_cid_ranges_by_rsgs S continue unless /kana|kata|hira/.test rsg rsg_txt = ( rsg.padEnd 25 ) range_txt = LAP.as_unicode_range segment echo ( CND.grey "rsg and CID range" ), ( CND.blue rsg_txt ), ( CND.lime range_txt ) return null #----------------------------------------------------------------------------------------------------------- @demo_configured_ranges = -> echo CND.steel CND.reverse "Configured CID Ranges".padEnd 108 for configured_range in @_read_configured_cid_ranges S { fontnick psname lap } = configured_range font_txt = ( psname.padEnd 25 ) range_txt = LAP.as_unicode_range lap # echo ( CND.grey "configured range" ), ( CND.yellow configured_range ) echo ( CND.grey "configured range" ), ( CND.yellow font_txt ), ( CND.lime range_txt ) return null #----------------------------------------------------------------------------------------------------------- @demo_disjunct_ranges = -> echo CND.steel CND.reverse "Disjunct CID Ranges".padEnd 108 for disjunct_range in @_read_disjunct_cid_ranges S { fontnick psname lap } = disjunct_range font_txt = ( psname.padEnd 25 ) if lap.size is 0 echo ( CND.grey "disjunct range" ), ( CND.grey font_txt ), ( CND.grey "no codepoints" ) else for segment in lap range_txt = LAP.as_unicode_range segment echo ( CND.grey "disjunct range" ), ( CND.yellow font_txt ), ( CND.lime range_txt ) return null #----------------------------------------------------------------------------------------------------------- @demo_kitty_font_config = -> echo CND.steel CND.reverse "Kitty Font Config".padEnd 108 @write_font_configuration_for_kitty_terminal S #----------------------------------------------------------------------------------------------------------- @_read_illegal_codepoints = ( settings ) -> return R if ( R = settings.illegal_codepoints )? segments = [] ranges = [ { lo: 0x0000, hi: 0xe000, } { lo: 0xf900, hi: 0xffff, } # { lo: 0x10000, hi: 0x1ffff, } # { lo: 0x20000, hi: 0x2ffff, } # { lo: 0x30000, hi: 0x3ffff, } # { lo: 0x0000, hi: 0x10ffff, } ] for range in ranges prv_cid = null for cid in [ range.lo .. range.hi ] if settings.illegal_codepoint_patterns.some ( re ) -> re.test String.fromCodePoint cid segments.push [ cid, cid, ] R = settings.illegal_codepoints = new LAP.Interlap segments help "excluding #{R.size} codepoints" return R #----------------------------------------------------------------------------------------------------------- @demo_illegal_codepoints = -> lap = @_read_illegal_codepoints S for segment in lap urge LAP.as_unicode_range segment return null ############################################################################################################ if module is require.main then do => # @demo_illegal_codepoints() # @demo_cid_ranges_by_rsgs() # @demo_configured_ranges() # @demo_disjunct_ranges() # @demo_kitty_font_config() #......................................................................................................... @write_font_configuration_for_kitty_terminal S # @write_whisk_character_tunnel S ############################################################################################################ ### NOTE original version has problems with these entries: # 3002 # symbol_map U+3000-U+303f HanaMinA # 2e81 # symbol_map U+2e80-U+2eff Sun-ExtA # 31c2 # symbol_map U+31c0-U+31ef Sun-ExtA # 3404 # symbol_map U+3400-U+4dbf Sun-ExtA ############################################################################################################
210152
# portals! 'use strict' ############################################################################################################ CND = require 'cnd' badge = 'kittyfonts' rpr = CND.rpr log = CND.get_logger 'plain', badge info = CND.get_logger 'info', badge whisper = CND.get_logger 'whisper', badge alert = CND.get_logger 'alert', badge debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge echo = CND.echo.bind CND #........................................................................................................... PATH = require 'path' FS = require 'fs' OS = require 'os' FS = require 'fs' hex = ( n ) -> ( n.toString 16 ).toUpperCase().padStart 4, '0' LAP = require '../../../apps/interlap' { type_of isa validate equals } = LAP.types.export() #----------------------------------------------------------------------------------------------------------- to_width = ( text, width ) -> ### TAINT use `to_width` module ### validate.text text validate.positive_integer width return text[ .. width ].padEnd width, ' ' #=========================================================================================================== # PERTAINING TO SPECIFIC SETTINGS / FONT CHOICES #----------------------------------------------------------------------------------------------------------- S = use_disjunct_ranges: false write_pua_sample: true write_ranges_sample: true write_special_interest_sample: true # source_path: '../../../assets/write-font-configuration-for-kitty-terminal.sample-data.json' paths: # configured_cid_ranges: '../../../../ucdb/cfg/styles-codepoints-and-fontnicks.txt' configured_cid_ranges: '../../../assets/ucdb/styles-codepoints-and-fontnicks.short.txt' cid_ranges_by_rsgs: '../../../../ucdb/cfg/rsgs-and-blocks.txt' kitty_fonts_conf: '~/.config/kitty/kitty-fonts.conf' psname_by_fontnicks: babelstonehan: 'BabelStoneHan' cwtexqheibold: 'cwTeXQHei-Bold' dejavuserif: 'DejaVuSerif' hanaminaotf: 'HanaMinA' hanaminbotf: 'HanaMinB' hanamina: 'HanaMinA' hanaminb: 'HanaMinB' ipamp: 'IPAPMincho' jizurathreeb: 'jizura3b' nanummyeongjo: 'NanumMyeongjo' sunexta: 'Sun-ExtA' thtshynpone: 'TH-Tshyn-P1' thtshynptwo: 'TH-Tshyn-P2' thtshynpzero: 'TH-Tshyn-P0' umingttcone: 'UMingCN' takaopgothic: 'TakaoGothic' # @default # asanamath ebgaramondtwelveregular: 'Iosevka-Slab' # hanaminexatwootf: '' lmromantenregular: 'Iosevka-Slab' iosevkaslab: 'Iosevka-Slab' # sourcehanserifheavytaiwan: '' # unifonttwelve: '' lastresort: 'LastResort' illegal_codepoints: null # illegal_codepoints: [ # see https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Special_code_points # [ 0x0000, 0x0000, ] # zero # [ 0x0001, 0x001f, ] # lower controls # [ 0x007f, 0x009f, ] # higher controls # [ 0xd800, 0xdfff, ] # surrogates # [ 0xfdd0, 0xfdef, ] # [ 0xfffe, 0xffff, ] # [ 0x1fffe, 0x1ffff, ] # [ 0x2fffe, 0x2ffff, ] # [ 0x3fffe, 0x3ffff, ] # [ 0x4fffe, 0x4ffff, ] # [ 0x5fffe, 0x5ffff, ] # [ 0x6fffe, 0x6ffff, ] # [ 0x7fffe, 0x7ffff, ] # [ 0x8fffe, 0x8ffff, ] # [ 0x9fffe, 0x9ffff, ] # [ 0xafffe, 0xaffff, ] # [ 0xbfffe, 0xbffff, ] # [ 0xcfffe, 0xcffff, ] # [ 0xdfffe, 0xdffff, ] # [ 0xefffe, 0xeffff, ] # [ 0xffffe, 0xfffff, ] # [ 0x10fffe, 0x10ffff, ] ] illegal_codepoint_patterns: [ ///^\p{Cc}$///u # Control ///^\p{Cs}$///u # Surrogate # ///^\p{Cn}$///u # Unassigned ] #=========================================================================================================== # GENERIC STUFF #----------------------------------------------------------------------------------------------------------- cid_range_pattern = ///^ 0x (?<first_cid_txt> [0-9a-fA-F]+ ) \.\. 0x (?<last_cid_txt> [0-9a-fA-F]+ ) $ /// parse_cid_hex_range_txt = ( cid_range_txt ) -> unless ( match = cid_range_txt.match cid_range_pattern )? throw new Error "^33736^ unable to parse CID range #{rpr cid_range_txt}" { first_cid_txt last_cid_txt } = match.groups first_cid = parseInt first_cid_txt, 16 last_cid = parseInt last_cid_txt, 16 return [ first_cid, last_cid, ] #----------------------------------------------------------------------------------------------------------- segment_from_cid_hex_range_txt = ( cid_range_txt ) -> new LAP.Segment parse_cid_hex_range_txt cid_range_txt #----------------------------------------------------------------------------------------------------------- @_read_cid_ranges_by_rsgs = ( settings ) -> return R if ( R = settings.cid_ranges_by_rsgs )? R = settings.cid_ranges_by_rsgs = {} source_path = PATH.resolve PATH.join __dirname, settings.paths.cid_ranges_by_rsgs lines = ( FS.readFileSync source_path, { encoding: 'utf-8', } ).split '\n' for line, line_idx in lines line = line.replace /^\s+$/g, '' continue if ( line.length is 0 ) or ( /^\s*#/.test line ) [ icgroup, rsg, is_cjk_txt, cid_range_txt, range_name..., ] = line.split /\s+/ continue if rsg.startsWith 'u-x-' try R[ rsg ] = segment_from_cid_hex_range_txt cid_range_txt catch error throw new Error "^4445^ illegal line: #{error.message}, line_nr: #{line_idx + 1}, line: #{rpr line}" return R # #----------------------------------------------------------------------------------------------------------- # @_read_illegal_codepoints = ( settings ) -> # return R if isa.interlap ( R = settings.illegal_codepoints ) # R = settings.illegal_codepoints = new LAP.Interlap settings.illegal_codepoints # return R #----------------------------------------------------------------------------------------------------------- @_segment_from_cid_literal = ( settings, cid_literal ) -> cid_ranges_by_rsgs = @_read_cid_ranges_by_rsgs settings #....................................................................................................... if cid_literal is '*' return new LAP.Segment [ 0x000000, 0x10ffff, ] #....................................................................................................... else if ( cid_literal.startsWith "'" ) and ( cid_literal.endsWith "'" ) validate.chr chr = cid_literal[ 1 ... cid_literal.length - 1 ] first_cid = chr.codePointAt 0 last_cid = first_cid return new LAP.Segment [ first_cid, last_cid, ] #....................................................................................................... else if ( cid_literal.startsWith 'rsg:' ) rsg = cid_literal[ 4 .. ] validate.nonempty_text rsg unless ( segment = cid_ranges_by_rsgs[ rsg ] )? throw new Error "^4445^ illegal line: unknown rsg: #{rpr rsg}, line_nr: #{line_nr}, line: #{rpr line}" return segment #....................................................................................................... else try return segment_from_cid_hex_range_txt cid_literal catch error throw new Error "^4445^ illegal line: #{error.message}, line_nr: #{line_nr}, line: #{rpr line}" #....................................................................................................... throw new Error "^4445^ illegal line: unable to parse CID range; line_nr: #{line_nr}, line: #{rpr line}" return null #----------------------------------------------------------------------------------------------------------- @_read_configured_cid_ranges = ( settings ) -> R = settings.configured_cid_ranges = [] source_path = PATH.resolve PATH.join __dirname, settings.paths.configured_cid_ranges lines = ( FS.readFileSync source_path, { encoding: 'utf-8', } ).split '\n' unknown_fontnicks = new Set() for line, line_idx in lines line_nr = line_idx + 1 line = line.replace /^\s+$/g, '' continue if ( line.length is 0 ) or ( /^\s*#/.test line ) [ styletag, cid_literal, fontnick, glyphstyle..., ] = line.split /\s+/ glyphstyle = glyphstyle.join ' ' validate.nonempty_text styletag validate.nonempty_text cid_literal validate.nonempty_text fontnick validate.text glyphstyle # continue unless fontnick? # continue unless first_cid? # continue unless last_cid? #....................................................................................................... unless styletag is '+style:ming' whisper "^776^ skipping line_nr: #{line_nr} b/c of styletag: #{rpr styletag}" continue #....................................................................................................... if glyphstyle? and /\bglyph\b/.test glyphstyle whisper "^776^ skipping line_nr: #{line_nr} b/c of glyphstyle: #{rpr glyphstyle}" continue #....................................................................................................... unless ( psname = settings.psname_by_fontnicks[ fontnick ] )? unless unknown_fontnicks.has fontnick unknown_fontnicks.add fontnick warn "unknown fontnick #{rpr fontnick} on linenr: #{line_nr} (only noting first occurrence)" continue #....................................................................................................... if cid_literal is '*' debug '^778^', { styletag, cid_literal, fontnick, } settings.default_fontnick ?= fontnick settings.default_psname ?= psname continue #....................................................................................................... segment = @_segment_from_cid_literal settings, cid_literal #....................................................................................................... ### NOTE for this particular file format, we could use segments instead of laps since there can be only one segment per record; however, for consistency with those cases where several disjunct segments per record are allowed, we use laps. ### ### TAINT consider to use a non-committal name like `cids` instead of `lap`, which is bound to a particular data type; allow to use segments and laps for this and similar attributes. ### lap = new LAP.Interlap segment R.push { fontnick, psname, lap, } return R #----------------------------------------------------------------------------------------------------------- @_read_configured_cid_ranges_as_laps = ( settings ) -> R = [] for { fontnick, psname, lap, } in @_read_configured_cid_ranges settings for segment in lap R.push { fontnick, psname, segment, } return R #----------------------------------------------------------------------------------------------------------- @_read_disjunct_cid_ranges = ( settings ) -> overlaps = @_read_configured_cid_ranges settings R = settings.disjunct_cid_ranges = [] org_by_fontnicks = {} exclusion = @_read_illegal_codepoints settings for idx in [ overlaps.length - 1 .. 0 ] by -1 rule = overlaps[ idx ] { fontnick psname lap } = rule disjunct = LAP.difference lap, exclusion exclusion = LAP.union lap, exclusion R.unshift { fontnick, psname, lap: disjunct, } return R #----------------------------------------------------------------------------------------------------------- @_read_disjunct_cid_segments = ( settings ) -> R = [] for disjunct_range in @_read_disjunct_cid_ranges settings { fontnick psname lap } = disjunct_range for segment in lap continue if segment.size is 0 # should never happen R.push { fontnick, psname, segment, } R.sort ( a, b ) -> return -1 if a.segment.lo < b.segment.lo return +1 if a.segment.lo < b.segment.lo return 0 return R #----------------------------------------------------------------------------------------------------------- @_write_method_from_path = ( settings, path = null ) -> return echo unless path? validate.nonempty_text path path = PATH.join OS.homedir(), path.replace /^~/, '' try FS.statSync path catch error throw error unless error.code is 'ENOENT' warn "^729^target path #{rpr path} does not exist" throw error FS.writeFileSync path, '' return write = ( line ) -> validate.text line FS.appendFileSync path, line + '\n' #----------------------------------------------------------------------------------------------------------- @_write_ranges_sample = ( settings, write ) -> for disjunct_range in settings.fontnicks_and_segments { fontnick psname segment } = disjunct_range # help fontnick, LAP.as_unicode_range lap unicode_range_txt = ( LAP.as_unicode_range segment ).padEnd 30 sample = ( String.fromCodePoint c for c in [ segment.lo .. segment.hi ][ .. 30 ] ) sample_txt = sample.join '' sample_txt = sample_txt.replace /[\x00-\x20]+/g, '' sample_txt = sample_txt.replace /[\x80-\x9f]+/g, '' sample_txt = sample_txt.replace /[\u2000-\u200f]+/g, '' sample_txt = sample_txt.replace /\s+/g, '' psname_txt = psname.padEnd 30 write "# symbol_map #{unicode_range_txt} #{psname_txt} # #{sample_txt}" #----------------------------------------------------------------------------------------------------------- @_write_pua_sample = ( settings, write ) -> for row_cid in [ 0xe000 .. 0xe3a0 ] by 0x10 row = [] for col_cid in [ 0x00 .. 0x0f ] cid = row_cid + col_cid row.push String.fromCodePoint cid row_cid_txt = "U+#{( row_cid.toString 16 ).padStart 4, '0'}" write "# #{row_cid_txt} #{row.join ''}" #----------------------------------------------------------------------------------------------------------- @_write_special_interest_sample = ( settings, write ) -> write '# x𒇷x' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' write '# x﷽x' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' write '# x𒇷 x' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' write '# x﷽ x' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' write '# ' write '# ' write '#  (32 chrs)' write '# | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |' write '# 豈更車賈滑串句龜龜契金喇奈懶癩羅蘿螺裸邏樂洛烙珞落酪駱亂卵欄爛金 (32 chrs)' write '# ■□▢▣▤▥▦▧▨▩▪▫▬▭▮▯▰▱▲' write '# ԀԁԂԃԄԅԆԇԈԉԊԋԌԍԎԏԐԑԒԓԔԕԖԗԘԙԚԛԜԝԞ' write '# ⤀⤁⤂⤃⤄⤅⤆⤇⤈⤉⤊⤋⤌⤍⤎⤏⤐⤑⤒⤓⤔⤕⤖⤗⤘⤙⤚⤛⤜⤝⤞' write '# ℀℁ℂ℃℄℅℆ℇ℈℉ℊℋℌℍℎℏℐℑℒℓ℔ℕ№℗℘ℙℚℛℜℝ℞' write '# ℀℁ℂ℃ ℄℅℆ℇ℈℉ℊℋℌℍℎℏℐℑℒℓ℔ℕ№℗℘ℙℚℛℜℝ℞' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' #----------------------------------------------------------------------------------------------------------- @write_font_configuration_for_kitty_terminal = ( settings ) -> write = @_write_method_from_path settings, settings.paths.kitty_fonts_conf #......................................................................................................... if settings.use_disjunct_ranges ? false settings.fontnicks_and_segments = @_read_disjunct_cid_segments settings else settings.fontnicks_and_segments = @_read_configured_cid_ranges_as_laps settings #......................................................................................................... @_write_special_interest_sample settings, write if settings.write_special_interest_sample ? false @_write_ranges_sample settings, write if settings.write_ranges_sample ? false @_write_pua_sample settings, write if settings.write_pua_sample ? false #......................................................................................................... unless settings.default_psname? warn "^334^ no default font configured" urge "^334^ add settings.default_fontnick" urge "^334^ or add CID range with asterisk in #{PATH.resolve settings.paths.configured_cid_ranges}" else write "font_family #{settings.default_psname}" write "bold_font auto" write "italic_font auto" write "bold_italic_font auto" #......................................................................................................... for disjunct_range in settings.fontnicks_and_segments { fontnick psname segment } = disjunct_range ### !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ### ### exclude default font: ### continue if psname is 'I<NAME>' ### !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ### unicode_range_txt = ( LAP.as_unicode_range segment ).padEnd 30 write "symbol_map #{unicode_range_txt} #{psname}" #......................................................................................................... return null #----------------------------------------------------------------------------------------------------------- @write_whisk_character_tunnel = ( settings ) -> # https://www.aivosto.com/articles/control-characters.html#APC chr_ranges = "[\\ue000-\\uefff]" source = """#!/usr/bin/env node const pattern = /(#{chr_ranges})/g; const rl = require( 'readline' ).createInterface({ input: process.stdin, output: process.stdout, terminal: false }) rl.on( 'line', ( line ) => { return process.stdout.write( line.replace( pattern, '$1 ' ) + '\\n' ); } ); """ # #!/usr/bin/env node # const pattern_2 = /([\ue000-\uefff])/ug; # const pattern_3 = /([\ufb50-\ufdff])/ug; # const pattern_7 = /([\u{12000}-\u{123ff}])/ug; # const rl = require( 'readline' ).createInterface({ # input: process.stdin, # output: process.stdout, # terminal: false }) # rl.on( 'line', ( line ) => { # return process.stdout.write( # line # .replace( pattern_2, '$1 ' ) # .replace( pattern_3, '$1 ' ) # .replace( pattern_7, '$1 ' ) # + '\n' ); } ); echo() echo source echo() # path = ??? # FS.writeFileSync path, source return null #=========================================================================================================== # DATA STRUCTURE DEMOS #----------------------------------------------------------------------------------------------------------- @demo_cid_ranges_by_rsgs = -> echo CND.steel CND.reverse "CID Ranges by RSGs".padEnd 108 for rsg, segment of @_read_cid_ranges_by_rsgs S continue unless /kana|kata|hira/.test rsg rsg_txt = ( rsg.padEnd 25 ) range_txt = LAP.as_unicode_range segment echo ( CND.grey "rsg and CID range" ), ( CND.blue rsg_txt ), ( CND.lime range_txt ) return null #----------------------------------------------------------------------------------------------------------- @demo_configured_ranges = -> echo CND.steel CND.reverse "Configured CID Ranges".padEnd 108 for configured_range in @_read_configured_cid_ranges S { fontnick psname lap } = configured_range font_txt = ( psname.padEnd 25 ) range_txt = LAP.as_unicode_range lap # echo ( CND.grey "configured range" ), ( CND.yellow configured_range ) echo ( CND.grey "configured range" ), ( CND.yellow font_txt ), ( CND.lime range_txt ) return null #----------------------------------------------------------------------------------------------------------- @demo_disjunct_ranges = -> echo CND.steel CND.reverse "Disjunct CID Ranges".padEnd 108 for disjunct_range in @_read_disjunct_cid_ranges S { fontnick psname lap } = disjunct_range font_txt = ( psname.padEnd 25 ) if lap.size is 0 echo ( CND.grey "disjunct range" ), ( CND.grey font_txt ), ( CND.grey "no codepoints" ) else for segment in lap range_txt = LAP.as_unicode_range segment echo ( CND.grey "disjunct range" ), ( CND.yellow font_txt ), ( CND.lime range_txt ) return null #----------------------------------------------------------------------------------------------------------- @demo_kitty_font_config = -> echo CND.steel CND.reverse "Kitty Font Config".padEnd 108 @write_font_configuration_for_kitty_terminal S #----------------------------------------------------------------------------------------------------------- @_read_illegal_codepoints = ( settings ) -> return R if ( R = settings.illegal_codepoints )? segments = [] ranges = [ { lo: 0x0000, hi: 0xe000, } { lo: 0xf900, hi: 0xffff, } # { lo: 0x10000, hi: 0x1ffff, } # { lo: 0x20000, hi: 0x2ffff, } # { lo: 0x30000, hi: 0x3ffff, } # { lo: 0x0000, hi: 0x10ffff, } ] for range in ranges prv_cid = null for cid in [ range.lo .. range.hi ] if settings.illegal_codepoint_patterns.some ( re ) -> re.test String.fromCodePoint cid segments.push [ cid, cid, ] R = settings.illegal_codepoints = new LAP.Interlap segments help "excluding #{R.size} codepoints" return R #----------------------------------------------------------------------------------------------------------- @demo_illegal_codepoints = -> lap = @_read_illegal_codepoints S for segment in lap urge LAP.as_unicode_range segment return null ############################################################################################################ if module is require.main then do => # @demo_illegal_codepoints() # @demo_cid_ranges_by_rsgs() # @demo_configured_ranges() # @demo_disjunct_ranges() # @demo_kitty_font_config() #......................................................................................................... @write_font_configuration_for_kitty_terminal S # @write_whisk_character_tunnel S ############################################################################################################ ### NOTE original version has problems with these entries: # 3002 # symbol_map U+3000-U+303f HanaMinA # 2e81 # symbol_map U+2e80-U+2eff Sun-ExtA # 31c2 # symbol_map U+31c0-U+31ef Sun-ExtA # 3404 # symbol_map U+3400-U+4dbf Sun-ExtA ############################################################################################################
true
# portals! 'use strict' ############################################################################################################ CND = require 'cnd' badge = 'kittyfonts' rpr = CND.rpr log = CND.get_logger 'plain', badge info = CND.get_logger 'info', badge whisper = CND.get_logger 'whisper', badge alert = CND.get_logger 'alert', badge debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge echo = CND.echo.bind CND #........................................................................................................... PATH = require 'path' FS = require 'fs' OS = require 'os' FS = require 'fs' hex = ( n ) -> ( n.toString 16 ).toUpperCase().padStart 4, '0' LAP = require '../../../apps/interlap' { type_of isa validate equals } = LAP.types.export() #----------------------------------------------------------------------------------------------------------- to_width = ( text, width ) -> ### TAINT use `to_width` module ### validate.text text validate.positive_integer width return text[ .. width ].padEnd width, ' ' #=========================================================================================================== # PERTAINING TO SPECIFIC SETTINGS / FONT CHOICES #----------------------------------------------------------------------------------------------------------- S = use_disjunct_ranges: false write_pua_sample: true write_ranges_sample: true write_special_interest_sample: true # source_path: '../../../assets/write-font-configuration-for-kitty-terminal.sample-data.json' paths: # configured_cid_ranges: '../../../../ucdb/cfg/styles-codepoints-and-fontnicks.txt' configured_cid_ranges: '../../../assets/ucdb/styles-codepoints-and-fontnicks.short.txt' cid_ranges_by_rsgs: '../../../../ucdb/cfg/rsgs-and-blocks.txt' kitty_fonts_conf: '~/.config/kitty/kitty-fonts.conf' psname_by_fontnicks: babelstonehan: 'BabelStoneHan' cwtexqheibold: 'cwTeXQHei-Bold' dejavuserif: 'DejaVuSerif' hanaminaotf: 'HanaMinA' hanaminbotf: 'HanaMinB' hanamina: 'HanaMinA' hanaminb: 'HanaMinB' ipamp: 'IPAPMincho' jizurathreeb: 'jizura3b' nanummyeongjo: 'NanumMyeongjo' sunexta: 'Sun-ExtA' thtshynpone: 'TH-Tshyn-P1' thtshynptwo: 'TH-Tshyn-P2' thtshynpzero: 'TH-Tshyn-P0' umingttcone: 'UMingCN' takaopgothic: 'TakaoGothic' # @default # asanamath ebgaramondtwelveregular: 'Iosevka-Slab' # hanaminexatwootf: '' lmromantenregular: 'Iosevka-Slab' iosevkaslab: 'Iosevka-Slab' # sourcehanserifheavytaiwan: '' # unifonttwelve: '' lastresort: 'LastResort' illegal_codepoints: null # illegal_codepoints: [ # see https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Special_code_points # [ 0x0000, 0x0000, ] # zero # [ 0x0001, 0x001f, ] # lower controls # [ 0x007f, 0x009f, ] # higher controls # [ 0xd800, 0xdfff, ] # surrogates # [ 0xfdd0, 0xfdef, ] # [ 0xfffe, 0xffff, ] # [ 0x1fffe, 0x1ffff, ] # [ 0x2fffe, 0x2ffff, ] # [ 0x3fffe, 0x3ffff, ] # [ 0x4fffe, 0x4ffff, ] # [ 0x5fffe, 0x5ffff, ] # [ 0x6fffe, 0x6ffff, ] # [ 0x7fffe, 0x7ffff, ] # [ 0x8fffe, 0x8ffff, ] # [ 0x9fffe, 0x9ffff, ] # [ 0xafffe, 0xaffff, ] # [ 0xbfffe, 0xbffff, ] # [ 0xcfffe, 0xcffff, ] # [ 0xdfffe, 0xdffff, ] # [ 0xefffe, 0xeffff, ] # [ 0xffffe, 0xfffff, ] # [ 0x10fffe, 0x10ffff, ] ] illegal_codepoint_patterns: [ ///^\p{Cc}$///u # Control ///^\p{Cs}$///u # Surrogate # ///^\p{Cn}$///u # Unassigned ] #=========================================================================================================== # GENERIC STUFF #----------------------------------------------------------------------------------------------------------- cid_range_pattern = ///^ 0x (?<first_cid_txt> [0-9a-fA-F]+ ) \.\. 0x (?<last_cid_txt> [0-9a-fA-F]+ ) $ /// parse_cid_hex_range_txt = ( cid_range_txt ) -> unless ( match = cid_range_txt.match cid_range_pattern )? throw new Error "^33736^ unable to parse CID range #{rpr cid_range_txt}" { first_cid_txt last_cid_txt } = match.groups first_cid = parseInt first_cid_txt, 16 last_cid = parseInt last_cid_txt, 16 return [ first_cid, last_cid, ] #----------------------------------------------------------------------------------------------------------- segment_from_cid_hex_range_txt = ( cid_range_txt ) -> new LAP.Segment parse_cid_hex_range_txt cid_range_txt #----------------------------------------------------------------------------------------------------------- @_read_cid_ranges_by_rsgs = ( settings ) -> return R if ( R = settings.cid_ranges_by_rsgs )? R = settings.cid_ranges_by_rsgs = {} source_path = PATH.resolve PATH.join __dirname, settings.paths.cid_ranges_by_rsgs lines = ( FS.readFileSync source_path, { encoding: 'utf-8', } ).split '\n' for line, line_idx in lines line = line.replace /^\s+$/g, '' continue if ( line.length is 0 ) or ( /^\s*#/.test line ) [ icgroup, rsg, is_cjk_txt, cid_range_txt, range_name..., ] = line.split /\s+/ continue if rsg.startsWith 'u-x-' try R[ rsg ] = segment_from_cid_hex_range_txt cid_range_txt catch error throw new Error "^4445^ illegal line: #{error.message}, line_nr: #{line_idx + 1}, line: #{rpr line}" return R # #----------------------------------------------------------------------------------------------------------- # @_read_illegal_codepoints = ( settings ) -> # return R if isa.interlap ( R = settings.illegal_codepoints ) # R = settings.illegal_codepoints = new LAP.Interlap settings.illegal_codepoints # return R #----------------------------------------------------------------------------------------------------------- @_segment_from_cid_literal = ( settings, cid_literal ) -> cid_ranges_by_rsgs = @_read_cid_ranges_by_rsgs settings #....................................................................................................... if cid_literal is '*' return new LAP.Segment [ 0x000000, 0x10ffff, ] #....................................................................................................... else if ( cid_literal.startsWith "'" ) and ( cid_literal.endsWith "'" ) validate.chr chr = cid_literal[ 1 ... cid_literal.length - 1 ] first_cid = chr.codePointAt 0 last_cid = first_cid return new LAP.Segment [ first_cid, last_cid, ] #....................................................................................................... else if ( cid_literal.startsWith 'rsg:' ) rsg = cid_literal[ 4 .. ] validate.nonempty_text rsg unless ( segment = cid_ranges_by_rsgs[ rsg ] )? throw new Error "^4445^ illegal line: unknown rsg: #{rpr rsg}, line_nr: #{line_nr}, line: #{rpr line}" return segment #....................................................................................................... else try return segment_from_cid_hex_range_txt cid_literal catch error throw new Error "^4445^ illegal line: #{error.message}, line_nr: #{line_nr}, line: #{rpr line}" #....................................................................................................... throw new Error "^4445^ illegal line: unable to parse CID range; line_nr: #{line_nr}, line: #{rpr line}" return null #----------------------------------------------------------------------------------------------------------- @_read_configured_cid_ranges = ( settings ) -> R = settings.configured_cid_ranges = [] source_path = PATH.resolve PATH.join __dirname, settings.paths.configured_cid_ranges lines = ( FS.readFileSync source_path, { encoding: 'utf-8', } ).split '\n' unknown_fontnicks = new Set() for line, line_idx in lines line_nr = line_idx + 1 line = line.replace /^\s+$/g, '' continue if ( line.length is 0 ) or ( /^\s*#/.test line ) [ styletag, cid_literal, fontnick, glyphstyle..., ] = line.split /\s+/ glyphstyle = glyphstyle.join ' ' validate.nonempty_text styletag validate.nonempty_text cid_literal validate.nonempty_text fontnick validate.text glyphstyle # continue unless fontnick? # continue unless first_cid? # continue unless last_cid? #....................................................................................................... unless styletag is '+style:ming' whisper "^776^ skipping line_nr: #{line_nr} b/c of styletag: #{rpr styletag}" continue #....................................................................................................... if glyphstyle? and /\bglyph\b/.test glyphstyle whisper "^776^ skipping line_nr: #{line_nr} b/c of glyphstyle: #{rpr glyphstyle}" continue #....................................................................................................... unless ( psname = settings.psname_by_fontnicks[ fontnick ] )? unless unknown_fontnicks.has fontnick unknown_fontnicks.add fontnick warn "unknown fontnick #{rpr fontnick} on linenr: #{line_nr} (only noting first occurrence)" continue #....................................................................................................... if cid_literal is '*' debug '^778^', { styletag, cid_literal, fontnick, } settings.default_fontnick ?= fontnick settings.default_psname ?= psname continue #....................................................................................................... segment = @_segment_from_cid_literal settings, cid_literal #....................................................................................................... ### NOTE for this particular file format, we could use segments instead of laps since there can be only one segment per record; however, for consistency with those cases where several disjunct segments per record are allowed, we use laps. ### ### TAINT consider to use a non-committal name like `cids` instead of `lap`, which is bound to a particular data type; allow to use segments and laps for this and similar attributes. ### lap = new LAP.Interlap segment R.push { fontnick, psname, lap, } return R #----------------------------------------------------------------------------------------------------------- @_read_configured_cid_ranges_as_laps = ( settings ) -> R = [] for { fontnick, psname, lap, } in @_read_configured_cid_ranges settings for segment in lap R.push { fontnick, psname, segment, } return R #----------------------------------------------------------------------------------------------------------- @_read_disjunct_cid_ranges = ( settings ) -> overlaps = @_read_configured_cid_ranges settings R = settings.disjunct_cid_ranges = [] org_by_fontnicks = {} exclusion = @_read_illegal_codepoints settings for idx in [ overlaps.length - 1 .. 0 ] by -1 rule = overlaps[ idx ] { fontnick psname lap } = rule disjunct = LAP.difference lap, exclusion exclusion = LAP.union lap, exclusion R.unshift { fontnick, psname, lap: disjunct, } return R #----------------------------------------------------------------------------------------------------------- @_read_disjunct_cid_segments = ( settings ) -> R = [] for disjunct_range in @_read_disjunct_cid_ranges settings { fontnick psname lap } = disjunct_range for segment in lap continue if segment.size is 0 # should never happen R.push { fontnick, psname, segment, } R.sort ( a, b ) -> return -1 if a.segment.lo < b.segment.lo return +1 if a.segment.lo < b.segment.lo return 0 return R #----------------------------------------------------------------------------------------------------------- @_write_method_from_path = ( settings, path = null ) -> return echo unless path? validate.nonempty_text path path = PATH.join OS.homedir(), path.replace /^~/, '' try FS.statSync path catch error throw error unless error.code is 'ENOENT' warn "^729^target path #{rpr path} does not exist" throw error FS.writeFileSync path, '' return write = ( line ) -> validate.text line FS.appendFileSync path, line + '\n' #----------------------------------------------------------------------------------------------------------- @_write_ranges_sample = ( settings, write ) -> for disjunct_range in settings.fontnicks_and_segments { fontnick psname segment } = disjunct_range # help fontnick, LAP.as_unicode_range lap unicode_range_txt = ( LAP.as_unicode_range segment ).padEnd 30 sample = ( String.fromCodePoint c for c in [ segment.lo .. segment.hi ][ .. 30 ] ) sample_txt = sample.join '' sample_txt = sample_txt.replace /[\x00-\x20]+/g, '' sample_txt = sample_txt.replace /[\x80-\x9f]+/g, '' sample_txt = sample_txt.replace /[\u2000-\u200f]+/g, '' sample_txt = sample_txt.replace /\s+/g, '' psname_txt = psname.padEnd 30 write "# symbol_map #{unicode_range_txt} #{psname_txt} # #{sample_txt}" #----------------------------------------------------------------------------------------------------------- @_write_pua_sample = ( settings, write ) -> for row_cid in [ 0xe000 .. 0xe3a0 ] by 0x10 row = [] for col_cid in [ 0x00 .. 0x0f ] cid = row_cid + col_cid row.push String.fromCodePoint cid row_cid_txt = "U+#{( row_cid.toString 16 ).padStart 4, '0'}" write "# #{row_cid_txt} #{row.join ''}" #----------------------------------------------------------------------------------------------------------- @_write_special_interest_sample = ( settings, write ) -> write '# x𒇷x' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' write '# x﷽x' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' write '# x𒇷 x' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' write '# x﷽ x' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' write '# ' write '# ' write '#  (32 chrs)' write '# | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |' write '# 豈更車賈滑串句龜龜契金喇奈懶癩羅蘿螺裸邏樂洛烙珞落酪駱亂卵欄爛金 (32 chrs)' write '# ■□▢▣▤▥▦▧▨▩▪▫▬▭▮▯▰▱▲' write '# ԀԁԂԃԄԅԆԇԈԉԊԋԌԍԎԏԐԑԒԓԔԕԖԗԘԙԚԛԜԝԞ' write '# ⤀⤁⤂⤃⤄⤅⤆⤇⤈⤉⤊⤋⤌⤍⤎⤏⤐⤑⤒⤓⤔⤕⤖⤗⤘⤙⤚⤛⤜⤝⤞' write '# ℀℁ℂ℃℄℅℆ℇ℈℉ℊℋℌℍℎℏℐℑℒℓ℔ℕ№℗℘ℙℚℛℜℝ℞' write '# ℀℁ℂ℃ ℄℅℆ℇ℈℉ℊℋℌℍℎℏℐℑℒℓ℔ℕ№℗℘ℙℚℛℜℝ℞' write '# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^.^.^.^.^.^.^.^.^.^.^.' #----------------------------------------------------------------------------------------------------------- @write_font_configuration_for_kitty_terminal = ( settings ) -> write = @_write_method_from_path settings, settings.paths.kitty_fonts_conf #......................................................................................................... if settings.use_disjunct_ranges ? false settings.fontnicks_and_segments = @_read_disjunct_cid_segments settings else settings.fontnicks_and_segments = @_read_configured_cid_ranges_as_laps settings #......................................................................................................... @_write_special_interest_sample settings, write if settings.write_special_interest_sample ? false @_write_ranges_sample settings, write if settings.write_ranges_sample ? false @_write_pua_sample settings, write if settings.write_pua_sample ? false #......................................................................................................... unless settings.default_psname? warn "^334^ no default font configured" urge "^334^ add settings.default_fontnick" urge "^334^ or add CID range with asterisk in #{PATH.resolve settings.paths.configured_cid_ranges}" else write "font_family #{settings.default_psname}" write "bold_font auto" write "italic_font auto" write "bold_italic_font auto" #......................................................................................................... for disjunct_range in settings.fontnicks_and_segments { fontnick psname segment } = disjunct_range ### !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ### ### exclude default font: ### continue if psname is 'IPI:NAME:<NAME>END_PI' ### !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ### unicode_range_txt = ( LAP.as_unicode_range segment ).padEnd 30 write "symbol_map #{unicode_range_txt} #{psname}" #......................................................................................................... return null #----------------------------------------------------------------------------------------------------------- @write_whisk_character_tunnel = ( settings ) -> # https://www.aivosto.com/articles/control-characters.html#APC chr_ranges = "[\\ue000-\\uefff]" source = """#!/usr/bin/env node const pattern = /(#{chr_ranges})/g; const rl = require( 'readline' ).createInterface({ input: process.stdin, output: process.stdout, terminal: false }) rl.on( 'line', ( line ) => { return process.stdout.write( line.replace( pattern, '$1 ' ) + '\\n' ); } ); """ # #!/usr/bin/env node # const pattern_2 = /([\ue000-\uefff])/ug; # const pattern_3 = /([\ufb50-\ufdff])/ug; # const pattern_7 = /([\u{12000}-\u{123ff}])/ug; # const rl = require( 'readline' ).createInterface({ # input: process.stdin, # output: process.stdout, # terminal: false }) # rl.on( 'line', ( line ) => { # return process.stdout.write( # line # .replace( pattern_2, '$1 ' ) # .replace( pattern_3, '$1 ' ) # .replace( pattern_7, '$1 ' ) # + '\n' ); } ); echo() echo source echo() # path = ??? # FS.writeFileSync path, source return null #=========================================================================================================== # DATA STRUCTURE DEMOS #----------------------------------------------------------------------------------------------------------- @demo_cid_ranges_by_rsgs = -> echo CND.steel CND.reverse "CID Ranges by RSGs".padEnd 108 for rsg, segment of @_read_cid_ranges_by_rsgs S continue unless /kana|kata|hira/.test rsg rsg_txt = ( rsg.padEnd 25 ) range_txt = LAP.as_unicode_range segment echo ( CND.grey "rsg and CID range" ), ( CND.blue rsg_txt ), ( CND.lime range_txt ) return null #----------------------------------------------------------------------------------------------------------- @demo_configured_ranges = -> echo CND.steel CND.reverse "Configured CID Ranges".padEnd 108 for configured_range in @_read_configured_cid_ranges S { fontnick psname lap } = configured_range font_txt = ( psname.padEnd 25 ) range_txt = LAP.as_unicode_range lap # echo ( CND.grey "configured range" ), ( CND.yellow configured_range ) echo ( CND.grey "configured range" ), ( CND.yellow font_txt ), ( CND.lime range_txt ) return null #----------------------------------------------------------------------------------------------------------- @demo_disjunct_ranges = -> echo CND.steel CND.reverse "Disjunct CID Ranges".padEnd 108 for disjunct_range in @_read_disjunct_cid_ranges S { fontnick psname lap } = disjunct_range font_txt = ( psname.padEnd 25 ) if lap.size is 0 echo ( CND.grey "disjunct range" ), ( CND.grey font_txt ), ( CND.grey "no codepoints" ) else for segment in lap range_txt = LAP.as_unicode_range segment echo ( CND.grey "disjunct range" ), ( CND.yellow font_txt ), ( CND.lime range_txt ) return null #----------------------------------------------------------------------------------------------------------- @demo_kitty_font_config = -> echo CND.steel CND.reverse "Kitty Font Config".padEnd 108 @write_font_configuration_for_kitty_terminal S #----------------------------------------------------------------------------------------------------------- @_read_illegal_codepoints = ( settings ) -> return R if ( R = settings.illegal_codepoints )? segments = [] ranges = [ { lo: 0x0000, hi: 0xe000, } { lo: 0xf900, hi: 0xffff, } # { lo: 0x10000, hi: 0x1ffff, } # { lo: 0x20000, hi: 0x2ffff, } # { lo: 0x30000, hi: 0x3ffff, } # { lo: 0x0000, hi: 0x10ffff, } ] for range in ranges prv_cid = null for cid in [ range.lo .. range.hi ] if settings.illegal_codepoint_patterns.some ( re ) -> re.test String.fromCodePoint cid segments.push [ cid, cid, ] R = settings.illegal_codepoints = new LAP.Interlap segments help "excluding #{R.size} codepoints" return R #----------------------------------------------------------------------------------------------------------- @demo_illegal_codepoints = -> lap = @_read_illegal_codepoints S for segment in lap urge LAP.as_unicode_range segment return null ############################################################################################################ if module is require.main then do => # @demo_illegal_codepoints() # @demo_cid_ranges_by_rsgs() # @demo_configured_ranges() # @demo_disjunct_ranges() # @demo_kitty_font_config() #......................................................................................................... @write_font_configuration_for_kitty_terminal S # @write_whisk_character_tunnel S ############################################################################################################ ### NOTE original version has problems with these entries: # 3002 # symbol_map U+3000-U+303f HanaMinA # 2e81 # symbol_map U+2e80-U+2eff Sun-ExtA # 31c2 # symbol_map U+31c0-U+31ef Sun-ExtA # 3404 # symbol_map U+3400-U+4dbf Sun-ExtA ############################################################################################################
[ { "context": "###\n * cena_auth\n * https://github.com/1egoman/cena_app\n *\n * Copyright (c) 2015 Ryan Gaus\n * Li", "end": 46, "score": 0.9955927729606628, "start": 39, "tag": "USERNAME", "value": "1egoman" }, { "context": "thub.com/1egoman/cena_app\n *\n * Copyright (c) 2015 Ryan Gaus\n * Licensed under the MIT license.\n###\n'use stric", "end": 90, "score": 0.9998767971992493, "start": 81, "tag": "NAME", "value": "Ryan Gaus" } ]
src/frontend/controllers/nav.coffee
1egoman/cena_app
0
### * cena_auth * https://github.com/1egoman/cena_app * * Copyright (c) 2015 Ryan Gaus * Licensed under the MIT license. ### 'use strict'; # nav controller @app.controller 'NavController', ($scope) -> # get the user whose lists we are viewing currently $scope.owner = _.last(location.pathname.split('/')).replace '/', ''
86908
### * cena_auth * https://github.com/1egoman/cena_app * * Copyright (c) 2015 <NAME> * Licensed under the MIT license. ### 'use strict'; # nav controller @app.controller 'NavController', ($scope) -> # get the user whose lists we are viewing currently $scope.owner = _.last(location.pathname.split('/')).replace '/', ''
true
### * cena_auth * https://github.com/1egoman/cena_app * * Copyright (c) 2015 PI:NAME:<NAME>END_PI * Licensed under the MIT license. ### 'use strict'; # nav controller @app.controller 'NavController', ($scope) -> # get the user whose lists we are viewing currently $scope.owner = _.last(location.pathname.split('/')).replace '/', ''
[ { "context": "ibute.do?style=2&id=2318991&type=2&source=2&token=3a3322513c2750ad80c5149adb3795d6')\n#music.doTask()\n#console.log argv\nurl = argv._[", "end": 4878, "score": 0.7915747165679932, "start": 4846, "tag": "PASSWORD", "value": "3a3322513c2750ad80c5149adb3795d6" } ]
app.coffee
youqingkui/down-meizu-music
1
request = require("request") async = require("async") cheerio = require("cheerio") fs = require("fs") argv = require('optimist').argv class Music constructor: (@url) -> @songs = [] @album = 'youqing' @albumImgUrl = '' @artist = 'youqing' @headers = { 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.3' } getUrlInfo:(cb) -> self = @ async.waterfall [ getJSON = (callback) -> op = { url:self.url headers:self.headers } request.get op, (err, res, body) -> return console.log err if err $ = cheerio.load(body) imgUrl = $(".special img") album = $("h4.name") describe = $(".describe").first() if imgUrl.length self.albumImgUrl = imgUrl.attr('src') if album.length self.album = self.changeSymbol(album.text()) if describe.length self.artist = self.changeSymbol($(describe).text()) else songs_text = $('script:contains("url")').text() return console.log "没有发现分享里面的东西1" unless songs_text self.album = self.changeSymbol($(".singer").text()) url = self.getSingSongUrl(songs_text) arr = [] tmp = {} tmp.title = $("h4.name").text() tmp.url = url arr.push(tmp) return callback(null, arr) songs_text = $('script:contains("songs")').text() return console.log "没有发现专辑分享里面的东西2" unless songs_text # todo oh, 这里可能存在安全隐患,暂时没有找到替代 jsonSongs = eval(songs_text) callback(null, jsonSongs) getSongsInfo = (songs, callback) -> songs.forEach (item) -> tmp = {} tmp.title = self.changeSymbol(item.title) tmp.url = item.url self.songs.push tmp cb() ] getSingSongUrl:(text) -> arr1 = text.split('"') url = arr1[7] return url changeSymbol:(text) -> text = text.replace(/\//g, '-') text = text.replace(/\s+/g,'-') console.log text return text getSongUrl:(cb) -> self = @ bashUrl = 'http://music.meizu.com' async.eachSeries self.songs, (item, callback) -> url = bashUrl + item.url request.get url, (err, res, body) -> return console.log err if err data = JSON.parse(body) if data.code != 200 return console.log "获取下载错误200", data item.downUrl = data.value.url item.ext = data.value.format callback() ,() -> cb() downSongs:(cb) -> self = @ async.eachSeries self.songs, (item, callback) -> self.downSong(item, callback) ,() -> console.log "all down" downSong:(info, cb) -> self = @ writeSong = fs.createWriteStream(self.album + '/' + info.title + '.' + info.ext) request.get info.downUrl .on 'response', (res) -> # console.log "................................." # console.log "#{self.album} #{info.downUrl}" console.log(res.statusCode) if res.statusCode is 200 console.log "连接下载歌曲#{info.title}成功" .on "error", (err) -> console.log "#{self.album} #{info.title} #{info.downUrl} down error: #{err}" return console.log "下载歌曲失败" .on 'end', () -> console.log "#{self.album} #{info.title} 歌曲下载成功" console.log ".................................\n" cb() .pipe(writeSong) createAlbumFolder:(cb) -> self = @ unless fs.existsSync(self.album) fs.mkdirSync(self.album) cb() downAlbumImg:(cb) -> self = @ extArr = self.albumImgUrl.split('.') ext = extArr[extArr.length - 1] writeImg = fs.createWriteStream(self.album + '/' + self.album + '.' + ext) request.get self.albumImgUrl .on 'response', (res) -> # console.log "................................." # console.log "#{self.album} #{self.albumImgUrl}" console.log(res.statusCode) if res.statusCode is 200 console.log '连接下载歌曲专辑图片成功', self.albumImgUrl .on "error", (err) -> console.log "#{self.album} #{self.albumImgUrl} down error: #{err}" return console.log "下载歌曲专辑图片失败失败" .on 'end', () -> console.log "#{self.album} #{self.albumImgUrl} 【专辑图片】下载成功" console.log ".................................\n" cb() .pipe(writeImg) doTask:() -> self = @ async.series [ (cb) -> self.getUrlInfo cb (cb) -> self.createAlbumFolder cb (cb) -> self.downAlbumImg cb (cb) -> self.getSongUrl cb (cb) -> self.downSongs cb ] #music = new Music('http://music.meizu.com/share/distribute.do?style=2&id=2318991&type=2&source=2&token=3a3322513c2750ad80c5149adb3795d6') #music.doTask() #console.log argv url = argv._[0] if not url console.log "需要输入从魅族音乐分享出来的专辑或单曲URL" else music = new Music(url) music.doTask()
128515
request = require("request") async = require("async") cheerio = require("cheerio") fs = require("fs") argv = require('optimist').argv class Music constructor: (@url) -> @songs = [] @album = 'youqing' @albumImgUrl = '' @artist = 'youqing' @headers = { 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.3' } getUrlInfo:(cb) -> self = @ async.waterfall [ getJSON = (callback) -> op = { url:self.url headers:self.headers } request.get op, (err, res, body) -> return console.log err if err $ = cheerio.load(body) imgUrl = $(".special img") album = $("h4.name") describe = $(".describe").first() if imgUrl.length self.albumImgUrl = imgUrl.attr('src') if album.length self.album = self.changeSymbol(album.text()) if describe.length self.artist = self.changeSymbol($(describe).text()) else songs_text = $('script:contains("url")').text() return console.log "没有发现分享里面的东西1" unless songs_text self.album = self.changeSymbol($(".singer").text()) url = self.getSingSongUrl(songs_text) arr = [] tmp = {} tmp.title = $("h4.name").text() tmp.url = url arr.push(tmp) return callback(null, arr) songs_text = $('script:contains("songs")').text() return console.log "没有发现专辑分享里面的东西2" unless songs_text # todo oh, 这里可能存在安全隐患,暂时没有找到替代 jsonSongs = eval(songs_text) callback(null, jsonSongs) getSongsInfo = (songs, callback) -> songs.forEach (item) -> tmp = {} tmp.title = self.changeSymbol(item.title) tmp.url = item.url self.songs.push tmp cb() ] getSingSongUrl:(text) -> arr1 = text.split('"') url = arr1[7] return url changeSymbol:(text) -> text = text.replace(/\//g, '-') text = text.replace(/\s+/g,'-') console.log text return text getSongUrl:(cb) -> self = @ bashUrl = 'http://music.meizu.com' async.eachSeries self.songs, (item, callback) -> url = bashUrl + item.url request.get url, (err, res, body) -> return console.log err if err data = JSON.parse(body) if data.code != 200 return console.log "获取下载错误200", data item.downUrl = data.value.url item.ext = data.value.format callback() ,() -> cb() downSongs:(cb) -> self = @ async.eachSeries self.songs, (item, callback) -> self.downSong(item, callback) ,() -> console.log "all down" downSong:(info, cb) -> self = @ writeSong = fs.createWriteStream(self.album + '/' + info.title + '.' + info.ext) request.get info.downUrl .on 'response', (res) -> # console.log "................................." # console.log "#{self.album} #{info.downUrl}" console.log(res.statusCode) if res.statusCode is 200 console.log "连接下载歌曲#{info.title}成功" .on "error", (err) -> console.log "#{self.album} #{info.title} #{info.downUrl} down error: #{err}" return console.log "下载歌曲失败" .on 'end', () -> console.log "#{self.album} #{info.title} 歌曲下载成功" console.log ".................................\n" cb() .pipe(writeSong) createAlbumFolder:(cb) -> self = @ unless fs.existsSync(self.album) fs.mkdirSync(self.album) cb() downAlbumImg:(cb) -> self = @ extArr = self.albumImgUrl.split('.') ext = extArr[extArr.length - 1] writeImg = fs.createWriteStream(self.album + '/' + self.album + '.' + ext) request.get self.albumImgUrl .on 'response', (res) -> # console.log "................................." # console.log "#{self.album} #{self.albumImgUrl}" console.log(res.statusCode) if res.statusCode is 200 console.log '连接下载歌曲专辑图片成功', self.albumImgUrl .on "error", (err) -> console.log "#{self.album} #{self.albumImgUrl} down error: #{err}" return console.log "下载歌曲专辑图片失败失败" .on 'end', () -> console.log "#{self.album} #{self.albumImgUrl} 【专辑图片】下载成功" console.log ".................................\n" cb() .pipe(writeImg) doTask:() -> self = @ async.series [ (cb) -> self.getUrlInfo cb (cb) -> self.createAlbumFolder cb (cb) -> self.downAlbumImg cb (cb) -> self.getSongUrl cb (cb) -> self.downSongs cb ] #music = new Music('http://music.meizu.com/share/distribute.do?style=2&id=2318991&type=2&source=2&token=<PASSWORD>') #music.doTask() #console.log argv url = argv._[0] if not url console.log "需要输入从魅族音乐分享出来的专辑或单曲URL" else music = new Music(url) music.doTask()
true
request = require("request") async = require("async") cheerio = require("cheerio") fs = require("fs") argv = require('optimist').argv class Music constructor: (@url) -> @songs = [] @album = 'youqing' @albumImgUrl = '' @artist = 'youqing' @headers = { 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.3' } getUrlInfo:(cb) -> self = @ async.waterfall [ getJSON = (callback) -> op = { url:self.url headers:self.headers } request.get op, (err, res, body) -> return console.log err if err $ = cheerio.load(body) imgUrl = $(".special img") album = $("h4.name") describe = $(".describe").first() if imgUrl.length self.albumImgUrl = imgUrl.attr('src') if album.length self.album = self.changeSymbol(album.text()) if describe.length self.artist = self.changeSymbol($(describe).text()) else songs_text = $('script:contains("url")').text() return console.log "没有发现分享里面的东西1" unless songs_text self.album = self.changeSymbol($(".singer").text()) url = self.getSingSongUrl(songs_text) arr = [] tmp = {} tmp.title = $("h4.name").text() tmp.url = url arr.push(tmp) return callback(null, arr) songs_text = $('script:contains("songs")').text() return console.log "没有发现专辑分享里面的东西2" unless songs_text # todo oh, 这里可能存在安全隐患,暂时没有找到替代 jsonSongs = eval(songs_text) callback(null, jsonSongs) getSongsInfo = (songs, callback) -> songs.forEach (item) -> tmp = {} tmp.title = self.changeSymbol(item.title) tmp.url = item.url self.songs.push tmp cb() ] getSingSongUrl:(text) -> arr1 = text.split('"') url = arr1[7] return url changeSymbol:(text) -> text = text.replace(/\//g, '-') text = text.replace(/\s+/g,'-') console.log text return text getSongUrl:(cb) -> self = @ bashUrl = 'http://music.meizu.com' async.eachSeries self.songs, (item, callback) -> url = bashUrl + item.url request.get url, (err, res, body) -> return console.log err if err data = JSON.parse(body) if data.code != 200 return console.log "获取下载错误200", data item.downUrl = data.value.url item.ext = data.value.format callback() ,() -> cb() downSongs:(cb) -> self = @ async.eachSeries self.songs, (item, callback) -> self.downSong(item, callback) ,() -> console.log "all down" downSong:(info, cb) -> self = @ writeSong = fs.createWriteStream(self.album + '/' + info.title + '.' + info.ext) request.get info.downUrl .on 'response', (res) -> # console.log "................................." # console.log "#{self.album} #{info.downUrl}" console.log(res.statusCode) if res.statusCode is 200 console.log "连接下载歌曲#{info.title}成功" .on "error", (err) -> console.log "#{self.album} #{info.title} #{info.downUrl} down error: #{err}" return console.log "下载歌曲失败" .on 'end', () -> console.log "#{self.album} #{info.title} 歌曲下载成功" console.log ".................................\n" cb() .pipe(writeSong) createAlbumFolder:(cb) -> self = @ unless fs.existsSync(self.album) fs.mkdirSync(self.album) cb() downAlbumImg:(cb) -> self = @ extArr = self.albumImgUrl.split('.') ext = extArr[extArr.length - 1] writeImg = fs.createWriteStream(self.album + '/' + self.album + '.' + ext) request.get self.albumImgUrl .on 'response', (res) -> # console.log "................................." # console.log "#{self.album} #{self.albumImgUrl}" console.log(res.statusCode) if res.statusCode is 200 console.log '连接下载歌曲专辑图片成功', self.albumImgUrl .on "error", (err) -> console.log "#{self.album} #{self.albumImgUrl} down error: #{err}" return console.log "下载歌曲专辑图片失败失败" .on 'end', () -> console.log "#{self.album} #{self.albumImgUrl} 【专辑图片】下载成功" console.log ".................................\n" cb() .pipe(writeImg) doTask:() -> self = @ async.series [ (cb) -> self.getUrlInfo cb (cb) -> self.createAlbumFolder cb (cb) -> self.downAlbumImg cb (cb) -> self.getSongUrl cb (cb) -> self.downSongs cb ] #music = new Music('http://music.meizu.com/share/distribute.do?style=2&id=2318991&type=2&source=2&token=PI:PASSWORD:<PASSWORD>END_PI') #music.doTask() #console.log argv url = argv._[0] if not url console.log "需要输入从魅族音乐分享出来的专辑或单曲URL" else music = new Music(url) music.doTask()
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9993306994438171, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "#url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n authInHost = (if result.host and re", "end": 20250, "score": 0.5577641129493713, "start": 20249, "tag": "EMAIL", "value": "2" }, { "context": "olveObject('mailto:local1@domain1', 'local2@domain2')\n authInHost = (if result.host and result.hos", "end": 20258, "score": 0.5937062501907349, "start": 20257, "tag": "EMAIL", "value": "2" } ]
lib/url.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. Url = -> @protocol = null @slashes = null @auth = null @host = null @port = null @hostname = null @hash = null @search = null @query = null @pathname = null @path = null @href = null return # Reference: RFC 3986, RFC 1808, RFC 2396 # define these here so at least they only have to be # compiled once on the first module load. # Special case for a simple path URL # RFC 2396: characters reserved for delimiting URLs. # We actually just auto-escape these. # RFC 2396: characters not allowed for various reasons. # Allowed by RFCs, but cause of XSS attacks. Always escape these. # Characters that are never ever allowed in a hostname. # Note that any invalid chars are also handled, but these # are the ones that are *expected* to be seen, so we fast-path # them. # protocols that can allow "unsafe" and "unwise" chars. # protocols that never have a hostname. # protocols that always contain a // bit. urlParse = (url, parseQueryString, slashesDenoteHost) -> return url if url and util.isObject(url) and url instanceof Url u = new Url u.parse url, parseQueryString, slashesDenoteHost u # Copy chrome, IE, opera backslash-handling behavior. # Back slashes before the query string get converted to forward slashes # See: https://code.google.com/p/chromium/issues/detail?id=25916 # trim before proceeding. # This is to support parse stuff like " http://foo.com \n" # Try fast path regexp # figure out if it's got a host # user@server is *always* interpreted as a hostname, and url # resolution will treat //foo/bar as host=foo,path=bar because that's # how the browser resolves relative URLs. # there's a hostname. # the first instance of /, ?, ;, or # ends the host. # # If there is an @ in the hostname, then non-host chars *are* allowed # to the left of the last @ sign, unless some host-ending character # comes *before* the @-sign. # URLs are obnoxious. # # ex: # http://a@b@c/ => user:a@b host:c # http://a@b?@c => user:a host:c path:/?@c # v0.12 TODO(isaacs): This is not quite how Chrome does things. # Review our test case against browsers more comprehensively. # find the first instance of any hostEndingChars # at this point, either we have an explicit point where the # auth portion cannot go past, or the last @ char is the decider. # atSign can be anywhere. # atSign must be in auth portion. # http://a@b/c@d => host:b auth:a path:/c@d # Now we have a portion which is definitely the auth. # Pull that off. # the host is the remaining to the left of the first non-host char # if we still have not hit it, then the entire thing is a host. # pull out port. # we've indicated that there is a hostname, # so even if it's empty, it has to be present. # if hostname begins with [ and ends with ] # assume that it's an IPv6 address. # validate a little. # we replace non-ASCII char with a temporary placeholder # we need this to make sure size of hostname is not # broken by replacing non-ASCII by nothing # we test again with ASCII char only # hostnames are always lower case. # IDNA Support: Returns a punycoded representation of "domain". # It only converts parts of the domain name that # have non-ASCII characters, i.e. it doesn't matter if # you call it with a domain that already is ASCII-only. # strip [ and ] from the hostname # the host field still retains them, though # now rest is set to the post-host stuff. # chop off any delim chars. # First, make 100% sure that any "autoEscape" chars get # escaped, even if encodeURIComponent doesn't think they # need to be. # chop off from the tail first. # got a fragment string. # no query string, but parseQueryString still requested #to support http.request # finally, reconstruct the href based on what has been validated. # format a parsed object into a url string urlFormat = (obj) -> # ensure it's an object, and not a string url. # If it's an obj, this is a no-op. # this way, you can call url_format() on strings # to clean up potentially wonky urls. obj = urlParse(obj) if util.isString(obj) return Url::format.call(obj) unless obj instanceof Url obj.format() # only the slashedProtocols get the //. Not mailto:, xmpp:, etc. # unless they had them to begin with. urlResolve = (source, relative) -> urlParse(source, false, true).resolve relative urlResolveObject = (source, relative) -> return relative unless source urlParse(source, false, true).resolveObject relative "use strict" punycode = require("punycode") util = require("util") exports.parse = urlParse exports.resolve = urlResolve exports.resolveObject = urlResolveObject exports.format = urlFormat exports.Url = Url protocolPattern = /^([a-z0-9.+-]+:)/i portPattern = /:[0-9]*$/ simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/ delims = [ "<" ">" "\"" "`" " " "\r" "\n" "\t" ] unwise = [ "{" "}" "|" "\\" "^" "`" ].concat(delims) autoEscape = ["'"].concat(unwise) nonHostChars = [ "%" "/" "?" ";" "#" ].concat(autoEscape) hostEndingChars = [ "/" "?" "#" ] hostnameMaxLen = 255 hostnamePatternString = "[^" + nonHostChars.join("") + "]{0,63}" hostnamePartPattern = new RegExp("^" + hostnamePatternString + "$") hostnamePartStart = new RegExp("^(" + hostnamePatternString + ")(.*)$") unsafeProtocol = javascript: true "javascript:": true hostlessProtocol = javascript: true "javascript:": true slashedProtocol = http: true https: true ftp: true gopher: true file: true "http:": true "https:": true "ftp:": true "gopher:": true "file:": true querystring = require("querystring") Url::parse = (url, parseQueryString, slashesDenoteHost) -> throw new TypeError("Parameter 'url' must be a string, not " + typeof url) unless util.isString(url) queryIndex = url.indexOf("?") splitter = (if (queryIndex isnt -1 and queryIndex < url.indexOf("#")) then "?" else "#") uSplit = url.split(splitter) slashRegex = /\\/g uSplit[0] = uSplit[0].replace(slashRegex, "/") url = uSplit.join(splitter) rest = url rest = rest.trim() if not slashesDenoteHost and url.split("#").length is 1 simplePath = simplePathPattern.exec(rest) if simplePath @path = rest @href = rest @pathname = simplePath[1] if simplePath[2] @search = simplePath[2] if parseQueryString @query = querystring.parse(@search.substr(1)) else @query = @search.substr(1) else if parseQueryString @search = "" @query = {} return this proto = protocolPattern.exec(rest) if proto proto = proto[0] lowerProto = proto.toLowerCase() @protocol = lowerProto rest = rest.substr(proto.length) if slashesDenoteHost or proto or rest.match(/^\/\/[^@\/]+@[^@\/]+/) slashes = rest.substr(0, 2) is "//" if slashes and not (proto and hostlessProtocol[proto]) rest = rest.substr(2) @slashes = true if not hostlessProtocol[proto] and (slashes or (proto and not slashedProtocol[proto])) hostEnd = -1 i = 0 while i < hostEndingChars.length hec = rest.indexOf(hostEndingChars[i]) hostEnd = hec if hec isnt -1 and (hostEnd is -1 or hec < hostEnd) i++ auth = undefined atSign = undefined if hostEnd is -1 atSign = rest.lastIndexOf("@") else atSign = rest.lastIndexOf("@", hostEnd) if atSign isnt -1 auth = rest.slice(0, atSign) rest = rest.slice(atSign + 1) @auth = decodeURIComponent(auth) hostEnd = -1 i = 0 while i < nonHostChars.length hec = rest.indexOf(nonHostChars[i]) hostEnd = hec if hec isnt -1 and (hostEnd is -1 or hec < hostEnd) i++ hostEnd = rest.length if hostEnd is -1 @host = rest.slice(0, hostEnd) rest = rest.slice(hostEnd) @parseHost() @hostname = @hostname or "" ipv6Hostname = @hostname[0] is "[" and @hostname[@hostname.length - 1] is "]" unless ipv6Hostname hostparts = @hostname.split(/\./) i = 0 l = hostparts.length while i < l part = hostparts[i] continue unless part unless part.match(hostnamePartPattern) newpart = "" j = 0 k = part.length while j < k if part.charCodeAt(j) > 127 newpart += "x" else newpart += part[j] j++ unless newpart.match(hostnamePartPattern) validParts = hostparts.slice(0, i) notHost = hostparts.slice(i + 1) bit = part.match(hostnamePartStart) if bit validParts.push bit[1] notHost.unshift bit[2] rest = "/" + notHost.join(".") + rest if notHost.length @hostname = validParts.join(".") break i++ if @hostname.length > hostnameMaxLen @hostname = "" else @hostname = @hostname.toLowerCase() @hostname = punycode.toASCII(@hostname) unless ipv6Hostname p = (if @port then ":" + @port else "") h = @hostname or "" @host = h + p @href += @host if ipv6Hostname @hostname = @hostname.substr(1, @hostname.length - 2) rest = "/" + rest if rest[0] isnt "/" unless unsafeProtocol[lowerProto] i = 0 l = autoEscape.length while i < l ae = autoEscape[i] esc = encodeURIComponent(ae) esc = escape(ae) if esc is ae rest = rest.split(ae).join(esc) i++ hash = rest.indexOf("#") if hash isnt -1 @hash = rest.substr(hash) rest = rest.slice(0, hash) qm = rest.indexOf("?") if qm isnt -1 @search = rest.substr(qm) @query = rest.substr(qm + 1) @query = querystring.parse(@query) if parseQueryString rest = rest.slice(0, qm) else if parseQueryString @search = "" @query = {} @pathname = rest if rest @pathname = "/" if slashedProtocol[lowerProto] and @hostname and not @pathname if @pathname or @search p = @pathname or "" s = @search or "" @path = p + s @href = @format(parseQueryString) this Url::format = (parseQueryString) -> auth = @auth or "" if auth auth = encodeURIComponent(auth) auth = auth.replace(/%3A/i, ":") auth += "@" protocol = @protocol or "" pathname = @pathname or "" hash = @hash or "" host = false query = "" search = "" if @path qm = @path.indexOf("?") if qm isnt -1 query = @path.slice(qm + 1) search = "?" + query pathname = @path.slice(0, qm) else if parseQueryString @query = {} @search = "" else @query = null @search = null pathname = @path if @host host = auth + @host else if @hostname host = auth + ((if @hostname.indexOf(":") is -1 then @hostname else "[" + @hostname + "]")) host += ":" + @port if @port query = querystring.stringify(@query) if not query and @query and util.isObject(@query) and Object.keys(@query).length search = @search or (query and ("?" + query)) or "" unless search protocol += ":" if protocol and protocol.substr(-1) isnt ":" if @slashes or (not protocol or slashedProtocol[protocol]) and host isnt false host = "//" + (host or "") pathname = "/" + pathname if pathname and pathname.charAt(0) isnt "/" else host = "" unless host hash = "#" + hash if hash and hash.charAt(0) isnt "#" search = "?" + search if search and search.charAt(0) isnt "?" pathname = pathname.replace(/[?#]/g, (match) -> encodeURIComponent match ) search = search.replace("#", "%23") protocol + host + pathname + search + hash Url::resolve = (relative) -> @resolveObject(urlParse(relative, false, true)).format() Url::resolveObject = (relative) -> if util.isString(relative) rel = new Url() rel.parse relative, false, true relative = rel result = new Url() tkeys = Object.keys(this) tk = 0 while tk < tkeys.length tkey = tkeys[tk] result[tkey] = this[tkey] tk++ # hash is always overridden, no matter what. # even href="" will remove it. result.hash = relative.hash # if the relative url is empty, then there's nothing left to do here. if relative.href is "" result.href = result.format() return result # hrefs like //foo/bar always cut to the protocol. if relative.slashes and not relative.protocol # take everything except the protocol from relative rkeys = Object.keys(relative) rk = 0 while rk < rkeys.length rkey = rkeys[rk] result[rkey] = relative[rkey] if rkey isnt "protocol" rk++ #urlParse appends trailing / to urls like http://www.example.com result.path = result.pathname = "/" if slashedProtocol[result.protocol] and result.hostname and not result.pathname result.href = result.format() return result if relative.protocol and relative.protocol isnt result.protocol # if it's a known url protocol, then changing # the protocol does weird things # first, if it's not file:, then we MUST have a host, # and if there was a path # to begin with, then we MUST have a path. # if it is file:, then the host is dropped, # because that's known to be hostless. # anything else is assumed to be absolute. unless slashedProtocol[relative.protocol] keys = Object.keys(relative) v = 0 while v < keys.length k = keys[v] result[k] = relative[k] v++ result.href = result.format() return result result.protocol = relative.protocol if not relative.host and not hostlessProtocol[relative.protocol] relPath = (relative.pathname or "").split("/") while relPath.length and not (relative.host = relPath.shift()) relative.host = "" unless relative.host relative.hostname = "" unless relative.hostname relPath.unshift "" if relPath[0] isnt "" relPath.unshift "" if relPath.length < 2 result.pathname = relPath.join("/") else result.pathname = relative.pathname result.search = relative.search result.query = relative.query result.host = relative.host or "" result.auth = relative.auth result.hostname = relative.hostname or relative.host result.port = relative.port # to support http.request if result.pathname or result.search p = result.pathname or "" s = result.search or "" result.path = p + s result.slashes = result.slashes or relative.slashes result.href = result.format() return result isSourceAbs = (result.pathname and result.pathname.charAt(0) is "/") isRelAbs = (relative.host or relative.pathname and relative.pathname.charAt(0) is "/") mustEndAbs = (isRelAbs or isSourceAbs or (result.host and relative.pathname)) removeAllDots = mustEndAbs srcPath = result.pathname and result.pathname.split("/") or [] relPath = relative.pathname and relative.pathname.split("/") or [] psychotic = result.protocol and not slashedProtocol[result.protocol] # if the url is a non-slashed url, then relative # links like ../.. should be able # to crawl up to the hostname, as well. This is strange. # result.protocol has already been set by now. # Later on, put the first path part into the host field. if psychotic result.hostname = "" result.port = null if result.host if srcPath[0] is "" srcPath[0] = result.host else srcPath.unshift result.host result.host = "" if relative.protocol relative.hostname = null relative.port = null if relative.host if relPath[0] is "" relPath[0] = relative.host else relPath.unshift relative.host relative.host = null mustEndAbs = mustEndAbs and (relPath[0] is "" or srcPath[0] is "") if isRelAbs # it's absolute. result.host = (if (relative.host or relative.host is "") then relative.host else result.host) result.hostname = (if (relative.hostname or relative.hostname is "") then relative.hostname else result.hostname) result.search = relative.search result.query = relative.query srcPath = relPath # fall through to the dot-handling below. else if relPath.length # it's relative # throw away the existing file, and take the new path instead. srcPath = [] unless srcPath srcPath.pop() srcPath = srcPath.concat(relPath) result.search = relative.search result.query = relative.query else unless util.isNullOrUndefined(relative.search) # just pull out the search. # like href='?foo'. # Put this after the other two cases because it simplifies the booleans if psychotic result.hostname = result.host = srcPath.shift() #occationaly the auth can get stuck only in host #this especialy happens in cases like #url.resolveObject('mailto:local1@domain1', 'local2@domain2') authInHost = (if result.host and result.host.indexOf("@") > 0 then result.host.split("@") else false) if authInHost result.auth = authInHost.shift() result.host = result.hostname = authInHost.shift() result.search = relative.search result.query = relative.query #to support http.request result.path = ((if result.pathname then result.pathname else "")) + ((if result.search then result.search else "")) if not util.isNull(result.pathname) or not util.isNull(result.search) result.href = result.format() return result unless srcPath.length # no path at all. easy. # we've already handled the other stuff above. result.pathname = null #to support http.request if result.search result.path = "/" + result.search else result.path = null result.href = result.format() return result # if a url ENDs in . or .., then it must get a trailing slash. # however, if it ends in anything else non-slashy, # then it must NOT get a trailing slash. last = srcPath.slice(-1)[0] hasTrailingSlash = ((result.host or relative.host) and (last is "." or last is "..") or last is "") # strip single dots, resolve double dots to parent dir # if the path tries to go above the root, `up` ends up > 0 up = 0 i = srcPath.length while i >= 0 last = srcPath[i] if last is "." srcPath.splice i, 1 else if last is ".." srcPath.splice i, 1 up++ else if up srcPath.splice i, 1 up-- i-- # if the path is allowed to go above the root, restore leading ..s if not mustEndAbs and not removeAllDots while up-- srcPath.unshift ".." up srcPath.unshift "" if mustEndAbs and srcPath[0] isnt "" and (not srcPath[0] or srcPath[0].charAt(0) isnt "/") srcPath.push "" if hasTrailingSlash and (srcPath.join("/").substr(-1) isnt "/") isAbsolute = srcPath[0] is "" or (srcPath[0] and srcPath[0].charAt(0) is "/") # put the host back if psychotic result.hostname = result.host = (if isAbsolute then "" else (if srcPath.length then srcPath.shift() else "")) #occationaly the auth can get stuck only in host #this especialy happens in cases like #url.resolveObject('mailto:local1@domain1', 'local2@domain2') authInHost = (if result.host and result.host.indexOf("@") > 0 then result.host.split("@") else false) if authInHost result.auth = authInHost.shift() result.host = result.hostname = authInHost.shift() mustEndAbs = mustEndAbs or (result.host and srcPath.length) srcPath.unshift "" if mustEndAbs and not isAbsolute unless srcPath.length result.pathname = null result.path = null else result.pathname = srcPath.join("/") #to support request.http result.path = ((if result.pathname then result.pathname else "")) + ((if result.search then result.search else "")) if not util.isNull(result.pathname) or not util.isNull(result.search) result.auth = relative.auth or result.auth result.slashes = result.slashes or relative.slashes result.href = result.format() result Url::parseHost = -> host = @host port = portPattern.exec(host) if port port = port[0] @port = port.substr(1) if port isnt ":" host = host.substr(0, host.length - port.length) @hostname = host if host return
138717
# 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. Url = -> @protocol = null @slashes = null @auth = null @host = null @port = null @hostname = null @hash = null @search = null @query = null @pathname = null @path = null @href = null return # Reference: RFC 3986, RFC 1808, RFC 2396 # define these here so at least they only have to be # compiled once on the first module load. # Special case for a simple path URL # RFC 2396: characters reserved for delimiting URLs. # We actually just auto-escape these. # RFC 2396: characters not allowed for various reasons. # Allowed by RFCs, but cause of XSS attacks. Always escape these. # Characters that are never ever allowed in a hostname. # Note that any invalid chars are also handled, but these # are the ones that are *expected* to be seen, so we fast-path # them. # protocols that can allow "unsafe" and "unwise" chars. # protocols that never have a hostname. # protocols that always contain a // bit. urlParse = (url, parseQueryString, slashesDenoteHost) -> return url if url and util.isObject(url) and url instanceof Url u = new Url u.parse url, parseQueryString, slashesDenoteHost u # Copy chrome, IE, opera backslash-handling behavior. # Back slashes before the query string get converted to forward slashes # See: https://code.google.com/p/chromium/issues/detail?id=25916 # trim before proceeding. # This is to support parse stuff like " http://foo.com \n" # Try fast path regexp # figure out if it's got a host # user@server is *always* interpreted as a hostname, and url # resolution will treat //foo/bar as host=foo,path=bar because that's # how the browser resolves relative URLs. # there's a hostname. # the first instance of /, ?, ;, or # ends the host. # # If there is an @ in the hostname, then non-host chars *are* allowed # to the left of the last @ sign, unless some host-ending character # comes *before* the @-sign. # URLs are obnoxious. # # ex: # http://a@b@c/ => user:a@b host:c # http://a@b?@c => user:a host:c path:/?@c # v0.12 TODO(isaacs): This is not quite how Chrome does things. # Review our test case against browsers more comprehensively. # find the first instance of any hostEndingChars # at this point, either we have an explicit point where the # auth portion cannot go past, or the last @ char is the decider. # atSign can be anywhere. # atSign must be in auth portion. # http://a@b/c@d => host:b auth:a path:/c@d # Now we have a portion which is definitely the auth. # Pull that off. # the host is the remaining to the left of the first non-host char # if we still have not hit it, then the entire thing is a host. # pull out port. # we've indicated that there is a hostname, # so even if it's empty, it has to be present. # if hostname begins with [ and ends with ] # assume that it's an IPv6 address. # validate a little. # we replace non-ASCII char with a temporary placeholder # we need this to make sure size of hostname is not # broken by replacing non-ASCII by nothing # we test again with ASCII char only # hostnames are always lower case. # IDNA Support: Returns a punycoded representation of "domain". # It only converts parts of the domain name that # have non-ASCII characters, i.e. it doesn't matter if # you call it with a domain that already is ASCII-only. # strip [ and ] from the hostname # the host field still retains them, though # now rest is set to the post-host stuff. # chop off any delim chars. # First, make 100% sure that any "autoEscape" chars get # escaped, even if encodeURIComponent doesn't think they # need to be. # chop off from the tail first. # got a fragment string. # no query string, but parseQueryString still requested #to support http.request # finally, reconstruct the href based on what has been validated. # format a parsed object into a url string urlFormat = (obj) -> # ensure it's an object, and not a string url. # If it's an obj, this is a no-op. # this way, you can call url_format() on strings # to clean up potentially wonky urls. obj = urlParse(obj) if util.isString(obj) return Url::format.call(obj) unless obj instanceof Url obj.format() # only the slashedProtocols get the //. Not mailto:, xmpp:, etc. # unless they had them to begin with. urlResolve = (source, relative) -> urlParse(source, false, true).resolve relative urlResolveObject = (source, relative) -> return relative unless source urlParse(source, false, true).resolveObject relative "use strict" punycode = require("punycode") util = require("util") exports.parse = urlParse exports.resolve = urlResolve exports.resolveObject = urlResolveObject exports.format = urlFormat exports.Url = Url protocolPattern = /^([a-z0-9.+-]+:)/i portPattern = /:[0-9]*$/ simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/ delims = [ "<" ">" "\"" "`" " " "\r" "\n" "\t" ] unwise = [ "{" "}" "|" "\\" "^" "`" ].concat(delims) autoEscape = ["'"].concat(unwise) nonHostChars = [ "%" "/" "?" ";" "#" ].concat(autoEscape) hostEndingChars = [ "/" "?" "#" ] hostnameMaxLen = 255 hostnamePatternString = "[^" + nonHostChars.join("") + "]{0,63}" hostnamePartPattern = new RegExp("^" + hostnamePatternString + "$") hostnamePartStart = new RegExp("^(" + hostnamePatternString + ")(.*)$") unsafeProtocol = javascript: true "javascript:": true hostlessProtocol = javascript: true "javascript:": true slashedProtocol = http: true https: true ftp: true gopher: true file: true "http:": true "https:": true "ftp:": true "gopher:": true "file:": true querystring = require("querystring") Url::parse = (url, parseQueryString, slashesDenoteHost) -> throw new TypeError("Parameter 'url' must be a string, not " + typeof url) unless util.isString(url) queryIndex = url.indexOf("?") splitter = (if (queryIndex isnt -1 and queryIndex < url.indexOf("#")) then "?" else "#") uSplit = url.split(splitter) slashRegex = /\\/g uSplit[0] = uSplit[0].replace(slashRegex, "/") url = uSplit.join(splitter) rest = url rest = rest.trim() if not slashesDenoteHost and url.split("#").length is 1 simplePath = simplePathPattern.exec(rest) if simplePath @path = rest @href = rest @pathname = simplePath[1] if simplePath[2] @search = simplePath[2] if parseQueryString @query = querystring.parse(@search.substr(1)) else @query = @search.substr(1) else if parseQueryString @search = "" @query = {} return this proto = protocolPattern.exec(rest) if proto proto = proto[0] lowerProto = proto.toLowerCase() @protocol = lowerProto rest = rest.substr(proto.length) if slashesDenoteHost or proto or rest.match(/^\/\/[^@\/]+@[^@\/]+/) slashes = rest.substr(0, 2) is "//" if slashes and not (proto and hostlessProtocol[proto]) rest = rest.substr(2) @slashes = true if not hostlessProtocol[proto] and (slashes or (proto and not slashedProtocol[proto])) hostEnd = -1 i = 0 while i < hostEndingChars.length hec = rest.indexOf(hostEndingChars[i]) hostEnd = hec if hec isnt -1 and (hostEnd is -1 or hec < hostEnd) i++ auth = undefined atSign = undefined if hostEnd is -1 atSign = rest.lastIndexOf("@") else atSign = rest.lastIndexOf("@", hostEnd) if atSign isnt -1 auth = rest.slice(0, atSign) rest = rest.slice(atSign + 1) @auth = decodeURIComponent(auth) hostEnd = -1 i = 0 while i < nonHostChars.length hec = rest.indexOf(nonHostChars[i]) hostEnd = hec if hec isnt -1 and (hostEnd is -1 or hec < hostEnd) i++ hostEnd = rest.length if hostEnd is -1 @host = rest.slice(0, hostEnd) rest = rest.slice(hostEnd) @parseHost() @hostname = @hostname or "" ipv6Hostname = @hostname[0] is "[" and @hostname[@hostname.length - 1] is "]" unless ipv6Hostname hostparts = @hostname.split(/\./) i = 0 l = hostparts.length while i < l part = hostparts[i] continue unless part unless part.match(hostnamePartPattern) newpart = "" j = 0 k = part.length while j < k if part.charCodeAt(j) > 127 newpart += "x" else newpart += part[j] j++ unless newpart.match(hostnamePartPattern) validParts = hostparts.slice(0, i) notHost = hostparts.slice(i + 1) bit = part.match(hostnamePartStart) if bit validParts.push bit[1] notHost.unshift bit[2] rest = "/" + notHost.join(".") + rest if notHost.length @hostname = validParts.join(".") break i++ if @hostname.length > hostnameMaxLen @hostname = "" else @hostname = @hostname.toLowerCase() @hostname = punycode.toASCII(@hostname) unless ipv6Hostname p = (if @port then ":" + @port else "") h = @hostname or "" @host = h + p @href += @host if ipv6Hostname @hostname = @hostname.substr(1, @hostname.length - 2) rest = "/" + rest if rest[0] isnt "/" unless unsafeProtocol[lowerProto] i = 0 l = autoEscape.length while i < l ae = autoEscape[i] esc = encodeURIComponent(ae) esc = escape(ae) if esc is ae rest = rest.split(ae).join(esc) i++ hash = rest.indexOf("#") if hash isnt -1 @hash = rest.substr(hash) rest = rest.slice(0, hash) qm = rest.indexOf("?") if qm isnt -1 @search = rest.substr(qm) @query = rest.substr(qm + 1) @query = querystring.parse(@query) if parseQueryString rest = rest.slice(0, qm) else if parseQueryString @search = "" @query = {} @pathname = rest if rest @pathname = "/" if slashedProtocol[lowerProto] and @hostname and not @pathname if @pathname or @search p = @pathname or "" s = @search or "" @path = p + s @href = @format(parseQueryString) this Url::format = (parseQueryString) -> auth = @auth or "" if auth auth = encodeURIComponent(auth) auth = auth.replace(/%3A/i, ":") auth += "@" protocol = @protocol or "" pathname = @pathname or "" hash = @hash or "" host = false query = "" search = "" if @path qm = @path.indexOf("?") if qm isnt -1 query = @path.slice(qm + 1) search = "?" + query pathname = @path.slice(0, qm) else if parseQueryString @query = {} @search = "" else @query = null @search = null pathname = @path if @host host = auth + @host else if @hostname host = auth + ((if @hostname.indexOf(":") is -1 then @hostname else "[" + @hostname + "]")) host += ":" + @port if @port query = querystring.stringify(@query) if not query and @query and util.isObject(@query) and Object.keys(@query).length search = @search or (query and ("?" + query)) or "" unless search protocol += ":" if protocol and protocol.substr(-1) isnt ":" if @slashes or (not protocol or slashedProtocol[protocol]) and host isnt false host = "//" + (host or "") pathname = "/" + pathname if pathname and pathname.charAt(0) isnt "/" else host = "" unless host hash = "#" + hash if hash and hash.charAt(0) isnt "#" search = "?" + search if search and search.charAt(0) isnt "?" pathname = pathname.replace(/[?#]/g, (match) -> encodeURIComponent match ) search = search.replace("#", "%23") protocol + host + pathname + search + hash Url::resolve = (relative) -> @resolveObject(urlParse(relative, false, true)).format() Url::resolveObject = (relative) -> if util.isString(relative) rel = new Url() rel.parse relative, false, true relative = rel result = new Url() tkeys = Object.keys(this) tk = 0 while tk < tkeys.length tkey = tkeys[tk] result[tkey] = this[tkey] tk++ # hash is always overridden, no matter what. # even href="" will remove it. result.hash = relative.hash # if the relative url is empty, then there's nothing left to do here. if relative.href is "" result.href = result.format() return result # hrefs like //foo/bar always cut to the protocol. if relative.slashes and not relative.protocol # take everything except the protocol from relative rkeys = Object.keys(relative) rk = 0 while rk < rkeys.length rkey = rkeys[rk] result[rkey] = relative[rkey] if rkey isnt "protocol" rk++ #urlParse appends trailing / to urls like http://www.example.com result.path = result.pathname = "/" if slashedProtocol[result.protocol] and result.hostname and not result.pathname result.href = result.format() return result if relative.protocol and relative.protocol isnt result.protocol # if it's a known url protocol, then changing # the protocol does weird things # first, if it's not file:, then we MUST have a host, # and if there was a path # to begin with, then we MUST have a path. # if it is file:, then the host is dropped, # because that's known to be hostless. # anything else is assumed to be absolute. unless slashedProtocol[relative.protocol] keys = Object.keys(relative) v = 0 while v < keys.length k = keys[v] result[k] = relative[k] v++ result.href = result.format() return result result.protocol = relative.protocol if not relative.host and not hostlessProtocol[relative.protocol] relPath = (relative.pathname or "").split("/") while relPath.length and not (relative.host = relPath.shift()) relative.host = "" unless relative.host relative.hostname = "" unless relative.hostname relPath.unshift "" if relPath[0] isnt "" relPath.unshift "" if relPath.length < 2 result.pathname = relPath.join("/") else result.pathname = relative.pathname result.search = relative.search result.query = relative.query result.host = relative.host or "" result.auth = relative.auth result.hostname = relative.hostname or relative.host result.port = relative.port # to support http.request if result.pathname or result.search p = result.pathname or "" s = result.search or "" result.path = p + s result.slashes = result.slashes or relative.slashes result.href = result.format() return result isSourceAbs = (result.pathname and result.pathname.charAt(0) is "/") isRelAbs = (relative.host or relative.pathname and relative.pathname.charAt(0) is "/") mustEndAbs = (isRelAbs or isSourceAbs or (result.host and relative.pathname)) removeAllDots = mustEndAbs srcPath = result.pathname and result.pathname.split("/") or [] relPath = relative.pathname and relative.pathname.split("/") or [] psychotic = result.protocol and not slashedProtocol[result.protocol] # if the url is a non-slashed url, then relative # links like ../.. should be able # to crawl up to the hostname, as well. This is strange. # result.protocol has already been set by now. # Later on, put the first path part into the host field. if psychotic result.hostname = "" result.port = null if result.host if srcPath[0] is "" srcPath[0] = result.host else srcPath.unshift result.host result.host = "" if relative.protocol relative.hostname = null relative.port = null if relative.host if relPath[0] is "" relPath[0] = relative.host else relPath.unshift relative.host relative.host = null mustEndAbs = mustEndAbs and (relPath[0] is "" or srcPath[0] is "") if isRelAbs # it's absolute. result.host = (if (relative.host or relative.host is "") then relative.host else result.host) result.hostname = (if (relative.hostname or relative.hostname is "") then relative.hostname else result.hostname) result.search = relative.search result.query = relative.query srcPath = relPath # fall through to the dot-handling below. else if relPath.length # it's relative # throw away the existing file, and take the new path instead. srcPath = [] unless srcPath srcPath.pop() srcPath = srcPath.concat(relPath) result.search = relative.search result.query = relative.query else unless util.isNullOrUndefined(relative.search) # just pull out the search. # like href='?foo'. # Put this after the other two cases because it simplifies the booleans if psychotic result.hostname = result.host = srcPath.shift() #occationaly the auth can get stuck only in host #this especialy happens in cases like #url.resolveObject('mailto:local1@domain1', 'local2@domain2') authInHost = (if result.host and result.host.indexOf("@") > 0 then result.host.split("@") else false) if authInHost result.auth = authInHost.shift() result.host = result.hostname = authInHost.shift() result.search = relative.search result.query = relative.query #to support http.request result.path = ((if result.pathname then result.pathname else "")) + ((if result.search then result.search else "")) if not util.isNull(result.pathname) or not util.isNull(result.search) result.href = result.format() return result unless srcPath.length # no path at all. easy. # we've already handled the other stuff above. result.pathname = null #to support http.request if result.search result.path = "/" + result.search else result.path = null result.href = result.format() return result # if a url ENDs in . or .., then it must get a trailing slash. # however, if it ends in anything else non-slashy, # then it must NOT get a trailing slash. last = srcPath.slice(-1)[0] hasTrailingSlash = ((result.host or relative.host) and (last is "." or last is "..") or last is "") # strip single dots, resolve double dots to parent dir # if the path tries to go above the root, `up` ends up > 0 up = 0 i = srcPath.length while i >= 0 last = srcPath[i] if last is "." srcPath.splice i, 1 else if last is ".." srcPath.splice i, 1 up++ else if up srcPath.splice i, 1 up-- i-- # if the path is allowed to go above the root, restore leading ..s if not mustEndAbs and not removeAllDots while up-- srcPath.unshift ".." up srcPath.unshift "" if mustEndAbs and srcPath[0] isnt "" and (not srcPath[0] or srcPath[0].charAt(0) isnt "/") srcPath.push "" if hasTrailingSlash and (srcPath.join("/").substr(-1) isnt "/") isAbsolute = srcPath[0] is "" or (srcPath[0] and srcPath[0].charAt(0) is "/") # put the host back if psychotic result.hostname = result.host = (if isAbsolute then "" else (if srcPath.length then srcPath.shift() else "")) #occationaly the auth can get stuck only in host #this especialy happens in cases like #url.resolveObject('mailto:local1@domain1', 'local<EMAIL>@domain<EMAIL>') authInHost = (if result.host and result.host.indexOf("@") > 0 then result.host.split("@") else false) if authInHost result.auth = authInHost.shift() result.host = result.hostname = authInHost.shift() mustEndAbs = mustEndAbs or (result.host and srcPath.length) srcPath.unshift "" if mustEndAbs and not isAbsolute unless srcPath.length result.pathname = null result.path = null else result.pathname = srcPath.join("/") #to support request.http result.path = ((if result.pathname then result.pathname else "")) + ((if result.search then result.search else "")) if not util.isNull(result.pathname) or not util.isNull(result.search) result.auth = relative.auth or result.auth result.slashes = result.slashes or relative.slashes result.href = result.format() result Url::parseHost = -> host = @host port = portPattern.exec(host) if port port = port[0] @port = port.substr(1) if port isnt ":" host = host.substr(0, host.length - port.length) @hostname = host if host 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. Url = -> @protocol = null @slashes = null @auth = null @host = null @port = null @hostname = null @hash = null @search = null @query = null @pathname = null @path = null @href = null return # Reference: RFC 3986, RFC 1808, RFC 2396 # define these here so at least they only have to be # compiled once on the first module load. # Special case for a simple path URL # RFC 2396: characters reserved for delimiting URLs. # We actually just auto-escape these. # RFC 2396: characters not allowed for various reasons. # Allowed by RFCs, but cause of XSS attacks. Always escape these. # Characters that are never ever allowed in a hostname. # Note that any invalid chars are also handled, but these # are the ones that are *expected* to be seen, so we fast-path # them. # protocols that can allow "unsafe" and "unwise" chars. # protocols that never have a hostname. # protocols that always contain a // bit. urlParse = (url, parseQueryString, slashesDenoteHost) -> return url if url and util.isObject(url) and url instanceof Url u = new Url u.parse url, parseQueryString, slashesDenoteHost u # Copy chrome, IE, opera backslash-handling behavior. # Back slashes before the query string get converted to forward slashes # See: https://code.google.com/p/chromium/issues/detail?id=25916 # trim before proceeding. # This is to support parse stuff like " http://foo.com \n" # Try fast path regexp # figure out if it's got a host # user@server is *always* interpreted as a hostname, and url # resolution will treat //foo/bar as host=foo,path=bar because that's # how the browser resolves relative URLs. # there's a hostname. # the first instance of /, ?, ;, or # ends the host. # # If there is an @ in the hostname, then non-host chars *are* allowed # to the left of the last @ sign, unless some host-ending character # comes *before* the @-sign. # URLs are obnoxious. # # ex: # http://a@b@c/ => user:a@b host:c # http://a@b?@c => user:a host:c path:/?@c # v0.12 TODO(isaacs): This is not quite how Chrome does things. # Review our test case against browsers more comprehensively. # find the first instance of any hostEndingChars # at this point, either we have an explicit point where the # auth portion cannot go past, or the last @ char is the decider. # atSign can be anywhere. # atSign must be in auth portion. # http://a@b/c@d => host:b auth:a path:/c@d # Now we have a portion which is definitely the auth. # Pull that off. # the host is the remaining to the left of the first non-host char # if we still have not hit it, then the entire thing is a host. # pull out port. # we've indicated that there is a hostname, # so even if it's empty, it has to be present. # if hostname begins with [ and ends with ] # assume that it's an IPv6 address. # validate a little. # we replace non-ASCII char with a temporary placeholder # we need this to make sure size of hostname is not # broken by replacing non-ASCII by nothing # we test again with ASCII char only # hostnames are always lower case. # IDNA Support: Returns a punycoded representation of "domain". # It only converts parts of the domain name that # have non-ASCII characters, i.e. it doesn't matter if # you call it with a domain that already is ASCII-only. # strip [ and ] from the hostname # the host field still retains them, though # now rest is set to the post-host stuff. # chop off any delim chars. # First, make 100% sure that any "autoEscape" chars get # escaped, even if encodeURIComponent doesn't think they # need to be. # chop off from the tail first. # got a fragment string. # no query string, but parseQueryString still requested #to support http.request # finally, reconstruct the href based on what has been validated. # format a parsed object into a url string urlFormat = (obj) -> # ensure it's an object, and not a string url. # If it's an obj, this is a no-op. # this way, you can call url_format() on strings # to clean up potentially wonky urls. obj = urlParse(obj) if util.isString(obj) return Url::format.call(obj) unless obj instanceof Url obj.format() # only the slashedProtocols get the //. Not mailto:, xmpp:, etc. # unless they had them to begin with. urlResolve = (source, relative) -> urlParse(source, false, true).resolve relative urlResolveObject = (source, relative) -> return relative unless source urlParse(source, false, true).resolveObject relative "use strict" punycode = require("punycode") util = require("util") exports.parse = urlParse exports.resolve = urlResolve exports.resolveObject = urlResolveObject exports.format = urlFormat exports.Url = Url protocolPattern = /^([a-z0-9.+-]+:)/i portPattern = /:[0-9]*$/ simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/ delims = [ "<" ">" "\"" "`" " " "\r" "\n" "\t" ] unwise = [ "{" "}" "|" "\\" "^" "`" ].concat(delims) autoEscape = ["'"].concat(unwise) nonHostChars = [ "%" "/" "?" ";" "#" ].concat(autoEscape) hostEndingChars = [ "/" "?" "#" ] hostnameMaxLen = 255 hostnamePatternString = "[^" + nonHostChars.join("") + "]{0,63}" hostnamePartPattern = new RegExp("^" + hostnamePatternString + "$") hostnamePartStart = new RegExp("^(" + hostnamePatternString + ")(.*)$") unsafeProtocol = javascript: true "javascript:": true hostlessProtocol = javascript: true "javascript:": true slashedProtocol = http: true https: true ftp: true gopher: true file: true "http:": true "https:": true "ftp:": true "gopher:": true "file:": true querystring = require("querystring") Url::parse = (url, parseQueryString, slashesDenoteHost) -> throw new TypeError("Parameter 'url' must be a string, not " + typeof url) unless util.isString(url) queryIndex = url.indexOf("?") splitter = (if (queryIndex isnt -1 and queryIndex < url.indexOf("#")) then "?" else "#") uSplit = url.split(splitter) slashRegex = /\\/g uSplit[0] = uSplit[0].replace(slashRegex, "/") url = uSplit.join(splitter) rest = url rest = rest.trim() if not slashesDenoteHost and url.split("#").length is 1 simplePath = simplePathPattern.exec(rest) if simplePath @path = rest @href = rest @pathname = simplePath[1] if simplePath[2] @search = simplePath[2] if parseQueryString @query = querystring.parse(@search.substr(1)) else @query = @search.substr(1) else if parseQueryString @search = "" @query = {} return this proto = protocolPattern.exec(rest) if proto proto = proto[0] lowerProto = proto.toLowerCase() @protocol = lowerProto rest = rest.substr(proto.length) if slashesDenoteHost or proto or rest.match(/^\/\/[^@\/]+@[^@\/]+/) slashes = rest.substr(0, 2) is "//" if slashes and not (proto and hostlessProtocol[proto]) rest = rest.substr(2) @slashes = true if not hostlessProtocol[proto] and (slashes or (proto and not slashedProtocol[proto])) hostEnd = -1 i = 0 while i < hostEndingChars.length hec = rest.indexOf(hostEndingChars[i]) hostEnd = hec if hec isnt -1 and (hostEnd is -1 or hec < hostEnd) i++ auth = undefined atSign = undefined if hostEnd is -1 atSign = rest.lastIndexOf("@") else atSign = rest.lastIndexOf("@", hostEnd) if atSign isnt -1 auth = rest.slice(0, atSign) rest = rest.slice(atSign + 1) @auth = decodeURIComponent(auth) hostEnd = -1 i = 0 while i < nonHostChars.length hec = rest.indexOf(nonHostChars[i]) hostEnd = hec if hec isnt -1 and (hostEnd is -1 or hec < hostEnd) i++ hostEnd = rest.length if hostEnd is -1 @host = rest.slice(0, hostEnd) rest = rest.slice(hostEnd) @parseHost() @hostname = @hostname or "" ipv6Hostname = @hostname[0] is "[" and @hostname[@hostname.length - 1] is "]" unless ipv6Hostname hostparts = @hostname.split(/\./) i = 0 l = hostparts.length while i < l part = hostparts[i] continue unless part unless part.match(hostnamePartPattern) newpart = "" j = 0 k = part.length while j < k if part.charCodeAt(j) > 127 newpart += "x" else newpart += part[j] j++ unless newpart.match(hostnamePartPattern) validParts = hostparts.slice(0, i) notHost = hostparts.slice(i + 1) bit = part.match(hostnamePartStart) if bit validParts.push bit[1] notHost.unshift bit[2] rest = "/" + notHost.join(".") + rest if notHost.length @hostname = validParts.join(".") break i++ if @hostname.length > hostnameMaxLen @hostname = "" else @hostname = @hostname.toLowerCase() @hostname = punycode.toASCII(@hostname) unless ipv6Hostname p = (if @port then ":" + @port else "") h = @hostname or "" @host = h + p @href += @host if ipv6Hostname @hostname = @hostname.substr(1, @hostname.length - 2) rest = "/" + rest if rest[0] isnt "/" unless unsafeProtocol[lowerProto] i = 0 l = autoEscape.length while i < l ae = autoEscape[i] esc = encodeURIComponent(ae) esc = escape(ae) if esc is ae rest = rest.split(ae).join(esc) i++ hash = rest.indexOf("#") if hash isnt -1 @hash = rest.substr(hash) rest = rest.slice(0, hash) qm = rest.indexOf("?") if qm isnt -1 @search = rest.substr(qm) @query = rest.substr(qm + 1) @query = querystring.parse(@query) if parseQueryString rest = rest.slice(0, qm) else if parseQueryString @search = "" @query = {} @pathname = rest if rest @pathname = "/" if slashedProtocol[lowerProto] and @hostname and not @pathname if @pathname or @search p = @pathname or "" s = @search or "" @path = p + s @href = @format(parseQueryString) this Url::format = (parseQueryString) -> auth = @auth or "" if auth auth = encodeURIComponent(auth) auth = auth.replace(/%3A/i, ":") auth += "@" protocol = @protocol or "" pathname = @pathname or "" hash = @hash or "" host = false query = "" search = "" if @path qm = @path.indexOf("?") if qm isnt -1 query = @path.slice(qm + 1) search = "?" + query pathname = @path.slice(0, qm) else if parseQueryString @query = {} @search = "" else @query = null @search = null pathname = @path if @host host = auth + @host else if @hostname host = auth + ((if @hostname.indexOf(":") is -1 then @hostname else "[" + @hostname + "]")) host += ":" + @port if @port query = querystring.stringify(@query) if not query and @query and util.isObject(@query) and Object.keys(@query).length search = @search or (query and ("?" + query)) or "" unless search protocol += ":" if protocol and protocol.substr(-1) isnt ":" if @slashes or (not protocol or slashedProtocol[protocol]) and host isnt false host = "//" + (host or "") pathname = "/" + pathname if pathname and pathname.charAt(0) isnt "/" else host = "" unless host hash = "#" + hash if hash and hash.charAt(0) isnt "#" search = "?" + search if search and search.charAt(0) isnt "?" pathname = pathname.replace(/[?#]/g, (match) -> encodeURIComponent match ) search = search.replace("#", "%23") protocol + host + pathname + search + hash Url::resolve = (relative) -> @resolveObject(urlParse(relative, false, true)).format() Url::resolveObject = (relative) -> if util.isString(relative) rel = new Url() rel.parse relative, false, true relative = rel result = new Url() tkeys = Object.keys(this) tk = 0 while tk < tkeys.length tkey = tkeys[tk] result[tkey] = this[tkey] tk++ # hash is always overridden, no matter what. # even href="" will remove it. result.hash = relative.hash # if the relative url is empty, then there's nothing left to do here. if relative.href is "" result.href = result.format() return result # hrefs like //foo/bar always cut to the protocol. if relative.slashes and not relative.protocol # take everything except the protocol from relative rkeys = Object.keys(relative) rk = 0 while rk < rkeys.length rkey = rkeys[rk] result[rkey] = relative[rkey] if rkey isnt "protocol" rk++ #urlParse appends trailing / to urls like http://www.example.com result.path = result.pathname = "/" if slashedProtocol[result.protocol] and result.hostname and not result.pathname result.href = result.format() return result if relative.protocol and relative.protocol isnt result.protocol # if it's a known url protocol, then changing # the protocol does weird things # first, if it's not file:, then we MUST have a host, # and if there was a path # to begin with, then we MUST have a path. # if it is file:, then the host is dropped, # because that's known to be hostless. # anything else is assumed to be absolute. unless slashedProtocol[relative.protocol] keys = Object.keys(relative) v = 0 while v < keys.length k = keys[v] result[k] = relative[k] v++ result.href = result.format() return result result.protocol = relative.protocol if not relative.host and not hostlessProtocol[relative.protocol] relPath = (relative.pathname or "").split("/") while relPath.length and not (relative.host = relPath.shift()) relative.host = "" unless relative.host relative.hostname = "" unless relative.hostname relPath.unshift "" if relPath[0] isnt "" relPath.unshift "" if relPath.length < 2 result.pathname = relPath.join("/") else result.pathname = relative.pathname result.search = relative.search result.query = relative.query result.host = relative.host or "" result.auth = relative.auth result.hostname = relative.hostname or relative.host result.port = relative.port # to support http.request if result.pathname or result.search p = result.pathname or "" s = result.search or "" result.path = p + s result.slashes = result.slashes or relative.slashes result.href = result.format() return result isSourceAbs = (result.pathname and result.pathname.charAt(0) is "/") isRelAbs = (relative.host or relative.pathname and relative.pathname.charAt(0) is "/") mustEndAbs = (isRelAbs or isSourceAbs or (result.host and relative.pathname)) removeAllDots = mustEndAbs srcPath = result.pathname and result.pathname.split("/") or [] relPath = relative.pathname and relative.pathname.split("/") or [] psychotic = result.protocol and not slashedProtocol[result.protocol] # if the url is a non-slashed url, then relative # links like ../.. should be able # to crawl up to the hostname, as well. This is strange. # result.protocol has already been set by now. # Later on, put the first path part into the host field. if psychotic result.hostname = "" result.port = null if result.host if srcPath[0] is "" srcPath[0] = result.host else srcPath.unshift result.host result.host = "" if relative.protocol relative.hostname = null relative.port = null if relative.host if relPath[0] is "" relPath[0] = relative.host else relPath.unshift relative.host relative.host = null mustEndAbs = mustEndAbs and (relPath[0] is "" or srcPath[0] is "") if isRelAbs # it's absolute. result.host = (if (relative.host or relative.host is "") then relative.host else result.host) result.hostname = (if (relative.hostname or relative.hostname is "") then relative.hostname else result.hostname) result.search = relative.search result.query = relative.query srcPath = relPath # fall through to the dot-handling below. else if relPath.length # it's relative # throw away the existing file, and take the new path instead. srcPath = [] unless srcPath srcPath.pop() srcPath = srcPath.concat(relPath) result.search = relative.search result.query = relative.query else unless util.isNullOrUndefined(relative.search) # just pull out the search. # like href='?foo'. # Put this after the other two cases because it simplifies the booleans if psychotic result.hostname = result.host = srcPath.shift() #occationaly the auth can get stuck only in host #this especialy happens in cases like #url.resolveObject('mailto:local1@domain1', 'local2@domain2') authInHost = (if result.host and result.host.indexOf("@") > 0 then result.host.split("@") else false) if authInHost result.auth = authInHost.shift() result.host = result.hostname = authInHost.shift() result.search = relative.search result.query = relative.query #to support http.request result.path = ((if result.pathname then result.pathname else "")) + ((if result.search then result.search else "")) if not util.isNull(result.pathname) or not util.isNull(result.search) result.href = result.format() return result unless srcPath.length # no path at all. easy. # we've already handled the other stuff above. result.pathname = null #to support http.request if result.search result.path = "/" + result.search else result.path = null result.href = result.format() return result # if a url ENDs in . or .., then it must get a trailing slash. # however, if it ends in anything else non-slashy, # then it must NOT get a trailing slash. last = srcPath.slice(-1)[0] hasTrailingSlash = ((result.host or relative.host) and (last is "." or last is "..") or last is "") # strip single dots, resolve double dots to parent dir # if the path tries to go above the root, `up` ends up > 0 up = 0 i = srcPath.length while i >= 0 last = srcPath[i] if last is "." srcPath.splice i, 1 else if last is ".." srcPath.splice i, 1 up++ else if up srcPath.splice i, 1 up-- i-- # if the path is allowed to go above the root, restore leading ..s if not mustEndAbs and not removeAllDots while up-- srcPath.unshift ".." up srcPath.unshift "" if mustEndAbs and srcPath[0] isnt "" and (not srcPath[0] or srcPath[0].charAt(0) isnt "/") srcPath.push "" if hasTrailingSlash and (srcPath.join("/").substr(-1) isnt "/") isAbsolute = srcPath[0] is "" or (srcPath[0] and srcPath[0].charAt(0) is "/") # put the host back if psychotic result.hostname = result.host = (if isAbsolute then "" else (if srcPath.length then srcPath.shift() else "")) #occationaly the auth can get stuck only in host #this especialy happens in cases like #url.resolveObject('mailto:local1@domain1', 'localPI:EMAIL:<EMAIL>END_PI@domainPI:EMAIL:<EMAIL>END_PI') authInHost = (if result.host and result.host.indexOf("@") > 0 then result.host.split("@") else false) if authInHost result.auth = authInHost.shift() result.host = result.hostname = authInHost.shift() mustEndAbs = mustEndAbs or (result.host and srcPath.length) srcPath.unshift "" if mustEndAbs and not isAbsolute unless srcPath.length result.pathname = null result.path = null else result.pathname = srcPath.join("/") #to support request.http result.path = ((if result.pathname then result.pathname else "")) + ((if result.search then result.search else "")) if not util.isNull(result.pathname) or not util.isNull(result.search) result.auth = relative.auth or result.auth result.slashes = result.slashes or relative.slashes result.href = result.format() result Url::parseHost = -> host = @host port = portPattern.exec(host) if port port = port[0] @port = port.substr(1) if port isnt ":" host = host.substr(0, host.length - port.length) @hostname = host if host return
[ { "context": "mal resolution\n if fullHero.get('name') in ['Knight', 'Robot Walker'] # These are too big, so shrink", "end": 5777, "score": 0.9997127652168274, "start": 5771, "tag": "NAME", "value": "Knight" }, { "context": "tion\n if fullHero.get('name') in ['Knight', 'Robot Walker'] # These are too big, so shrink them.\n m", "end": 5793, "score": 0.9997472167015076, "start": 5781, "tag": "NAME", "value": "Robot Walker" }, { "context": "odal itself is dismissed\n\n\ntemporaryHeroInfo =\n knight:\n fullName: 'Tharin Thunderfist'\n weapons: ", "end": 7568, "score": 0.5255604982376099, "start": 7563, "tag": "NAME", "value": "night" }, { "context": "ed\n\n\ntemporaryHeroInfo =\n knight:\n fullName: 'Tharin Thunderfist'\n weapons: 'Swords - Short Range, No Magic'\n ", "end": 7603, "score": 0.9998964071273804, "start": 7585, "tag": "NAME", "value": "Tharin Thunderfist" }, { "context": "5\n speedAbsolute: 6\n\n captain:\n fullName: 'Captain Anya Weston'\n weapons: 'Swords - Short Range, No Magic'\n ", "end": 7893, "score": 0.9998301863670349, "start": 7874, "tag": "NAME", "value": "Captain Anya Weston" }, { "context": "Factor: 1.4\n speed: 1.5\n speedAbsolute: 6\n\n thoktar:\n fullName: 'Thoktar the Devourer'\n weapons", "end": 8176, "score": 0.8324456214904785, "start": 8169, "tag": "NAME", "value": "thoktar" }, { "context": "5\n speedAbsolute: 6\n\n thoktar:\n fullName: 'Thoktar the Devourer'\n weapons: 'Wands, Staffs - Long Range, Magic'", "end": 8213, "score": 0.9998906850814819, "start": 8193, "tag": "NAME", "value": "Thoktar the Devourer" }, { "context": "emental', 'devour']\n\n equestrian:\n fullName: 'Rider Reynaldo'\n weapons: 'Crossbows, Guns - Long Range, No M", "end": 8522, "score": 0.9998772740364075, "start": 8508, "tag": "NAME", "value": "Rider Reynaldo" }, { "context": "ills: ['hide']\n\n 'potion-master':\n fullName: 'Master Snake'\n weapons: 'Wands, Staffs - Long Range, Magic'", "end": 8818, "score": 0.9997469782829285, "start": 8806, "tag": "NAME", "value": "Master Snake" }, { "context": "ills: ['brewPotion']\n\n librarian:\n fullName: 'Hushbaum'\n weapons: 'Wands, Staffs - Long Range, Magic'", "end": 9106, "score": 0.9993925094604492, "start": 9098, "tag": "NAME", "value": "Hushbaum" }, { "context": "ctor: 1.4\n speed: 2.5\n speedAbsolute: 7\n\n 'robot-walker':\n fullName: '???'\n weapons: '???'\n clas", "end": 9347, "score": 0.9380655884742737, "start": 9335, "tag": "USERNAME", "value": "robot-walker" }, { "context": "bsolute: 11\n skills: ['???', '???', '???']\n\n 'michael-heasell':\n fullName: '???'\n weapons: '???'\n clas", "end": 9617, "score": 0.9922961592674255, "start": 9602, "tag": "USERNAME", "value": "michael-heasell" }, { "context": " speedAbsolute: 16\n skills: ['???', '???']\n\n 'ian-elliott':\n fullName: '???'\n weapons: 'Swords - Shor", "end": 9873, "score": 0.9055588245391846, "start": 9862, "tag": "USERNAME", "value": "ian-elliott" } ]
app/views/game-menu/ChooseHeroView.coffee
rodeofly/rodeofly.github.io
0
CocoView = require 'views/kinds/CocoView' template = require 'templates/game-menu/choose-hero-view' {me} = require 'lib/auth' ThangType = require 'models/ThangType' CocoCollection = require 'collections/CocoCollection' SpriteBuilder = require 'lib/sprites/SpriteBuilder' AudioPlayer = require 'lib/AudioPlayer' module.exports = class ChooseHeroView extends CocoView id: 'choose-hero-view' className: 'tab-pane' template: template events: 'click #restart-level-confirm-button': -> Backbone.Mediator.publish 'level:restart', {} 'slide.bs.carousel #hero-carousel': 'onHeroChanged' 'change #option-code-language': 'onCodeLanguageChanged' shortcuts: 'left': -> @$el.find('#hero-carousel').carousel('prev') if @heroes.models.length and not @$el.hasClass 'secret' 'right': -> @$el.find('#hero-carousel').carousel('next') if @heroes.models.length and not @$el.hasClass 'secret' constructor: (options) -> super options @heroes = new CocoCollection([], {model: ThangType}) @heroes.url = '/db/thang.type?view=heroes&project=original,name,slug,soundTriggers,featureImage' @supermodel.loadCollection(@heroes, 'heroes') @stages = {} destroy: -> for heroIndex, stage of @stages createjs.Ticker.removeEventListener "tick", stage stage.removeAllChildren() super() getRenderData: (context={}) -> context = super(context) context.heroes = @heroes.models hero.locked = temporaryHeroInfo[hero.get('slug')].status is 'Locked' and not me.earnedHero hero.get('original') for hero in context.heroes context.level = @options.level context.codeLanguages = [ {id: 'python', name: 'Python (Default)'} {id: 'javascript', name: 'JavaScript'} {id: 'coffeescript', name: 'CoffeeScript'} {id: 'clojure', name: 'Clojure (Experimental)'} {id: 'lua', name: 'Lua (Experimental)'} {id: 'io', name: 'Io (Experimental)'} ] context.codeLanguage = @codeLanguage = @options.session.get('codeLanguage') ? me.get('aceConfig')?.language ? 'python' context.heroInfo = temporaryHeroInfo context afterRender: -> super() return unless @supermodel.finished() heroes = @heroes.models @$el.find('.hero-indicator').each -> heroID = $(@).data('hero-id') hero = _.find heroes, (hero) -> hero.get('original') is heroID $(@).find('.hero-avatar').css('background-image', "url(#{hero.getPortraitURL()})").tooltip() _.defer => $(@).addClass 'initialized' @canvasWidth = 313 # @$el.find('canvas').width() # unreliable, whatever @canvasHeight = @$el.find('canvas').height() heroConfig = @options.session.get('heroConfig') ? me.get('heroConfig') ? {} heroIndex = Math.max 0, _.findIndex(heroes, ((hero) -> hero.get('original') is heroConfig.thangType)) @$el.find(".hero-item:nth-child(#{heroIndex + 1}), .hero-indicator:nth-child(#{heroIndex + 1})").addClass('active') @onHeroChanged direction: null, relatedTarget: @$el.find('.hero-item')[heroIndex] @$el.find('.hero-stat').tooltip() @buildCodeLanguages() onHeroChanged: (e) -> direction = e.direction # 'left' or 'right' heroItem = $(e.relatedTarget) hero = _.find @heroes.models, (hero) -> hero.get('original') is heroItem.data('hero-id') return console.error "Couldn't find hero from heroItem:", heroItem unless hero heroIndex = heroItem.index() @$el.find('.hero-indicator').each -> distance = Math.min 3, Math.abs $(@).index() - heroIndex size = 100 - (50 / 3) * distance $(@).css width: size, height: size, top: -(100 - size) / 2 heroInfo = temporaryHeroInfo[hero.get('slug')] locked = heroInfo.status is 'Locked' and not me.earnedHero ThangType.heroes[hero.get('slug')] hero = @loadHero hero, heroIndex @preloadHero heroIndex + 1 @preloadHero heroIndex - 1 @selectedHero = hero unless locked Backbone.Mediator.publish 'level:hero-selection-updated', hero: @selectedHero $('#choose-inventory-button').prop 'disabled', locked getFullHero: (original) -> url = "/db/thang.type/#{original}/version" if fullHero = @supermodel.getModel url return fullHero fullHero = new ThangType() fullHero.setURL url fullHero = (@supermodel.loadModel fullHero, 'thang').model fullHero preloadHero: (heroIndex) -> return unless hero = @heroes.models[heroIndex] @loadHero hero, heroIndex, true loadHero: (hero, heroIndex, preloading=false) -> createjs.Ticker.removeEventListener 'tick', stage for stage in _.values @stages if featureImage = hero.get 'featureImage' $(".hero-item[data-hero-id='#{hero.get('original')}'] canvas").hide() $(".hero-item[data-hero-id='#{hero.get('original')}'] .hero-feature-image").show().find('img').prop('src', '/file/' + featureImage) @playSelectionSound hero unless preloading return hero createjs.Ticker.setFPS 30 # In case we paused it from being inactive somewhere else if stage = @stages[heroIndex] unless preloading _.defer -> createjs.Ticker.addEventListener 'tick', stage # Deferred, otherwise it won't start updating for some reason. @playSelectionSound hero return hero fullHero = @getFullHero hero.get 'original' onLoaded = => return unless canvas = $(".hero-item[data-hero-id='#{fullHero.get('original')}'] canvas") canvas.show().prop width: @canvasWidth, height: @canvasHeight builder = new SpriteBuilder(fullHero) movieClip = builder.buildMovieClip(fullHero.get('actions').attack?.animation ? fullHero.get('actions').idle.animation) movieClip.scaleX = movieClip.scaleY = canvas.prop('height') / 120 # Average hero height is ~110px tall at normal resolution if fullHero.get('name') in ['Knight', 'Robot Walker'] # These are too big, so shrink them. movieClip.scaleX *= 0.7 movieClip.scaleY *= 0.7 movieClip.regX = -fullHero.get('positions').registration.x movieClip.regY = -fullHero.get('positions').registration.y movieClip.x = canvas.prop('width') * 0.5 movieClip.y = canvas.prop('height') * 0.925 # This is where the feet go. stage = new createjs.Stage(canvas[0]) @stages[heroIndex] = stage stage.addChild movieClip stage.update() movieClip.gotoAndPlay 0 unless preloading createjs.Ticker.addEventListener 'tick', stage @playSelectionSound hero if fullHero.loaded _.defer onLoaded else @listenToOnce fullHero, 'sync', onLoaded fullHero playSelectionSound: (hero) -> return if @$el.hasClass 'secret' @currentSoundInstance?.stop() return unless sounds = hero.get('soundTriggers')?.selected return unless sound = sounds[Math.floor Math.random() * sounds.length] name = AudioPlayer.nameForSoundReference sound AudioPlayer.preloadSoundReference sound @currentSoundInstance = AudioPlayer.playSound name, 1 @currentSoundInstance buildCodeLanguages: -> $select = @$el.find('#option-code-language') $select.fancySelect().parent().find('.options li').each -> languageName = $(@).text() languageID = $(@).data('value') blurb = $.i18n.t("choose_hero.#{languageID}_blurb") $(@).text("#{languageName} - #{blurb}") onCodeLanguageChanged: (e) -> @codeLanguage = @$el.find('#option-code-language').val() @codeLanguageChanged = true onShown: -> # Called when we switch tabs to this within the modal onHidden: -> # Called when the modal itself is dismissed temporaryHeroInfo = knight: fullName: 'Tharin Thunderfist' weapons: 'Swords - Short Range, No Magic' class: 'Warrior' description: 'Beefcake! Beefcaaake!' status: 'Available' attack: 8 attackFactor: 1.2 health: 8.5 healthFactor: 1.4 speed: 1.5 speedAbsolute: 6 captain: fullName: 'Captain Anya Weston' weapons: 'Swords - Short Range, No Magic' class: 'Warrior' description: 'Don\'t bother me, I\'m winning this fight for you.' status: 'Available' attack: 8 attackFactor: 1.2 health: 8.5 healthFactor: 1.4 speed: 1.5 speedAbsolute: 6 thoktar: fullName: 'Thoktar the Devourer' weapons: 'Wands, Staffs - Long Range, Magic' class: 'Wizard' description: '???' status: 'Locked' attack: 5 attackFactor: 2 health: 4.5 healthFactor: 1.4 speed: 2.5 speedAbsolute: 7 skills: ['summonElemental', 'devour'] equestrian: fullName: 'Rider Reynaldo' weapons: 'Crossbows, Guns - Long Range, No Magic' class: 'Ranger' description: '???' status: 'Locked' attack: 6 attackFactor: 1.4 health: 7 healthFactor: 1.8 speed: 1.5 speedAbsolute: 6 skills: ['hide'] 'potion-master': fullName: 'Master Snake' weapons: 'Wands, Staffs - Long Range, Magic' class: 'Wizard' description: '???' status: 'Locked' attack: 2 attackFactor: 0.833 health: 4 healthFactor: 1.2 speed: 6 speedAbsolute: 11 skills: ['brewPotion'] librarian: fullName: 'Hushbaum' weapons: 'Wands, Staffs - Long Range, Magic' class: 'Wizard' description: '???' status: 'Locked' attack: 3 attackFactor: 1.2 health: 4.5 healthFactor: 1.4 speed: 2.5 speedAbsolute: 7 'robot-walker': fullName: '???' weapons: '???' class: 'Ranger' description: '???' status: 'Locked' attack: 6.5 attackFactor: 1.6 health: 5.5 healthFactor: 1.2 speed: 6 speedAbsolute: 11 skills: ['???', '???', '???'] 'michael-heasell': fullName: '???' weapons: '???' class: 'Ranger' description: '???' status: 'Locked' attack: 4 attackFactor: 0.714 health: 5 healthFactor: 1 speed: 10 speedAbsolute: 16 skills: ['???', '???'] 'ian-elliott': fullName: '???' weapons: 'Swords - Short Range, No Magic' class: 'Warrior' description: '???' status: 'Locked' attack: 9.5 attackFactor: 1.8 health: 6.5 healthFactor: 0.714 speed: 3.5 speedAbsolute: 8 skills: ['trueStrike']
94852
CocoView = require 'views/kinds/CocoView' template = require 'templates/game-menu/choose-hero-view' {me} = require 'lib/auth' ThangType = require 'models/ThangType' CocoCollection = require 'collections/CocoCollection' SpriteBuilder = require 'lib/sprites/SpriteBuilder' AudioPlayer = require 'lib/AudioPlayer' module.exports = class ChooseHeroView extends CocoView id: 'choose-hero-view' className: 'tab-pane' template: template events: 'click #restart-level-confirm-button': -> Backbone.Mediator.publish 'level:restart', {} 'slide.bs.carousel #hero-carousel': 'onHeroChanged' 'change #option-code-language': 'onCodeLanguageChanged' shortcuts: 'left': -> @$el.find('#hero-carousel').carousel('prev') if @heroes.models.length and not @$el.hasClass 'secret' 'right': -> @$el.find('#hero-carousel').carousel('next') if @heroes.models.length and not @$el.hasClass 'secret' constructor: (options) -> super options @heroes = new CocoCollection([], {model: ThangType}) @heroes.url = '/db/thang.type?view=heroes&project=original,name,slug,soundTriggers,featureImage' @supermodel.loadCollection(@heroes, 'heroes') @stages = {} destroy: -> for heroIndex, stage of @stages createjs.Ticker.removeEventListener "tick", stage stage.removeAllChildren() super() getRenderData: (context={}) -> context = super(context) context.heroes = @heroes.models hero.locked = temporaryHeroInfo[hero.get('slug')].status is 'Locked' and not me.earnedHero hero.get('original') for hero in context.heroes context.level = @options.level context.codeLanguages = [ {id: 'python', name: 'Python (Default)'} {id: 'javascript', name: 'JavaScript'} {id: 'coffeescript', name: 'CoffeeScript'} {id: 'clojure', name: 'Clojure (Experimental)'} {id: 'lua', name: 'Lua (Experimental)'} {id: 'io', name: 'Io (Experimental)'} ] context.codeLanguage = @codeLanguage = @options.session.get('codeLanguage') ? me.get('aceConfig')?.language ? 'python' context.heroInfo = temporaryHeroInfo context afterRender: -> super() return unless @supermodel.finished() heroes = @heroes.models @$el.find('.hero-indicator').each -> heroID = $(@).data('hero-id') hero = _.find heroes, (hero) -> hero.get('original') is heroID $(@).find('.hero-avatar').css('background-image', "url(#{hero.getPortraitURL()})").tooltip() _.defer => $(@).addClass 'initialized' @canvasWidth = 313 # @$el.find('canvas').width() # unreliable, whatever @canvasHeight = @$el.find('canvas').height() heroConfig = @options.session.get('heroConfig') ? me.get('heroConfig') ? {} heroIndex = Math.max 0, _.findIndex(heroes, ((hero) -> hero.get('original') is heroConfig.thangType)) @$el.find(".hero-item:nth-child(#{heroIndex + 1}), .hero-indicator:nth-child(#{heroIndex + 1})").addClass('active') @onHeroChanged direction: null, relatedTarget: @$el.find('.hero-item')[heroIndex] @$el.find('.hero-stat').tooltip() @buildCodeLanguages() onHeroChanged: (e) -> direction = e.direction # 'left' or 'right' heroItem = $(e.relatedTarget) hero = _.find @heroes.models, (hero) -> hero.get('original') is heroItem.data('hero-id') return console.error "Couldn't find hero from heroItem:", heroItem unless hero heroIndex = heroItem.index() @$el.find('.hero-indicator').each -> distance = Math.min 3, Math.abs $(@).index() - heroIndex size = 100 - (50 / 3) * distance $(@).css width: size, height: size, top: -(100 - size) / 2 heroInfo = temporaryHeroInfo[hero.get('slug')] locked = heroInfo.status is 'Locked' and not me.earnedHero ThangType.heroes[hero.get('slug')] hero = @loadHero hero, heroIndex @preloadHero heroIndex + 1 @preloadHero heroIndex - 1 @selectedHero = hero unless locked Backbone.Mediator.publish 'level:hero-selection-updated', hero: @selectedHero $('#choose-inventory-button').prop 'disabled', locked getFullHero: (original) -> url = "/db/thang.type/#{original}/version" if fullHero = @supermodel.getModel url return fullHero fullHero = new ThangType() fullHero.setURL url fullHero = (@supermodel.loadModel fullHero, 'thang').model fullHero preloadHero: (heroIndex) -> return unless hero = @heroes.models[heroIndex] @loadHero hero, heroIndex, true loadHero: (hero, heroIndex, preloading=false) -> createjs.Ticker.removeEventListener 'tick', stage for stage in _.values @stages if featureImage = hero.get 'featureImage' $(".hero-item[data-hero-id='#{hero.get('original')}'] canvas").hide() $(".hero-item[data-hero-id='#{hero.get('original')}'] .hero-feature-image").show().find('img').prop('src', '/file/' + featureImage) @playSelectionSound hero unless preloading return hero createjs.Ticker.setFPS 30 # In case we paused it from being inactive somewhere else if stage = @stages[heroIndex] unless preloading _.defer -> createjs.Ticker.addEventListener 'tick', stage # Deferred, otherwise it won't start updating for some reason. @playSelectionSound hero return hero fullHero = @getFullHero hero.get 'original' onLoaded = => return unless canvas = $(".hero-item[data-hero-id='#{fullHero.get('original')}'] canvas") canvas.show().prop width: @canvasWidth, height: @canvasHeight builder = new SpriteBuilder(fullHero) movieClip = builder.buildMovieClip(fullHero.get('actions').attack?.animation ? fullHero.get('actions').idle.animation) movieClip.scaleX = movieClip.scaleY = canvas.prop('height') / 120 # Average hero height is ~110px tall at normal resolution if fullHero.get('name') in ['<NAME>', '<NAME>'] # These are too big, so shrink them. movieClip.scaleX *= 0.7 movieClip.scaleY *= 0.7 movieClip.regX = -fullHero.get('positions').registration.x movieClip.regY = -fullHero.get('positions').registration.y movieClip.x = canvas.prop('width') * 0.5 movieClip.y = canvas.prop('height') * 0.925 # This is where the feet go. stage = new createjs.Stage(canvas[0]) @stages[heroIndex] = stage stage.addChild movieClip stage.update() movieClip.gotoAndPlay 0 unless preloading createjs.Ticker.addEventListener 'tick', stage @playSelectionSound hero if fullHero.loaded _.defer onLoaded else @listenToOnce fullHero, 'sync', onLoaded fullHero playSelectionSound: (hero) -> return if @$el.hasClass 'secret' @currentSoundInstance?.stop() return unless sounds = hero.get('soundTriggers')?.selected return unless sound = sounds[Math.floor Math.random() * sounds.length] name = AudioPlayer.nameForSoundReference sound AudioPlayer.preloadSoundReference sound @currentSoundInstance = AudioPlayer.playSound name, 1 @currentSoundInstance buildCodeLanguages: -> $select = @$el.find('#option-code-language') $select.fancySelect().parent().find('.options li').each -> languageName = $(@).text() languageID = $(@).data('value') blurb = $.i18n.t("choose_hero.#{languageID}_blurb") $(@).text("#{languageName} - #{blurb}") onCodeLanguageChanged: (e) -> @codeLanguage = @$el.find('#option-code-language').val() @codeLanguageChanged = true onShown: -> # Called when we switch tabs to this within the modal onHidden: -> # Called when the modal itself is dismissed temporaryHeroInfo = k<NAME>: fullName: '<NAME>' weapons: 'Swords - Short Range, No Magic' class: 'Warrior' description: 'Beefcake! Beefcaaake!' status: 'Available' attack: 8 attackFactor: 1.2 health: 8.5 healthFactor: 1.4 speed: 1.5 speedAbsolute: 6 captain: fullName: '<NAME>' weapons: 'Swords - Short Range, No Magic' class: 'Warrior' description: 'Don\'t bother me, I\'m winning this fight for you.' status: 'Available' attack: 8 attackFactor: 1.2 health: 8.5 healthFactor: 1.4 speed: 1.5 speedAbsolute: 6 <NAME>: fullName: '<NAME>' weapons: 'Wands, Staffs - Long Range, Magic' class: 'Wizard' description: '???' status: 'Locked' attack: 5 attackFactor: 2 health: 4.5 healthFactor: 1.4 speed: 2.5 speedAbsolute: 7 skills: ['summonElemental', 'devour'] equestrian: fullName: '<NAME>' weapons: 'Crossbows, Guns - Long Range, No Magic' class: 'Ranger' description: '???' status: 'Locked' attack: 6 attackFactor: 1.4 health: 7 healthFactor: 1.8 speed: 1.5 speedAbsolute: 6 skills: ['hide'] 'potion-master': fullName: '<NAME>' weapons: 'Wands, Staffs - Long Range, Magic' class: 'Wizard' description: '???' status: 'Locked' attack: 2 attackFactor: 0.833 health: 4 healthFactor: 1.2 speed: 6 speedAbsolute: 11 skills: ['brewPotion'] librarian: fullName: '<NAME>' weapons: 'Wands, Staffs - Long Range, Magic' class: 'Wizard' description: '???' status: 'Locked' attack: 3 attackFactor: 1.2 health: 4.5 healthFactor: 1.4 speed: 2.5 speedAbsolute: 7 'robot-walker': fullName: '???' weapons: '???' class: 'Ranger' description: '???' status: 'Locked' attack: 6.5 attackFactor: 1.6 health: 5.5 healthFactor: 1.2 speed: 6 speedAbsolute: 11 skills: ['???', '???', '???'] 'michael-heasell': fullName: '???' weapons: '???' class: 'Ranger' description: '???' status: 'Locked' attack: 4 attackFactor: 0.714 health: 5 healthFactor: 1 speed: 10 speedAbsolute: 16 skills: ['???', '???'] 'ian-elliott': fullName: '???' weapons: 'Swords - Short Range, No Magic' class: 'Warrior' description: '???' status: 'Locked' attack: 9.5 attackFactor: 1.8 health: 6.5 healthFactor: 0.714 speed: 3.5 speedAbsolute: 8 skills: ['trueStrike']
true
CocoView = require 'views/kinds/CocoView' template = require 'templates/game-menu/choose-hero-view' {me} = require 'lib/auth' ThangType = require 'models/ThangType' CocoCollection = require 'collections/CocoCollection' SpriteBuilder = require 'lib/sprites/SpriteBuilder' AudioPlayer = require 'lib/AudioPlayer' module.exports = class ChooseHeroView extends CocoView id: 'choose-hero-view' className: 'tab-pane' template: template events: 'click #restart-level-confirm-button': -> Backbone.Mediator.publish 'level:restart', {} 'slide.bs.carousel #hero-carousel': 'onHeroChanged' 'change #option-code-language': 'onCodeLanguageChanged' shortcuts: 'left': -> @$el.find('#hero-carousel').carousel('prev') if @heroes.models.length and not @$el.hasClass 'secret' 'right': -> @$el.find('#hero-carousel').carousel('next') if @heroes.models.length and not @$el.hasClass 'secret' constructor: (options) -> super options @heroes = new CocoCollection([], {model: ThangType}) @heroes.url = '/db/thang.type?view=heroes&project=original,name,slug,soundTriggers,featureImage' @supermodel.loadCollection(@heroes, 'heroes') @stages = {} destroy: -> for heroIndex, stage of @stages createjs.Ticker.removeEventListener "tick", stage stage.removeAllChildren() super() getRenderData: (context={}) -> context = super(context) context.heroes = @heroes.models hero.locked = temporaryHeroInfo[hero.get('slug')].status is 'Locked' and not me.earnedHero hero.get('original') for hero in context.heroes context.level = @options.level context.codeLanguages = [ {id: 'python', name: 'Python (Default)'} {id: 'javascript', name: 'JavaScript'} {id: 'coffeescript', name: 'CoffeeScript'} {id: 'clojure', name: 'Clojure (Experimental)'} {id: 'lua', name: 'Lua (Experimental)'} {id: 'io', name: 'Io (Experimental)'} ] context.codeLanguage = @codeLanguage = @options.session.get('codeLanguage') ? me.get('aceConfig')?.language ? 'python' context.heroInfo = temporaryHeroInfo context afterRender: -> super() return unless @supermodel.finished() heroes = @heroes.models @$el.find('.hero-indicator').each -> heroID = $(@).data('hero-id') hero = _.find heroes, (hero) -> hero.get('original') is heroID $(@).find('.hero-avatar').css('background-image', "url(#{hero.getPortraitURL()})").tooltip() _.defer => $(@).addClass 'initialized' @canvasWidth = 313 # @$el.find('canvas').width() # unreliable, whatever @canvasHeight = @$el.find('canvas').height() heroConfig = @options.session.get('heroConfig') ? me.get('heroConfig') ? {} heroIndex = Math.max 0, _.findIndex(heroes, ((hero) -> hero.get('original') is heroConfig.thangType)) @$el.find(".hero-item:nth-child(#{heroIndex + 1}), .hero-indicator:nth-child(#{heroIndex + 1})").addClass('active') @onHeroChanged direction: null, relatedTarget: @$el.find('.hero-item')[heroIndex] @$el.find('.hero-stat').tooltip() @buildCodeLanguages() onHeroChanged: (e) -> direction = e.direction # 'left' or 'right' heroItem = $(e.relatedTarget) hero = _.find @heroes.models, (hero) -> hero.get('original') is heroItem.data('hero-id') return console.error "Couldn't find hero from heroItem:", heroItem unless hero heroIndex = heroItem.index() @$el.find('.hero-indicator').each -> distance = Math.min 3, Math.abs $(@).index() - heroIndex size = 100 - (50 / 3) * distance $(@).css width: size, height: size, top: -(100 - size) / 2 heroInfo = temporaryHeroInfo[hero.get('slug')] locked = heroInfo.status is 'Locked' and not me.earnedHero ThangType.heroes[hero.get('slug')] hero = @loadHero hero, heroIndex @preloadHero heroIndex + 1 @preloadHero heroIndex - 1 @selectedHero = hero unless locked Backbone.Mediator.publish 'level:hero-selection-updated', hero: @selectedHero $('#choose-inventory-button').prop 'disabled', locked getFullHero: (original) -> url = "/db/thang.type/#{original}/version" if fullHero = @supermodel.getModel url return fullHero fullHero = new ThangType() fullHero.setURL url fullHero = (@supermodel.loadModel fullHero, 'thang').model fullHero preloadHero: (heroIndex) -> return unless hero = @heroes.models[heroIndex] @loadHero hero, heroIndex, true loadHero: (hero, heroIndex, preloading=false) -> createjs.Ticker.removeEventListener 'tick', stage for stage in _.values @stages if featureImage = hero.get 'featureImage' $(".hero-item[data-hero-id='#{hero.get('original')}'] canvas").hide() $(".hero-item[data-hero-id='#{hero.get('original')}'] .hero-feature-image").show().find('img').prop('src', '/file/' + featureImage) @playSelectionSound hero unless preloading return hero createjs.Ticker.setFPS 30 # In case we paused it from being inactive somewhere else if stage = @stages[heroIndex] unless preloading _.defer -> createjs.Ticker.addEventListener 'tick', stage # Deferred, otherwise it won't start updating for some reason. @playSelectionSound hero return hero fullHero = @getFullHero hero.get 'original' onLoaded = => return unless canvas = $(".hero-item[data-hero-id='#{fullHero.get('original')}'] canvas") canvas.show().prop width: @canvasWidth, height: @canvasHeight builder = new SpriteBuilder(fullHero) movieClip = builder.buildMovieClip(fullHero.get('actions').attack?.animation ? fullHero.get('actions').idle.animation) movieClip.scaleX = movieClip.scaleY = canvas.prop('height') / 120 # Average hero height is ~110px tall at normal resolution if fullHero.get('name') in ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] # These are too big, so shrink them. movieClip.scaleX *= 0.7 movieClip.scaleY *= 0.7 movieClip.regX = -fullHero.get('positions').registration.x movieClip.regY = -fullHero.get('positions').registration.y movieClip.x = canvas.prop('width') * 0.5 movieClip.y = canvas.prop('height') * 0.925 # This is where the feet go. stage = new createjs.Stage(canvas[0]) @stages[heroIndex] = stage stage.addChild movieClip stage.update() movieClip.gotoAndPlay 0 unless preloading createjs.Ticker.addEventListener 'tick', stage @playSelectionSound hero if fullHero.loaded _.defer onLoaded else @listenToOnce fullHero, 'sync', onLoaded fullHero playSelectionSound: (hero) -> return if @$el.hasClass 'secret' @currentSoundInstance?.stop() return unless sounds = hero.get('soundTriggers')?.selected return unless sound = sounds[Math.floor Math.random() * sounds.length] name = AudioPlayer.nameForSoundReference sound AudioPlayer.preloadSoundReference sound @currentSoundInstance = AudioPlayer.playSound name, 1 @currentSoundInstance buildCodeLanguages: -> $select = @$el.find('#option-code-language') $select.fancySelect().parent().find('.options li').each -> languageName = $(@).text() languageID = $(@).data('value') blurb = $.i18n.t("choose_hero.#{languageID}_blurb") $(@).text("#{languageName} - #{blurb}") onCodeLanguageChanged: (e) -> @codeLanguage = @$el.find('#option-code-language').val() @codeLanguageChanged = true onShown: -> # Called when we switch tabs to this within the modal onHidden: -> # Called when the modal itself is dismissed temporaryHeroInfo = kPI:NAME:<NAME>END_PI: fullName: 'PI:NAME:<NAME>END_PI' weapons: 'Swords - Short Range, No Magic' class: 'Warrior' description: 'Beefcake! Beefcaaake!' status: 'Available' attack: 8 attackFactor: 1.2 health: 8.5 healthFactor: 1.4 speed: 1.5 speedAbsolute: 6 captain: fullName: 'PI:NAME:<NAME>END_PI' weapons: 'Swords - Short Range, No Magic' class: 'Warrior' description: 'Don\'t bother me, I\'m winning this fight for you.' status: 'Available' attack: 8 attackFactor: 1.2 health: 8.5 healthFactor: 1.4 speed: 1.5 speedAbsolute: 6 PI:NAME:<NAME>END_PI: fullName: 'PI:NAME:<NAME>END_PI' weapons: 'Wands, Staffs - Long Range, Magic' class: 'Wizard' description: '???' status: 'Locked' attack: 5 attackFactor: 2 health: 4.5 healthFactor: 1.4 speed: 2.5 speedAbsolute: 7 skills: ['summonElemental', 'devour'] equestrian: fullName: 'PI:NAME:<NAME>END_PI' weapons: 'Crossbows, Guns - Long Range, No Magic' class: 'Ranger' description: '???' status: 'Locked' attack: 6 attackFactor: 1.4 health: 7 healthFactor: 1.8 speed: 1.5 speedAbsolute: 6 skills: ['hide'] 'potion-master': fullName: 'PI:NAME:<NAME>END_PI' weapons: 'Wands, Staffs - Long Range, Magic' class: 'Wizard' description: '???' status: 'Locked' attack: 2 attackFactor: 0.833 health: 4 healthFactor: 1.2 speed: 6 speedAbsolute: 11 skills: ['brewPotion'] librarian: fullName: 'PI:NAME:<NAME>END_PI' weapons: 'Wands, Staffs - Long Range, Magic' class: 'Wizard' description: '???' status: 'Locked' attack: 3 attackFactor: 1.2 health: 4.5 healthFactor: 1.4 speed: 2.5 speedAbsolute: 7 'robot-walker': fullName: '???' weapons: '???' class: 'Ranger' description: '???' status: 'Locked' attack: 6.5 attackFactor: 1.6 health: 5.5 healthFactor: 1.2 speed: 6 speedAbsolute: 11 skills: ['???', '???', '???'] 'michael-heasell': fullName: '???' weapons: '???' class: 'Ranger' description: '???' status: 'Locked' attack: 4 attackFactor: 0.714 health: 5 healthFactor: 1 speed: 10 speedAbsolute: 16 skills: ['???', '???'] 'ian-elliott': fullName: '???' weapons: 'Swords - Short Range, No Magic' class: 'Warrior' description: '???' status: 'Locked' attack: 9.5 attackFactor: 1.8 health: 6.5 healthFactor: 0.714 speed: 3.5 speedAbsolute: 8 skills: ['trueStrike']
[ { "context": "kenario:'\n 'Conto:'\n 'Contone:'\n 'Nalika '\n 'Nalikaning '\n 'Manawa '\n 'Mena", "end": 179, "score": 0.6487376689910889, "start": 174, "tag": "NAME", "value": "alika" }, { "context": "'Conto:'\n 'Contone:'\n 'Nalika '\n 'Nalikaning '\n 'Manawa '\n 'Menawa '\n 'Njuk ", "end": 196, "score": 0.5790774822235107, "start": 190, "tag": "NAME", "value": "alikan" } ]
settings/language-gherkin_jv.cson
mackoj/language-gherkin-i18n
17
'.text.gherkin.feature.jv': 'editor': 'completions': [ 'Fitur:' 'Dasar:' 'Skenario:' 'Konsep skenario:' 'Conto:' 'Contone:' 'Nalika ' 'Nalikaning ' 'Manawa ' 'Menawa ' 'Njuk ' 'Banjur ' 'Tapi ' 'Nanging ' 'Ananging ' 'Lan ' ] 'increaseIndentPattern': 'Skenario: .*' 'commentStart': '# '
214458
'.text.gherkin.feature.jv': 'editor': 'completions': [ 'Fitur:' 'Dasar:' 'Skenario:' 'Konsep skenario:' 'Conto:' 'Contone:' 'N<NAME> ' 'N<NAME>ing ' 'Manawa ' 'Menawa ' 'Njuk ' 'Banjur ' 'Tapi ' 'Nanging ' 'Ananging ' 'Lan ' ] 'increaseIndentPattern': 'Skenario: .*' 'commentStart': '# '
true
'.text.gherkin.feature.jv': 'editor': 'completions': [ 'Fitur:' 'Dasar:' 'Skenario:' 'Konsep skenario:' 'Conto:' 'Contone:' 'NPI:NAME:<NAME>END_PI ' 'NPI:NAME:<NAME>END_PIing ' 'Manawa ' 'Menawa ' 'Njuk ' 'Banjur ' 'Tapi ' 'Nanging ' 'Ananging ' 'Lan ' ] 'increaseIndentPattern': 'Skenario: .*' 'commentStart': '# '
[ { "context": "Ob =\n username : ''\n phone: ''\n password: ''\n repassword : ''\n checkPolicy : false\n e", "end": 734, "score": 0.6273216009140015, "start": 734, "tag": "PASSWORD", "value": "" }, { "context": "THENTICATED\"\n params =\n password : $scope.register.password\n name : $scope.register.username\n ", "end": 2354, "score": 0.9969437122344971, "start": 2330, "tag": "PASSWORD", "value": "$scope.register.password" }, { "context": " phone : $scope.register.phone\n password : $scope.register.password\n name : $scope.register.username\n console", "end": 3450, "score": 0.9952794909477234, "start": 3426, "tag": "PASSWORD", "value": "$scope.register.password" } ]
app/core/controllers/register.coffee
xitrumuit1991/ls-yuptv
0
"use strict" route = ($stateProvider, GlobalConfig)-> $stateProvider .state "base.register", url : "register" views : "main@" : templateUrl : "/templates/register/view.html" controller : "registerCtrl" route.$inject = ['$stateProvider', 'GlobalConfig'] ctrl = ($rootScope, $scope, $timeout, $location, $window, $state, $stateParams, ApiService, $http, GlobalConfig, $interval, Notification) -> console.log 'register coffee ' rexPhone = /^0[1-9]{1}[0-9]{8,12}$/; rexEmail = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; basicOb = username : '' phone: '' password: '' repassword : '' checkPolicy : false error : '' $scope.register = _.clone basicOb validateRegister = ()-> if $scope.register.username.length < 6 $scope.register.error = 'Tên người dùng ít nhất 6 kí tự ' return false if rexPhone.test($scope.register.phone) is false $scope.register.error = 'Số điện thoại không đúng định dạng ' return false if $scope.register.password.length < 6 $scope.register.error = 'Mật khẩu ít nhất 6 kí tự ' return false if $scope.register.password != $scope.register.repassword $scope.register.error = 'Mật khẩu nhập lại không đúng' return false if $scope.register.checkPolicy == false $scope.register.error = 'Vui lòng đồng ý với các điều khoản sử dụng' return false return true $scope.submitRegisterAccountKit = ()-> if !$scope.register.username or !$scope.register.phone or !$scope.register.password or !$scope.register.repassword $scope.register.error = 'Vui lòng nhập đầy đủ thông tin' return return if validateRegister() == false paramAccountKit = countryCode: '+84', phoneNumber: $scope.register.phone AccountKit.login 'PHONE', paramAccountKit,(response)-> console.log 'AccountKit.login response',response if response and response.status isnt "PARTIALLY_AUTHENTICATED" #if response and response.status in ['NOT_AUTHENTICATED','BAD_PARAMS'] return Notification.error('Không thể gửi OTP code.') if response and response.status is "PARTIALLY_AUTHENTICATED" params = password : $scope.register.password name : $scope.register.username phone : $scope.register.phone params.code = response.code if response.code params.access_token = response.access_token if response.access_token and !params.code ApiService.registerAccountByAccountKit params, (error, result)-> if result and result.error return Notification.error(result.message) console.log 'registerAccountByAccountKit result=',result Notification.success('Đăng kí tài khoản thành công. Bạn có thể đăng nhập ngay bây giờ!') $scope.register = _.clone basicOb $timeout(()-> $rootScope.$emit 'login-from-reset-password', {} $state.go 'base' ,1000) $scope.submitRegister = ()-> if !$scope.register.username or !$scope.register.phone or !$scope.register.password or !$scope.register.repassword $scope.register.error = 'Vui lòng nhập đầy đủ thông tin' return return if validateRegister() == false params = phone : $scope.register.phone password : $scope.register.password name : $scope.register.username console.log 'registerAccount=',params ApiService.registerAccount params, (error, result)-> $scope.register.error='' if error console.error error Notification.error(error) return if result and result.error return Notification.error(result.message) console.log result paramsActive = phone: $scope.register.phone, code : if result.code then result.code.toString() else '' ApiService.registerAccountActive paramsActive,(err, res)-> console.log 'res active code=',res if err return Notification.error(JSON.stringify(err)) if res and res.error return Notification.error(res.message) if res and res.verify == true Notification.success('Đăng kí tài khoản thành công') $scope.register = username : '' phone: '' password: '' repassword : '' checkPolicy : false error : '' $state.go 'base',{reload:true} return ctrl.$inject = [ '$rootScope', '$scope', '$timeout', '$location', '$window', '$state', '$stateParams', 'ApiService', '$http', 'GlobalConfig', '$interval', 'Notification' ] angular .module("app") .config route .controller "registerCtrl", ctrl
153891
"use strict" route = ($stateProvider, GlobalConfig)-> $stateProvider .state "base.register", url : "register" views : "main@" : templateUrl : "/templates/register/view.html" controller : "registerCtrl" route.$inject = ['$stateProvider', 'GlobalConfig'] ctrl = ($rootScope, $scope, $timeout, $location, $window, $state, $stateParams, ApiService, $http, GlobalConfig, $interval, Notification) -> console.log 'register coffee ' rexPhone = /^0[1-9]{1}[0-9]{8,12}$/; rexEmail = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; basicOb = username : '' phone: '' password:<PASSWORD> '' repassword : '' checkPolicy : false error : '' $scope.register = _.clone basicOb validateRegister = ()-> if $scope.register.username.length < 6 $scope.register.error = 'Tên người dùng ít nhất 6 kí tự ' return false if rexPhone.test($scope.register.phone) is false $scope.register.error = 'Số điện thoại không đúng định dạng ' return false if $scope.register.password.length < 6 $scope.register.error = 'Mật khẩu ít nhất 6 kí tự ' return false if $scope.register.password != $scope.register.repassword $scope.register.error = 'Mật khẩu nhập lại không đúng' return false if $scope.register.checkPolicy == false $scope.register.error = 'Vui lòng đồng ý với các điều khoản sử dụng' return false return true $scope.submitRegisterAccountKit = ()-> if !$scope.register.username or !$scope.register.phone or !$scope.register.password or !$scope.register.repassword $scope.register.error = 'Vui lòng nhập đầy đủ thông tin' return return if validateRegister() == false paramAccountKit = countryCode: '+84', phoneNumber: $scope.register.phone AccountKit.login 'PHONE', paramAccountKit,(response)-> console.log 'AccountKit.login response',response if response and response.status isnt "PARTIALLY_AUTHENTICATED" #if response and response.status in ['NOT_AUTHENTICATED','BAD_PARAMS'] return Notification.error('Không thể gửi OTP code.') if response and response.status is "PARTIALLY_AUTHENTICATED" params = password : <PASSWORD> name : $scope.register.username phone : $scope.register.phone params.code = response.code if response.code params.access_token = response.access_token if response.access_token and !params.code ApiService.registerAccountByAccountKit params, (error, result)-> if result and result.error return Notification.error(result.message) console.log 'registerAccountByAccountKit result=',result Notification.success('Đăng kí tài khoản thành công. Bạn có thể đăng nhập ngay bây giờ!') $scope.register = _.clone basicOb $timeout(()-> $rootScope.$emit 'login-from-reset-password', {} $state.go 'base' ,1000) $scope.submitRegister = ()-> if !$scope.register.username or !$scope.register.phone or !$scope.register.password or !$scope.register.repassword $scope.register.error = 'Vui lòng nhập đầy đủ thông tin' return return if validateRegister() == false params = phone : $scope.register.phone password : <PASSWORD> name : $scope.register.username console.log 'registerAccount=',params ApiService.registerAccount params, (error, result)-> $scope.register.error='' if error console.error error Notification.error(error) return if result and result.error return Notification.error(result.message) console.log result paramsActive = phone: $scope.register.phone, code : if result.code then result.code.toString() else '' ApiService.registerAccountActive paramsActive,(err, res)-> console.log 'res active code=',res if err return Notification.error(JSON.stringify(err)) if res and res.error return Notification.error(res.message) if res and res.verify == true Notification.success('Đăng kí tài khoản thành công') $scope.register = username : '' phone: '' password: '' repassword : '' checkPolicy : false error : '' $state.go 'base',{reload:true} return ctrl.$inject = [ '$rootScope', '$scope', '$timeout', '$location', '$window', '$state', '$stateParams', 'ApiService', '$http', 'GlobalConfig', '$interval', 'Notification' ] angular .module("app") .config route .controller "registerCtrl", ctrl
true
"use strict" route = ($stateProvider, GlobalConfig)-> $stateProvider .state "base.register", url : "register" views : "main@" : templateUrl : "/templates/register/view.html" controller : "registerCtrl" route.$inject = ['$stateProvider', 'GlobalConfig'] ctrl = ($rootScope, $scope, $timeout, $location, $window, $state, $stateParams, ApiService, $http, GlobalConfig, $interval, Notification) -> console.log 'register coffee ' rexPhone = /^0[1-9]{1}[0-9]{8,12}$/; rexEmail = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; basicOb = username : '' phone: '' password:PI:PASSWORD:<PASSWORD>END_PI '' repassword : '' checkPolicy : false error : '' $scope.register = _.clone basicOb validateRegister = ()-> if $scope.register.username.length < 6 $scope.register.error = 'Tên người dùng ít nhất 6 kí tự ' return false if rexPhone.test($scope.register.phone) is false $scope.register.error = 'Số điện thoại không đúng định dạng ' return false if $scope.register.password.length < 6 $scope.register.error = 'Mật khẩu ít nhất 6 kí tự ' return false if $scope.register.password != $scope.register.repassword $scope.register.error = 'Mật khẩu nhập lại không đúng' return false if $scope.register.checkPolicy == false $scope.register.error = 'Vui lòng đồng ý với các điều khoản sử dụng' return false return true $scope.submitRegisterAccountKit = ()-> if !$scope.register.username or !$scope.register.phone or !$scope.register.password or !$scope.register.repassword $scope.register.error = 'Vui lòng nhập đầy đủ thông tin' return return if validateRegister() == false paramAccountKit = countryCode: '+84', phoneNumber: $scope.register.phone AccountKit.login 'PHONE', paramAccountKit,(response)-> console.log 'AccountKit.login response',response if response and response.status isnt "PARTIALLY_AUTHENTICATED" #if response and response.status in ['NOT_AUTHENTICATED','BAD_PARAMS'] return Notification.error('Không thể gửi OTP code.') if response and response.status is "PARTIALLY_AUTHENTICATED" params = password : PI:PASSWORD:<PASSWORD>END_PI name : $scope.register.username phone : $scope.register.phone params.code = response.code if response.code params.access_token = response.access_token if response.access_token and !params.code ApiService.registerAccountByAccountKit params, (error, result)-> if result and result.error return Notification.error(result.message) console.log 'registerAccountByAccountKit result=',result Notification.success('Đăng kí tài khoản thành công. Bạn có thể đăng nhập ngay bây giờ!') $scope.register = _.clone basicOb $timeout(()-> $rootScope.$emit 'login-from-reset-password', {} $state.go 'base' ,1000) $scope.submitRegister = ()-> if !$scope.register.username or !$scope.register.phone or !$scope.register.password or !$scope.register.repassword $scope.register.error = 'Vui lòng nhập đầy đủ thông tin' return return if validateRegister() == false params = phone : $scope.register.phone password : PI:PASSWORD:<PASSWORD>END_PI name : $scope.register.username console.log 'registerAccount=',params ApiService.registerAccount params, (error, result)-> $scope.register.error='' if error console.error error Notification.error(error) return if result and result.error return Notification.error(result.message) console.log result paramsActive = phone: $scope.register.phone, code : if result.code then result.code.toString() else '' ApiService.registerAccountActive paramsActive,(err, res)-> console.log 'res active code=',res if err return Notification.error(JSON.stringify(err)) if res and res.error return Notification.error(res.message) if res and res.verify == true Notification.success('Đăng kí tài khoản thành công') $scope.register = username : '' phone: '' password: '' repassword : '' checkPolicy : false error : '' $state.go 'base',{reload:true} return ctrl.$inject = [ '$rootScope', '$scope', '$timeout', '$location', '$window', '$state', '$stateParams', 'ApiService', '$http', 'GlobalConfig', '$interval', 'Notification' ] angular .module("app") .config route .controller "registerCtrl", ctrl
[ { "context": " s = [ 'The Matrix – The Wachowskis',\n '© Martin Dedek, Graficky design 2, FUD UJEP',\n \"n#{n}/m", "end": 4333, "score": 0.9998865127563477, "start": 4321, "tag": "NAME", "value": "Martin Dedek" } ]
src/poster.coffee
dedekm/terry-poster
0
window.init = () -> canvas = document.createElement('canvas') canvas.width = WIDTH canvas.height = HEIGHT document.body.appendChild(canvas) ctx = canvas.getContext("2d") strings = $('#input input').map((iput) -> this.value ).get() ctx.font = "25px Arial" ctx.fillStyle = "#000000" ctx.textAlign="center" for s, i in strings ctx.fillText(s.split("").join(String.fromCharCode(8202)), WIDTH/2, 40 + i* 25) pixelGrid = new PixelGrid(ctx) document.body.removeChild(canvas) $('#input').remove() scene = new THREE.Scene() camera = new THREE.PerspectiveCamera( 60, WIDTH / HEIGHT, 63, 105.5 ) scene = new THREE.Scene() renderer = new THREE.WebGLRenderer( ) renderer.setSize( WIDTH * 12, HEIGHT * 12 ) # document.body.appendChild( renderer.domElement ) renderer.setClearColor(0x000000) grid = new Grid(WIDTH, HEIGHT, DEPTH) camera.position.set( WIDTH/2, HEIGHT/2 + 2, 105 ) class Tube constructor: (@x, @y, @z) -> @x ?= Math.round(Math.random() * WIDTH) @y ?= Math.round(Math.random() * HEIGHT) @z ?= 0 grid.setNode(@x,@y,@z, true) @path = [this.actualPosition()] actualPosition: () -> new THREE.Vector3(@x, @y, @z) possible_directions: () -> preferable = [ 'right' if pixelGrid.getPixel(@x + 1, @y) > 0, 'up' if pixelGrid.getPixel(@x,@y + 1) > 0, 'forward' if pixelGrid.getPixel(@x, @y) > 0, 'left' if pixelGrid.getPixel(@x - 1,@y) > 0, 'down' if pixelGrid.getPixel(@x,@y - 1) > 0 # 'backward' if pixelGrid.getPixel(@x, @y) > 0 and @z >= DEPTH - 1 ].filter(Boolean) preferable = ['forward'] if pixelGrid.getPixel(@x, @y) > 0 && @z < DEPTH - DEPTH/2 preferable = ['backward'] if pixelGrid.getPixel(@x, @y) == 0 && @z > DEPTH / 3 directions = [ 'right' unless grid.getNode(@x + 1, @y, @z), 'up' unless grid.getNode(@x, @y + 1, @z), 'forward' if not grid.getNode(@x, @y, @z + 1) and ((@z < DEPTH / 2 and pixelGrid.getPixel(@x, @y) == 0) or (pixelGrid.getPixel(@x, @y) > 0)), 'left' unless grid.getNode(@x - 1, @y, @z), 'down' unless grid.getNode(@x, @y - 1, @z), 'backward' unless grid.getNode(@x, @y, @z - 1) ].filter(Boolean) preferable_directions = (direction for direction in directions when direction in preferable) if preferable_directions.length > 0 preferable_directions else directions move: (direction) -> pd = this.possible_directions() if pd.length > 0 direction ?= pd[Math.floor(Math.random()*pd.length)] switch direction when 'right' @x++ when 'up' @y++ when 'forward' @z++ when 'left' @x-- when 'down' @y-- when 'backward' @z-- grid.setNode(@x,@y,@z, true) @path.push(this.actualPosition()) # else # console.log 'cant move' createTube: () -> curve = new THREE.SplineCurve3(@path) geometry = new THREE.TubeGeometry( curve, #path @path.length * 3, #segments 0.45, #radius 8, #radiusSegments false #closed ) # tube = new THREE.Mesh( geometry, MATERIAL ) # scene.add(grid.helpGrid(pixelGrid.pixels)) n = 5 tubes = [] for x in [0...WIDTH/n] for y in [0...HEIGHT/n] unless grid.getNode(x* n,y * n,1) == 'full' tubes.push new Tube(x * n,y * n,1) moves = 25 for [0..moves] for tube in tubes tube.move() # tubes = [new Tube(55, 55,0)] # for [0..20] # tubes[0].move() # console.log 'z = ' + tubes[0].z # console.log String(tubes[0].possible_directions()) # console.log '----' group = new THREE.Geometry() for tube in tubes group.merge(tube.createTube()) bufferGeometry = new THREE.BufferGeometry().fromGeometry( group ) mesh = new THREE.Mesh( bufferGeometry, MATERIAL ) scene.add(mesh) renderPDF= () -> dataURL = renderer.domElement.toDataURL() doc = new jsPDF('p', 'mm', 'b1-poster') doc.addImage(dataURL, 'PNG', 8, 8, 708, 1008) doc.setFont("monospace", "bold") doc.setFontSize(8) doc.setTextColor(160,160,160) s = [ 'The Matrix – The Wachowskis', '© Martin Dedek, Graficky design 2, FUD UJEP', "n#{n}/m#{moves}", 'poster generated by software licensed under the MIT licence', 'dedekm.github.io/terry-poster', new Date().toUTCString() + ' for Terry posters' ] for string, i in s doc.text("#{new Date().getTime()} ~ #{string}", 22, 1000 - (s.length-1) * 4 + i * 4) for i in [{c: 255, w: 1.5}, {c: 0, w: 0.5}] doc.setDrawColor(i.c,i.c,i.c) doc.setLineWidth(i.w) doc.line(12, 0, 12, 9) doc.line(0, 12, 9, 12) doc.line(712, 0, 712, 9) doc.line(715, 12, 724, 12) doc.line(712, 1015, 712, 1024) doc.line(715, 1012, 724, 1012) doc.line(0, 1012, 9, 1012) doc.line(12, 1015, 12, 1024) doc.save('poster.pdf') # doc.output('dataurlstring', 'Test.pdf') render = () -> renderer.render( scene, camera ) appendChild() renderPDF() appendChild = () -> imgData = renderer.domElement.toDataURL() imgNode = document.createElement("img") imgNode.src = imgData document.body.appendChild(imgNode) render()
224634
window.init = () -> canvas = document.createElement('canvas') canvas.width = WIDTH canvas.height = HEIGHT document.body.appendChild(canvas) ctx = canvas.getContext("2d") strings = $('#input input').map((iput) -> this.value ).get() ctx.font = "25px Arial" ctx.fillStyle = "#000000" ctx.textAlign="center" for s, i in strings ctx.fillText(s.split("").join(String.fromCharCode(8202)), WIDTH/2, 40 + i* 25) pixelGrid = new PixelGrid(ctx) document.body.removeChild(canvas) $('#input').remove() scene = new THREE.Scene() camera = new THREE.PerspectiveCamera( 60, WIDTH / HEIGHT, 63, 105.5 ) scene = new THREE.Scene() renderer = new THREE.WebGLRenderer( ) renderer.setSize( WIDTH * 12, HEIGHT * 12 ) # document.body.appendChild( renderer.domElement ) renderer.setClearColor(0x000000) grid = new Grid(WIDTH, HEIGHT, DEPTH) camera.position.set( WIDTH/2, HEIGHT/2 + 2, 105 ) class Tube constructor: (@x, @y, @z) -> @x ?= Math.round(Math.random() * WIDTH) @y ?= Math.round(Math.random() * HEIGHT) @z ?= 0 grid.setNode(@x,@y,@z, true) @path = [this.actualPosition()] actualPosition: () -> new THREE.Vector3(@x, @y, @z) possible_directions: () -> preferable = [ 'right' if pixelGrid.getPixel(@x + 1, @y) > 0, 'up' if pixelGrid.getPixel(@x,@y + 1) > 0, 'forward' if pixelGrid.getPixel(@x, @y) > 0, 'left' if pixelGrid.getPixel(@x - 1,@y) > 0, 'down' if pixelGrid.getPixel(@x,@y - 1) > 0 # 'backward' if pixelGrid.getPixel(@x, @y) > 0 and @z >= DEPTH - 1 ].filter(Boolean) preferable = ['forward'] if pixelGrid.getPixel(@x, @y) > 0 && @z < DEPTH - DEPTH/2 preferable = ['backward'] if pixelGrid.getPixel(@x, @y) == 0 && @z > DEPTH / 3 directions = [ 'right' unless grid.getNode(@x + 1, @y, @z), 'up' unless grid.getNode(@x, @y + 1, @z), 'forward' if not grid.getNode(@x, @y, @z + 1) and ((@z < DEPTH / 2 and pixelGrid.getPixel(@x, @y) == 0) or (pixelGrid.getPixel(@x, @y) > 0)), 'left' unless grid.getNode(@x - 1, @y, @z), 'down' unless grid.getNode(@x, @y - 1, @z), 'backward' unless grid.getNode(@x, @y, @z - 1) ].filter(Boolean) preferable_directions = (direction for direction in directions when direction in preferable) if preferable_directions.length > 0 preferable_directions else directions move: (direction) -> pd = this.possible_directions() if pd.length > 0 direction ?= pd[Math.floor(Math.random()*pd.length)] switch direction when 'right' @x++ when 'up' @y++ when 'forward' @z++ when 'left' @x-- when 'down' @y-- when 'backward' @z-- grid.setNode(@x,@y,@z, true) @path.push(this.actualPosition()) # else # console.log 'cant move' createTube: () -> curve = new THREE.SplineCurve3(@path) geometry = new THREE.TubeGeometry( curve, #path @path.length * 3, #segments 0.45, #radius 8, #radiusSegments false #closed ) # tube = new THREE.Mesh( geometry, MATERIAL ) # scene.add(grid.helpGrid(pixelGrid.pixels)) n = 5 tubes = [] for x in [0...WIDTH/n] for y in [0...HEIGHT/n] unless grid.getNode(x* n,y * n,1) == 'full' tubes.push new Tube(x * n,y * n,1) moves = 25 for [0..moves] for tube in tubes tube.move() # tubes = [new Tube(55, 55,0)] # for [0..20] # tubes[0].move() # console.log 'z = ' + tubes[0].z # console.log String(tubes[0].possible_directions()) # console.log '----' group = new THREE.Geometry() for tube in tubes group.merge(tube.createTube()) bufferGeometry = new THREE.BufferGeometry().fromGeometry( group ) mesh = new THREE.Mesh( bufferGeometry, MATERIAL ) scene.add(mesh) renderPDF= () -> dataURL = renderer.domElement.toDataURL() doc = new jsPDF('p', 'mm', 'b1-poster') doc.addImage(dataURL, 'PNG', 8, 8, 708, 1008) doc.setFont("monospace", "bold") doc.setFontSize(8) doc.setTextColor(160,160,160) s = [ 'The Matrix – The Wachowskis', '© <NAME>, Graficky design 2, FUD UJEP', "n#{n}/m#{moves}", 'poster generated by software licensed under the MIT licence', 'dedekm.github.io/terry-poster', new Date().toUTCString() + ' for Terry posters' ] for string, i in s doc.text("#{new Date().getTime()} ~ #{string}", 22, 1000 - (s.length-1) * 4 + i * 4) for i in [{c: 255, w: 1.5}, {c: 0, w: 0.5}] doc.setDrawColor(i.c,i.c,i.c) doc.setLineWidth(i.w) doc.line(12, 0, 12, 9) doc.line(0, 12, 9, 12) doc.line(712, 0, 712, 9) doc.line(715, 12, 724, 12) doc.line(712, 1015, 712, 1024) doc.line(715, 1012, 724, 1012) doc.line(0, 1012, 9, 1012) doc.line(12, 1015, 12, 1024) doc.save('poster.pdf') # doc.output('dataurlstring', 'Test.pdf') render = () -> renderer.render( scene, camera ) appendChild() renderPDF() appendChild = () -> imgData = renderer.domElement.toDataURL() imgNode = document.createElement("img") imgNode.src = imgData document.body.appendChild(imgNode) render()
true
window.init = () -> canvas = document.createElement('canvas') canvas.width = WIDTH canvas.height = HEIGHT document.body.appendChild(canvas) ctx = canvas.getContext("2d") strings = $('#input input').map((iput) -> this.value ).get() ctx.font = "25px Arial" ctx.fillStyle = "#000000" ctx.textAlign="center" for s, i in strings ctx.fillText(s.split("").join(String.fromCharCode(8202)), WIDTH/2, 40 + i* 25) pixelGrid = new PixelGrid(ctx) document.body.removeChild(canvas) $('#input').remove() scene = new THREE.Scene() camera = new THREE.PerspectiveCamera( 60, WIDTH / HEIGHT, 63, 105.5 ) scene = new THREE.Scene() renderer = new THREE.WebGLRenderer( ) renderer.setSize( WIDTH * 12, HEIGHT * 12 ) # document.body.appendChild( renderer.domElement ) renderer.setClearColor(0x000000) grid = new Grid(WIDTH, HEIGHT, DEPTH) camera.position.set( WIDTH/2, HEIGHT/2 + 2, 105 ) class Tube constructor: (@x, @y, @z) -> @x ?= Math.round(Math.random() * WIDTH) @y ?= Math.round(Math.random() * HEIGHT) @z ?= 0 grid.setNode(@x,@y,@z, true) @path = [this.actualPosition()] actualPosition: () -> new THREE.Vector3(@x, @y, @z) possible_directions: () -> preferable = [ 'right' if pixelGrid.getPixel(@x + 1, @y) > 0, 'up' if pixelGrid.getPixel(@x,@y + 1) > 0, 'forward' if pixelGrid.getPixel(@x, @y) > 0, 'left' if pixelGrid.getPixel(@x - 1,@y) > 0, 'down' if pixelGrid.getPixel(@x,@y - 1) > 0 # 'backward' if pixelGrid.getPixel(@x, @y) > 0 and @z >= DEPTH - 1 ].filter(Boolean) preferable = ['forward'] if pixelGrid.getPixel(@x, @y) > 0 && @z < DEPTH - DEPTH/2 preferable = ['backward'] if pixelGrid.getPixel(@x, @y) == 0 && @z > DEPTH / 3 directions = [ 'right' unless grid.getNode(@x + 1, @y, @z), 'up' unless grid.getNode(@x, @y + 1, @z), 'forward' if not grid.getNode(@x, @y, @z + 1) and ((@z < DEPTH / 2 and pixelGrid.getPixel(@x, @y) == 0) or (pixelGrid.getPixel(@x, @y) > 0)), 'left' unless grid.getNode(@x - 1, @y, @z), 'down' unless grid.getNode(@x, @y - 1, @z), 'backward' unless grid.getNode(@x, @y, @z - 1) ].filter(Boolean) preferable_directions = (direction for direction in directions when direction in preferable) if preferable_directions.length > 0 preferable_directions else directions move: (direction) -> pd = this.possible_directions() if pd.length > 0 direction ?= pd[Math.floor(Math.random()*pd.length)] switch direction when 'right' @x++ when 'up' @y++ when 'forward' @z++ when 'left' @x-- when 'down' @y-- when 'backward' @z-- grid.setNode(@x,@y,@z, true) @path.push(this.actualPosition()) # else # console.log 'cant move' createTube: () -> curve = new THREE.SplineCurve3(@path) geometry = new THREE.TubeGeometry( curve, #path @path.length * 3, #segments 0.45, #radius 8, #radiusSegments false #closed ) # tube = new THREE.Mesh( geometry, MATERIAL ) # scene.add(grid.helpGrid(pixelGrid.pixels)) n = 5 tubes = [] for x in [0...WIDTH/n] for y in [0...HEIGHT/n] unless grid.getNode(x* n,y * n,1) == 'full' tubes.push new Tube(x * n,y * n,1) moves = 25 for [0..moves] for tube in tubes tube.move() # tubes = [new Tube(55, 55,0)] # for [0..20] # tubes[0].move() # console.log 'z = ' + tubes[0].z # console.log String(tubes[0].possible_directions()) # console.log '----' group = new THREE.Geometry() for tube in tubes group.merge(tube.createTube()) bufferGeometry = new THREE.BufferGeometry().fromGeometry( group ) mesh = new THREE.Mesh( bufferGeometry, MATERIAL ) scene.add(mesh) renderPDF= () -> dataURL = renderer.domElement.toDataURL() doc = new jsPDF('p', 'mm', 'b1-poster') doc.addImage(dataURL, 'PNG', 8, 8, 708, 1008) doc.setFont("monospace", "bold") doc.setFontSize(8) doc.setTextColor(160,160,160) s = [ 'The Matrix – The Wachowskis', '© PI:NAME:<NAME>END_PI, Graficky design 2, FUD UJEP', "n#{n}/m#{moves}", 'poster generated by software licensed under the MIT licence', 'dedekm.github.io/terry-poster', new Date().toUTCString() + ' for Terry posters' ] for string, i in s doc.text("#{new Date().getTime()} ~ #{string}", 22, 1000 - (s.length-1) * 4 + i * 4) for i in [{c: 255, w: 1.5}, {c: 0, w: 0.5}] doc.setDrawColor(i.c,i.c,i.c) doc.setLineWidth(i.w) doc.line(12, 0, 12, 9) doc.line(0, 12, 9, 12) doc.line(712, 0, 712, 9) doc.line(715, 12, 724, 12) doc.line(712, 1015, 712, 1024) doc.line(715, 1012, 724, 1012) doc.line(0, 1012, 9, 1012) doc.line(12, 1015, 12, 1024) doc.save('poster.pdf') # doc.output('dataurlstring', 'Test.pdf') render = () -> renderer.render( scene, camera ) appendChild() renderPDF() appendChild = () -> imgData = renderer.domElement.toDataURL() imgNode = document.createElement("img") imgNode.src = imgData document.body.appendChild(imgNode) render()
[ { "context": "spre\"\n contact: \"Contact\"\n twitter_follow: \"Urmărește\"\n employers: \"Angajați\"\n\n versions:\n save_", "end": 754, "score": 0.998232364654541, "start": 745, "tag": "USERNAME", "value": "Urmărește" }, { "context": "unt_title: \"Recuperează Cont\"\n send_password: \"Trimite parolă de recuperare\"\n\n signup:\n create_account_title: \"Crează con", "end": 1263, "score": 0.9991551637649536, "start": 1235, "tag": "PASSWORD", "value": "Trimite parolă de recuperare" }, { "context": "Poză\"\n wizard_tab: \"Wizard\"\n password_tab: \"Parolă\"\n emails_tab: \"Email-uri\"\n admin: \"Admin\"\n ", "end": 4736, "score": 0.9003582000732422, "start": 4730, "tag": "PASSWORD", "value": "Parolă" }, { "context": " \"Culoare haine pentru Wizard\"\n new_password: \"Parolă nouă\"\n new_password_verify: \"Verifică\"\n email_su", "end": 5153, "score": 0.9992478489875793, "start": 5142, "tag": "PASSWORD", "value": "Parolă nouă" }, { "context": "password: \"Parolă nouă\"\n new_password_verify: \"Verifică\"\n email_subscriptions: \"Subscripție Email\"\n ", "end": 5189, "score": 0.9991991519927979, "start": 5181, "tag": "PASSWORD", "value": "Verifică" }, { "context": "ved: \"Modificări salvate\"\n password_mismatch: \"Parola nu se potrivește.\"\n\n account_profile:\n edit_settings: \"Modifică ", "end": 5858, "score": 0.9947015047073364, "start": 5835, "tag": "PASSWORD", "value": "Parola nu se potrivește" }, { "context": "ază Articol\"\n\n general:\n and: \"și\"\n name: \"Nume\"\n body: \"Corp\"\n version: \"Versiune\"\n com", "end": 12414, "score": 0.8496316075325012, "start": 12410, "tag": "NAME", "value": "Nume" }, { "context": "eneral:\n and: \"și\"\n name: \"Nume\"\n body: \"Corp\"\n version: \"Versiune\"\n commit_msg: \"Înregis", "end": 12431, "score": 0.645362377166748, "start": 12427, "tag": "NAME", "value": "Corp" }, { "context": "\"\n or: \"sau\"\n email: \"Email\"\n password: \"Parolă\"\n message: \"Mesaj\"\n code: \"Cod\"\n ladder:", "end": 12704, "score": 0.9991790652275085, "start": 12698, "tag": "PASSWORD", "value": "Parolă" }, { "context": "\"\n why_paragraph_1: \"Când am dezolvat Skritter, George nu știa cum să programeze și era mereu frustat de", "end": 13408, "score": 0.9867684245109558, "start": 13402, "tag": "NAME", "value": "George" }, { "context": "hitect, kitchen wizard, și maestru al finanțelor. Scott este cel rezonabil.\"\n nick_description: \"P", "end": 15007, "score": 0.5808663964271545, "start": 15006, "tag": "NAME", "value": "S" }, { "context": "ommunity organizer; probabil ca ați vorbit deja cu Jeremy.\"\n michael_description: \"Programmer, sys-admin", "end": 15321, "score": 0.5296338200569153, "start": 15315, "tag": "NAME", "value": "Jeremy" }, { "context": "er, sys-admin, and undergrad technical wunderkind, Michael este cel care ține serverele in picioare.\"\n\n leg", "end": 15416, "score": 0.9976251125335693, "start": 15409, "tag": "NAME", "value": "Michael" }, { "context": "erea noastră!\"\n introduction_desc_signature: \"- Nick, George, Scott, Michael, și Jeremy\"\n alert_acc", "end": 22567, "score": 0.9997778534889221, "start": 22563, "tag": "NAME", "value": "Nick" }, { "context": "oastră!\"\n introduction_desc_signature: \"- Nick, George, Scott, Michael, și Jeremy\"\n alert_account_mes", "end": 22575, "score": 0.9582732915878296, "start": 22569, "tag": "NAME", "value": "George" }, { "context": "\n introduction_desc_signature: \"- Nick, George, Scott, Michael, și Jeremy\"\n alert_account_message_in", "end": 22582, "score": 0.9986484050750732, "start": 22577, "tag": "NAME", "value": "Scott" }, { "context": "troduction_desc_signature: \"- Nick, George, Scott, Michael, și Jeremy\"\n alert_account_message_intro: \"Sal", "end": 22591, "score": 0.9951342940330505, "start": 22584, "tag": "NAME", "value": "Michael" }, { "context": "esc_signature: \"- Nick, George, Scott, Michael, și Jeremy\"\n alert_account_message_intro: \"Salutare!\"\n ", "end": 22602, "score": 0.9993791580200195, "start": 22596, "tag": "NAME", "value": "Jeremy" } ]
app/locale/ro.coffee
JeremyGeros/codecombat
0
module.exports = nativeDescription: "limba română", englishDescription: "Romanian", translation: common: loading: "Se incarcă..." saving: "Se salvează..." sending: "Se trimite..." cancel: "Anulează" save: "Salvează" delay_1_sec: "1 secundă" delay_3_sec: "3 secunde" delay_5_sec: "5 secunde" manual: "Manual" fork: "Fork" play: "Joaca" modal: close: "Inchide" okay: "Okay" not_found: page_not_found: "Pagina nu a fost gasită" nav: play: "Nivele" editor: "Editor" blog: "Blog" forum: "Forum" admin: "Admin" home: "Acasa" contribute: "Contribuie" legal: "Confidențialitate și termeni" about: "Despre" contact: "Contact" twitter_follow: "Urmărește" employers: "Angajați" versions: save_version_title: "Salvează noua versiune" new_major_version: "Versiune nouă majoră" cla_prefix: "Pentru a salva modificările mai intâi trebuie sa fiți de acord cu" cla_url: "CLA" cla_suffix: "." cla_agree: "SUNT DE ACORD" login: sign_up: "Crează cont" log_in: "Log In" log_out: "Log Out" recover: "recuperează cont" recover: recover_account_title: "Recuperează Cont" send_password: "Trimite parolă de recuperare" signup: create_account_title: "Crează cont pentru a salva progresul" description: "Este gratis. Doar un scurt formular inainte si poți continua:" email_announcements: "Primește notificări prin emaill" coppa: "13+ sau non-USA " coppa_why: "(De ce?)" creating: "Se crează contul..." sign_up: "Înscrie-te" log_in: "loghează-te cu parola" home: slogan: "Învață sa scri JavaScript jucându-te" no_ie: "CodeCombat nu merge pe Internet Explorer 9 sau mai vechi. Scuze!" no_mobile: "CodeCombat nu a fost proiectat pentru dispozitive mobile si s-ar putea sa nu meargâ!" play: "Joacâ" # old_browser: "Uh oh, your browser is too old to run CodeCombat. Sorry!" # old_browser_suffix: "You can try anyway, but it probably won't work." # campaign: "Campaign" # for_beginners: "For Beginners" # multiplayer: "Multiplayer" # for_developers: "For Developers" play: choose_your_level: "Alege nivelul" adventurer_prefix: "Poți să sari la orice nivel de mai jos" adventurer_forum: "forumul Aventurierului" adventurer_suffix: "." campaign_beginner: "Campanie pentru Începători" campaign_beginner_description: "... în care se învață tainele programării." campaign_dev: "Nivele aleatoare mai grele" campaign_dev_description: "... în care se învață interfața, cu o dificultate puțin mai mare." campaign_multiplayer: "Arene Multiplayer" campaign_multiplayer_description: "... în care te lupți cap-la-cap contra alti jucători." campaign_player_created: "Create de jucători" campaign_player_created_description: "... în care ai ocazia să testezi creativitatea colegilor tai <a href=\"/contribute#artisan\">Artisan Wizards</a>." level_difficulty: "Dificultate: " play_as: "Alege-ți echipa" # spectate: "Spectate" contact: contact_us: "Contact CodeCombat" welcome: "Folosiți acest formular pentru a ne trimite email. " contribute_prefix: "Dacă sunteți interesați in a contribui uitați-vă pe " contribute_page: "pagina de contribuție" contribute_suffix: "!" forum_prefix: "Pentru orice altceva vă rugăm sa incercați " forum_page: "forumul nostru" forum_suffix: " în schimb." send: "Trimite Feedback" diplomat_suggestion: title: "Ajută-ne să traducem CodeCombat!" sub_heading: "Avem nevoie de abilitățile tale lingvistice." pitch_body: "CodeCombat este dezvoltat in limba engleza , dar deja avem jucatări din toate colțurile lumii.Mulți dintre ei vor să joace in română și nu vorbesc engleză.Dacă poți vorbi ambele te rugăm să te gândești dacă ai dori să devi un Diplomat și să ne ajuți sa traducem atât jocul cât și site-ul." missing_translations: "Until we can translate everything into Romanian, you'll see English when Romanian isn't available." learn_more: "Află mai multe despre cum să fi un Diplomat" subscribe_as_diplomat: "Înscrie-te ca Diplomat" wizard_settings: title: "Setări Wizard" customize_avatar: "Personalizează-ți Avatarul" clothes: "Haine" trim: "Margine" cloud: "Nor" spell: "Vrajă" boots: "Încălțăminte" hue: "Culoare" saturation: "Saturație" lightness: "Luminozitate" account_settings: title: "Setări Cont" not_logged_in: "Loghează-te sau crează un cont nou pentru a schimba setările." autosave: "Modificările se salvează automat" me_tab: "Eu" picture_tab: "Poză" wizard_tab: "Wizard" password_tab: "Parolă" emails_tab: "Email-uri" admin: "Admin" gravatar_select: "Selectează ce poză Gravatar vrei să foloșesti" gravatar_add_photos: "Adaugă thumbnails și poze la un cont Gravatar pentru email-ul tău pentru a alege o imagine." gravatar_add_more_photos: "Adaugă mai multe poze la contul tău Gravatar pentru a le accesa aici." wizard_color: "Culoare haine pentru Wizard" new_password: "Parolă nouă" new_password_verify: "Verifică" email_subscriptions: "Subscripție Email" email_announcements: "Anunțuri" email_notifications: "Notificări" email_notifications_description: "Primește notificări periodic pentru contul tău." email_announcements_description: "Primește email-uri cu ultimele știri despre CodeCombat." contributor_emails: "Contributor Class Emails" contribute_prefix: "Căutăm oameni să se alăture distracției! Intră pe " contribute_page: "pagina de contribuție" contribute_suffix: " pentru a afla mai multe." email_toggle: "Alege tot" error_saving: "Salvare erori" saved: "Modificări salvate" password_mismatch: "Parola nu se potrivește." account_profile: edit_settings: "Modifică setările" profile_for_prefix: "Profil pentru " profile_for_suffix: "" profile: "Profil" user_not_found: "Utilizator negăsit. Verifică URL-ul??" gravatar_not_found_mine: "N-am putut găsi profilul asociat cu:" gravatar_not_found_email_suffix: "." gravatar_signup_prefix: "Înscrie-te la " gravatar_signup_suffix: " pentru a fi gata!" gravatar_not_found_other: "Din păcate nu este asociat nici un profil cu această adresă de email." gravatar_contact: "Contact" gravatar_websites: "Website-uri" gravatar_accounts: "Așa cum apare la" gravatar_profile_link: "Full Gravatar Profile" play_level: level_load_error: "Nivelul nu a putut fi încărcat: " done: "Gata" grid: "Grilă" customize_wizard: "Personalizează Wizard-ul" home: "Acasă" guide: "Ghid" multiplayer: "Multiplayer" restart: "Restart" goals: "Obiective" action_timeline: "Timeline-ul acțiunii" click_to_select: "Apasă pe o unitate pentru a o selecta." reload_title: "Reîncarcă tot Codul?" reload_really: "Ești sigur că vrei să reîncarci nivelul de la început?" reload_confirm: "Reload All" victory_title_prefix: "" victory_title_suffix: " Terminat" victory_sign_up: "Înscrie-te pentru a salva progresul" victory_sign_up_poke: "Vrei să-ți salvezi codul? Crează un cont gratis!" victory_rate_the_level: "Apreciază nivelul: " victory_rank_my_game: "Plasează-mi jocul in clasament" victory_ranking_game: "Se trimite..." victory_return_to_ladder: "Înapoi la jocurile de clasament" victory_play_next_level: "Joacă nivelul următor" victory_go_home: "Acasă" victory_review: "Spune-ne mai multe!" victory_hour_of_code_done: "Ai terminat?" victory_hour_of_code_done_yes: "Da, am terminat Hour of Code™!" multiplayer_title: "Setări Multiplayer" multiplayer_link_description: "Împărtășește acest link cu cei care vor să ți se alăture." multiplayer_hint_label: "Hint:" multiplayer_hint: " Apasă pe link pentru a selecta tot, apoi apasă ⌘-C sau Ctrl-C pentru a copia link-ul." multiplayer_coming_soon: "Mai multe feature-uri multiplayer în curând!" guide_title: "Ghid" tome_minion_spells: "Vrăjile Minion-ilor tăi" tome_read_only_spells: "Vrăji Read-Only" tome_other_units: "Alte unități" tome_cast_button_castable: "Aplică Vraja" tome_cast_button_casting: "Se încarcă" tome_cast_button_cast: "Aplică Vraja" tome_autocast_delay: "Întârziere Autocast" tome_select_spell: "Alege o vrajă" tome_select_a_thang: "Alege pe cineva pentru " tome_available_spells: "Vrăjile disponibile" hud_continue: "Continuă (apasă shift-space)" spell_saved: "Vrajă salvată" skip_tutorial: "Sari peste (esc)" # editor_config: "Editor Config" # editor_config_title: "Editor Configuration" # editor_config_keybindings_label: "Key Bindings" # editor_config_keybindings_default: "Default (Ace)" # editor_config_keybindings_description: "Adds additional shortcuts known from the common editors." # editor_config_invisibles_label: "Show Invisibles" # editor_config_invisibles_description: "Displays invisibles such as spaces or tabs." # editor_config_indentguides_label: "Show Indent Guides" # editor_config_indentguides_description: "Displays vertical lines to see indentation better." # editor_config_behaviors_label: "Smart Behaviors" # editor_config_behaviors_description: "Autocompletes brackets, braces, and quotes." admin: av_title: "Admin vede" av_entities_sub_title: "Entități" av_entities_users_url: "Utilizatori" av_entities_active_instances_url: "Instanțe active" av_other_sub_title: "Altele" av_other_debug_base_url: "Base (pentru debugging base.jade)" u_title: "Listă utilizatori" lg_title: "Ultimele jocuri" editor: main_title: "Editori CodeCombat" main_description: "Construiește propriile nivele,campanii,unități și conținut educațional.Noi îți furnizăm toate uneltele necesare!" article_title: "Editor Articol" article_description: "Scrie articole care oferă jucătorilor cunoștințe despre conceptele de programare care pot fi folosite pe o varietate de nivele și campanii." thang_title: "Editor Thang" thang_description: "Construiește unități ,definește logica lor,grafica și sunetul.Momentan suportă numai importare de grafică vectorială exportată din Flash." level_title: "Editor Nivele" level_description: "Include uneltele pentru scriptare, upload audio, și construcție de logică costum pentru toate tipurile de nivele.Tot ce folosim noi înșine!" security_notice: "Multe setări majore de securitate în aceste editoare nu sunt momentan disponibile.Pe măsură ce îmbunătățim securitatea acestor sisteme, ele vor deveni disponibile. Dacă doriți să folosiți aceste setări mai devrme, " contact_us: "contactați-ne!" hipchat_prefix: "Ne puteți de asemenea găsi la" hipchat_url: "HipChat." revert: "Revino la versiunea anterioară" revert_models: "Resetează Modelele" level_some_options: "Opțiuni?" level_tab_thangs: "Thangs" level_tab_scripts: "Script-uri" level_tab_settings: "Setări" level_tab_components: "Componente" level_tab_systems: "Sisteme" level_tab_thangs_title: "Thangs actuali" level_tab_thangs_conditions: "Condiți inițiale" level_tab_thangs_add: "Adaugă Thangs" level_settings_title: "Setări" level_component_tab_title: "Componente actuale" level_component_btn_new: "Crează componentă nouă" level_systems_tab_title: "Sisteme actuale" level_systems_btn_new: "Crează sistem nou" level_systems_btn_add: "Adaugă Sistem" level_components_title: "Înapoi la toți Thangs" level_components_type: "Tip" level_component_edit_title: "Editează Componenta" level_component_config_schema: "Schema Config" level_component_settings: "Setări" level_system_edit_title: "Editează Sistem" create_system_title: "Crează sistem nou" new_component_title: "Crează componentă nouă" new_component_field_system: "Sistem" new_article_title: "Crează un articol nou" new_thang_title: "Crează un nou tip de Thang" new_level_title: "Crează un nivel nou" article_search_title: "Caută articole aici" thang_search_title: "Caută tipuri de Thang aici" level_search_title: "Caută nivele aici" article: edit_btn_preview: "Preview" edit_article_title: "Editează Articol" general: and: "și" name: "Nume" body: "Corp" version: "Versiune" commit_msg: "Înregistrează Mesajul" history: "Istoric" version_history_for: "Versiune istorie pentru: " result: "Rezultat" results: "Resultate" description: "Descriere" or: "sau" email: "Email" password: "Parolă" message: "Mesaj" code: "Cod" ladder: "Clasament" when: "când" opponent: "oponent" rank: "Rank" score: "Scor" win: "Victorie" loss: "Înfrângere" tie: "Remiză" easy: "Ușor" medium: "Mediu" hard: "Greu" about: who_is_codecombat: "Cine este CodeCombat?" why_codecombat: "De ce CodeCombat?" who_description_prefix: "au pornit împreuna CodeCombat în 2013. Tot noi am creat " who_description_suffix: "în 2008, dezvoltând aplicația web si iOS #1 de învățat cum să scri caractere Japoneze si Chinezești." who_description_ending: "Acum este timpul să învățăm oamenii să scrie cod." why_paragraph_1: "Când am dezolvat Skritter, George nu știa cum să programeze și era mereu frustat de inabilitatea sa de a putea implementa ideile sale. După aceea, a încercat să învețe, dar lecțiile erau prea lente. Colegul său , vrând să se reprofilze și să se lase de predat,a încercat Codecademy, dar \"s-a plictisit.\" În fiecare săptămână un alt prieten a început Codecademy, iar apoi s-a lăsat. Am realizat că este aceeași problemă care am rezolvat-u cu Skritter: oameni încercând să învețe ceva nou prin lecții lente și intensive când defapt ceea ce le trebuie sunt lecții rapide și multă practică. Noi știm cum să rezolvăm asta." why_paragraph_2: "Trebuie să înveți să programezi? Nu-ți trebuie lecții. Trebuie să scri mult cod și să te distrezi făcând asta." why_paragraph_3_prefix: "Despre asta este programarea. Trebuie să fie distractiv. Nu precum" why_paragraph_3_italic: "wow o insignă" why_paragraph_3_center: "ci" why_paragraph_3_italic_caps: "TREBUIE SĂ TERMIN ACEST NIVEL!" why_paragraph_3_suffix: "De aceea CodeCombat este un joc multiplayer, nu un curs transfigurat în joc. Nu ne vom opri până când tu nu te poți opri--și de data asta, e de bine." why_paragraph_4: "Dacă e să devi dependent de vreun joc, devino dependent de acesta și fi un vrăjitor al noii ere tehnologice." why_ending: "Nu uita, este totul gratis. " why_ending_url: "Devino un vrăjitor acum!" george_description: "CEO, business guy, web designer, game designer, și campion al programatorilor începători." scott_description: "Programmer extraordinaire, software architect, kitchen wizard, și maestru al finanțelor. Scott este cel rezonabil." nick_description: "Programming wizard, eccentric motivation mage, and upside-down experimenter. Nick poate să facă orice si a ales să dezvolte CodeCombat." jeremy_description: "Customer support mage, usability tester, and community organizer; probabil ca ați vorbit deja cu Jeremy." michael_description: "Programmer, sys-admin, and undergrad technical wunderkind, Michael este cel care ține serverele in picioare." legal: page_title: "Aspecte Legale" opensource_intro: "CodeCombat este free-to-play și complet open source." opensource_description_prefix: "Vizitează " github_url: "pagina noastră de GitHub" opensource_description_center: "și ajută-ne dacă îți place! CodeCombat este construit peste o mulțime de proiecte open source, care noi le iubim. Vizitați" archmage_wiki_url: "Archmage wiki" opensource_description_suffix: "pentru o listă cu software-ul care face acest joc posibil." practices_title: "Convenții" practices_description: "Acestea sunt promisiunile noastre către tine, jucătorul, fără așa mulți termeni legali." privacy_title: "Confidenţialitate şi termeni" privacy_description: "Noi nu vom vinde nici o informație personală. Intenționăm să obținem profit prin recrutare eventual, dar stați liniștiți , nu vă vom vinde informațiile personale companiilor interesate fără consimțământul vostru explicit." security_title: "Securitate" security_description: "Ne străduim să vă protejăm informațiile personale. Fiind un proiect open-source, site-ul nostru oferă oricui posibilitatea de a ne revizui și îmbunătăți sistemul de securitate." email_title: "Email" email_description_prefix: "Noi nu vă vom inunda cu spam. Prin" email_settings_url: "setările tale de email" email_description_suffix: " sau prin link-urile din email-urile care vi le trimitem, puteți să schimbați preferințele și să vâ dezabonați oricând." cost_title: "Cost" cost_description: "Momentan, CodeCombat este 100% gratis! Unul dintre obiectele noastre principale este să îl menținem așa, astfel încât să poată juca cât mai mulți oameni. Dacă va fi nevoie , s-ar putea să percepem o plată pentru o pentru anumite servici,dar am prefera să nu o facem. Cu puțin noroc, vom putea susține compania cu:" recruitment_title: "Recrutare" recruitment_description_prefix: "Aici la CodeCombat, vei deveni un vrăjitor puternic nu doar în joc , ci și în viața reală." url_hire_programmers: "Nimeni nu poate angaja programatori destul de rapid" recruitment_description_suffix: "așa că odată ce ți-ai dezvoltat abilitățile și esti de acord, noi vom trimite un demo cu cele mai bune realizări ale tale către miile de angajatori care se omoară să pună mâna pe tine. Pe noi ne plătesc puțin, pe tine te vor plăti" recruitment_description_italic: "mult" recruitment_description_ending: "site-ul rămâne gratis și toată lumea este fericită. Acesta este planul." copyrights_title: "Drepturi de autor și licențe" contributor_title: "Acord de licență Contributor" contributor_description_prefix: "Toți contribuitorii, atât pe site cât și pe GitHub-ul nostru, sunt supuși la" cla_url: "ALC" contributor_description_suffix: "la care trebuie să fi de accord înainte să poți contribui." code_title: "Code - MIT" code_description_prefix: "Tot codul deținut de CodeCombat sau hostat pe codecombat.com, atât pe GitHub cât și în baza de date codecombat.com, este licențiată sub" mit_license_url: "MIT license" code_description_suffix: "Asta include tot codul din Systems și Components care este oferit de către CodeCombat cu scopul de a crea nivele." art_title: "Artă/Muzică - Conținut Comun " art_description_prefix: "Tot conținutul creativ/artistic este valabil sub" cc_license_url: "Creative Commons Attribution 4.0 International License" art_description_suffix: "Conținut comun este orice făcut general valabil de către CodeCombat cu scopul de a crea nivele. Asta include:" art_music: "Muzică" art_sound: "Sunet" art_artwork: "Artwork" art_sprites: "Sprites" art_other: "Orice si toate celelalte creații non-cod care sunt disponibile când se crează nivele." art_access: "Momentan nu există nici un sistem universal,ușor pentru preluarea acestor bunuri. În general, preluați-le precum site-ul din URL-urile folosite, contactați-ne pentru asistență, sau ajutați-ne sa extindem site-ul pentru a face aceste bunuri mai ușor accesibile." art_paragraph_1: "Pentru atribuire, vă rugăm numiți și lăsați referire link la codecombat.com unde este folosită sursa sau unde este adecvat pentru mediu. De exemplu:" use_list_1: "Dacă este folosit într-un film sau alt joc, includeți codecombat.com la credite." use_list_2: "Dacă este folosit pe un site, includeți un link in apropiere, de exemplu sub o imagine, sau in pagina generală de atribuiri unde menționați și alte Bunuri Creative și software open source folosit pe site. Ceva care face referință explicit la CodeCombat, precum o postare pe un blog care menționează CodeCombat, nu trebuie să facă o atribuire separată." art_paragraph_2: "Dacă conținutul folosit nu este creat de către CodeCombat ci de către un utilizator al codecombat.com,atunci faceți referință către ei, și urmăriți indicațiile de atribuire prevăzute în descrierea resursei dacă există." rights_title: "Drepturi rezervate" rights_desc: "Toate drepturile sunt rezervate pentru Nivele în sine. Asta include" rights_scripts: "Script-uri" rights_unit: "Configurații de unități" rights_description: "Descriere" rights_writings: "Scrieri" rights_media: "Media (sunete, muzică) și orice alt conținut creativ dezvoltat special pentru acel nivel care nu este valabil în mod normal pentru creat nivele." rights_clarification: "Pentru a clarifica, orice este valabil in Editorul de Nivele pentru scopul de a crea nivele se află sub CC,pe când conținutul creat cu Editorul de Nivele sau încărcat pentru a face nivelul nu se află." nutshell_title: "Pe scurt" nutshell_description: "Orice resurse vă punem la dispoziție în Editorul de Nivele puteți folosi liber cum vreți pentru a crea nivele. Dar ne rezervăm dreptul de a rezerva distribuția de nivele în sine (care sunt create pe codecombat.com) astfel încât să se poată percepe o taxă pentru ele pe vitor, dacă se va ajunge la așa ceva." canonical: "Versiunea in engleză a acestui document este cea definitivă, versiunea canonică. Dacă există orice discrepanțe între traduceri, documentul in engleză are prioritate." contribute: page_title: "Contribuțtii" character_classes_title: "Clase de caractere" introduction_desc_intro: "Avem speranțe mari pentru CodeCombat." introduction_desc_pref: "Vrem să fie locul unde programatori de toate rangurile vin să învețe și să se distreze împreună, introduc pe alții in minunata lume a programării, și reflectă cele mai bune părți ale comunității. Nu vrem și nu putem să facem asta singuri; ceea ce face proiectele precum GitHub, Stack Overflow și Linux geniale sunt oameni care le folosesc și construiec peste ele. Cu scopul acesta, " introduction_desc_github_url: "CodeCombat este complet open source" introduction_desc_suf: ", și ne propunem să vă punem la dispoziție pe cât de mult posibil modalități de a lua parte la acest proiect pentru a-l face la fel de mult as vostru cât și al nostru." introduction_desc_ending: "Sperăm să vă placă petrecerea noastră!" introduction_desc_signature: "- Nick, George, Scott, Michael, și Jeremy" alert_account_message_intro: "Salutare!" alert_account_message_pref: "Pentru a te abona la email-uri de clasă, va trebui să " alert_account_message_suf: "mai întâi." alert_account_message_create_url: "creați un cont" archmage_summary: "Interesat să lucrezi la grafica jocului, interfața grafică cu utilizatorul, baze de date și organizare server , multiplayer networking, fizică, sunet, sau performanțe game engine ? Vrei să ajuți la construirea unui joc pentru a învăța pe alții ceea ce te pricepi? Avem o grămadă de făcut dacă ești un programator experimentat și vrei sa dezvolți pentru CodeCombat, această clasă este pentru tine. Ne-ar plăcea să ne ajuți să construim cel mai bun joc de programare făcut vreodată." archmage_introduction: "Una dintre cele mai bune părți despre construirea unui joc este că sintetizează atât de multe lucruri diferite. Grafică, sunet, networking în timp real, social networking, și desigur multe dintre aspectele comune ale programării, de la gestiune low-level a bazelor de date , și administrare server până la construirea de interfețe. Este mult de muncă, și dacă ești un programator cu experiență, cu un dor de a se arunca cu capul înainte îm CodeCombat, această clasă ți se potrivește. Ne-ar plăcea să ne ajuți să construim cel mai bun joc de programare făcut vreodată." class_attributes: "Atribute pe clase" archmage_attribute_1_pref: "Cunoștințe în " archmage_attribute_1_suf: ", sau o dorință de a învăța. Majoritatea codului este în acest limbaj. Dacă ești fan Ruby sau Python, te vei simți ca acasă. Este JavaScript, dar cu o sintaxă mai frumoasă." archmage_attribute_2: "Ceva experiență în programare și inițiativă personală. Te vom ajuta să te orientezi, dar nu putem aloca prea mult timp pentru a te pregăti." how_to_join: "Cum să ni te alături" join_desc_1: "Oricine poate să ajute! Doar intrați pe " join_desc_2: "pentru a începe, și bifați căsuța de dedesubt pentru a te marca ca un Archmage curajos și pentru a primi ultimele știri pe email. Vrei să discuți despre ce să faci sau cum să te implici mai mult? " join_desc_3: ", sau găsește-ne în " join_desc_4: "și pornim de acolo!" join_url_email: "Trimite-ne Email" join_url_hipchat: "public HipChat room" more_about_archmage: "Învață mai multe despre cum să devi un Archmage" archmage_subscribe_desc: "Primește email-uri despre noi oportunități de progrmare și anunțuri." artisan_summary_pref: "Vrei să creezi nivele și să extinzi arsenalul CodeCombat? Oamenii ne termină nivelele mai repede decât putem să le creăm! Momentan, editorul nostru de nivele este rudimentar, așa că aveți grijă. Crearea de nivele va fi o mică provocare și va mai avea câteva bug-uri. Dacă ai viziuni cu campanii care cuprind loop-uri for pentru" artisan_summary_suf: "atunci asta e clasa pentru tine." artisan_introduction_pref: "Trebuie să construim nivele adiționale! Oamenii sunt nerăbdători pentru mai mult conținut, și noi putem face doar atât singuri. Momentan editorul de nivele abia este utilizabil până și de creatorii lui, așa că aveți grijă. Dacă ai viziuni cu campanii care cuprind loop-uri for pentru" artisan_introduction_suf: "atunci aceasta ar fi clasa pentru tine." artisan_attribute_1: "Orice experiență în crearea de conținut ca acesta ar fi de preferat, precum folosirea editoarelor de nivele de la Blizzard. Dar nu este obligatoriu!" artisan_attribute_2: "Un chef de a face o mulțime de teste și iterări. Pentru a face nivele bune, trebuie să testați pe mai mulți oameni și să obțineți feedback, și să fiți pregăți să reparați o mulțime de lucruri." artisan_attribute_3: "Pentru moment trebui să ai nervi de oțel. Editorul nostru de nivele este abia la început și încă are multe probleme. Ai fost avertizat!" artisan_join_desc: "Folosiți editorul de nivele urmărind acești pași , mai mult sau mai puțin:" artisan_join_step1: "Citește documentația." artisan_join_step2: "Crează un nivel nou și explorează nivelele deja existente." artisan_join_step3: "Găsește-ne pe chatul nostru de Hipchat pentru ajutor." artisan_join_step4: "Postează nivelele tale pe forum pentru feedback." more_about_artisan: "Învață mai multe despre ce înseamnă să devi un Artizan" artisan_subscribe_desc: "Primește email-uri despre update-uri legate de Editorul de Nivele și anunțuri." adventurer_summary: "Să fie clar ce implică rolul tău: tu ești tancul. Vei avea multe de îndurat. Avem nevoie de oameni care să testeze nivelele noi și să ne ajute să găsim moduri noi de a le îmbunătăți. Va fi greu; să creezi jocuri bune este un proces dificil și nimeni nu o face perfect din prima. Dacă crezi că poți îndura , atunci aceasta este clasa pentru tine." adventurer_introduction: "Să fie clar ce implică rolul tău: tu ești tancul. Vei avea multe de îndurat. Avem nevoie de oameni care să testeze nivelele noi și să ne ajute să găsim moduri noi de a le îmbunătăți. Va fi greu; să creezi jocuri bune este un proces dificil și nimeni nu o face perfect din prima. Dacă crezi că poți îndura , atunci aceasta este clasa pentru tine." adventurer_attribute_1: "O sete de cunoaștere. Tu vrei să înveți cum să programezi și noi vrem să te învățăm. Cel mai probabil tu vei fi cel care va preda mai mult în acest caz." adventurer_attribute_2: "Carismatic. Formulează într-un mod clar ceea ce trebuie îmbunătățit și oferă sugestii." adventurer_join_pref: "Ori fă echipă (sau recrutează!) cu un Artizan și lucrează cu el, sau bifează căsuța de mai jos pentru a primi email când sunt noi nivele de testat. De asemenea vom posta despre nivele care trebuiesc revizuite pe rețelele noastre precum" adventurer_forum_url: "forumul nostru" adventurer_join_suf: "deci dacă preferi să fi înștiințat în acele moduri ,înscrie-te acolo!" more_about_adventurer: "Învață mai multe despre ce înseamnă să devi un Aventurier" adventurer_subscribe_desc: "Primește email-uri când sunt noi nivele de testat." # scribe_summary_pref: "CodeCombat is not just going to be a bunch of levels. It will also be a resource of programming knowledge that players can hook into. That way, each Artisan can link to a detailed article that for the player's edification: documentation akin to what the " # scribe_summary_suf: " has built. If you enjoy explaining programming concepts, then this class is for you." # scribe_introduction_pref: "CodeCombat isn't just going to be a bunch of levels. It will also include a resource for knowledge, a wiki of programming concepts that levels can hook into. That way rather than each Artisan having to describe in detail what a comparison operator is, they can simply link their level to the Article describing them that is already written for the player's edification. Something along the lines of what the " # scribe_introduction_url_mozilla: "Mozilla Developer Network" # scribe_introduction_suf: " has built. If your idea of fun is articulating the concepts of programming in Markdown form, then this class might be for you." # scribe_attribute_1: "Skill in words is pretty much all you need. Not only grammar and spelling, but able to convey complicated ideas to others." # contact_us_url: "Contact us" # scribe_join_description: "tell us a little about yourself, your experience with programming and what sort of things you'd like to write about. We'll go from there!" # more_about_scribe: "Learn More About Becoming a Scribe" # scribe_subscribe_desc: "Get emails about article writing announcements." # diplomat_summary: "There is a large interest in CodeCombat in other countries that do not speak English! We are looking for translators who are willing to spend their time translating the site's corpus of words so that CodeCombat is accessible across the world as soon as possible. If you'd like to help getting CodeCombat international, then this class is for you." # diplomat_introduction_pref: "So, if there's one thing we learned from the " # diplomat_launch_url: "launch in October" # diplomat_introduction_suf: "it's that there is sizeable interest in CodeCombat in other countries! We're building a corps of translators eager to turn one set of words into another set of words to get CodeCombat as accessible across the world as possible. If you like getting sneak peeks at upcoming content and getting these levels to your fellow nationals ASAP, then this class might be for you." # diplomat_attribute_1: "Fluency in English and the language you would like to translate to. When conveying complicated ideas, it's important to have a strong grasp in both!" # diplomat_join_pref_github: "Find your language locale file " # diplomat_github_url: "on GitHub" # diplomat_join_suf_github: ", edit it online, and submit a pull request. Also, check this box below to keep up-to-date on new internationalization developments!" # more_about_diplomat: "Learn More About Becoming a Diplomat" # diplomat_subscribe_desc: "Get emails about i18n developments and levels to translate." # ambassador_summary: "We are trying to build a community, and every community needs a support team when there are troubles. We have got chats, emails, and social networks so that our users can get acquainted with the game. If you want to help people get involved, have fun, and learn some programming, then this class is for you." # ambassador_introduction: "This is a community we're building, and you are the connections. We've got Olark chats, emails, and social networks with lots of people to talk with and help get acquainted with the game and learn from. If you want to help people get involved and have fun, and get a good feel of the pulse of CodeCombat and where we're going, then this class might be for you." # ambassador_attribute_1: "Communication skills. Be able to identify the problems players are having and help them solve them. Also, keep the rest of us informed about what players are saying, what they like and don't like and want more of!" # ambassador_join_desc: "tell us a little about yourself, what you've done and what you'd be interested in doing. We'll go from there!" # ambassador_join_note_strong: "Note" # ambassador_join_note_desc: "One of our top priorities is to build multiplayer where players having difficulty solving levels can summon higher level wizards to help them. This will be a great way for ambassadors to do their thing. We'll keep you posted!" # more_about_ambassador: "Learn More About Becoming an Ambassador" # ambassador_subscribe_desc: "Get emails on support updates and multiplayer developments." # counselor_summary: "None of the above roles fit what you are interested in? Do not worry, we are on the lookout for anybody who wants a hand in the development of CodeCombat! If you are interested in teaching, game development, open source management, or anything else that you think will be relevant to us, then this class is for you." # counselor_introduction_1: "Do you have life experience? A different perspective on things that can help us decide how to shape CodeCombat? Of all these roles, this will probably take the least time, but individually you may make the most difference. We're on the lookout for wisened sages, particularly in areas like: teaching, game development, open source project management, technical recruiting, entrepreneurship, or design." # counselor_introduction_2: "Or really anything that is relevant to the development of CodeCombat. If you have knowledge and want to share it to help grow this project, then this class might be for you." # counselor_attribute_1: "Experience, in any of the areas above or something you think might be helpful." # counselor_attribute_2: "A little bit of free time!" # counselor_join_desc: "tell us a little about yourself, what you've done and what you'd be interested in doing. We'll put you in our contact list and be in touch when we could use advice (not too often)." more_about_counselor: "Află mai multe despre ce înseamna să devi Consilier" changes_auto_save: "Modificările sunt salvate automat când apeși checkbox-uri." diligent_scribes: "Scribii noștri:" powerful_archmages: "Bravii noștri Archmage:" creative_artisans: "Artizanii noștri creativi:" brave_adventurers: "Aventurierii noștri neînfricați:" translating_diplomats: "Diplomații noștri abili:" helpful_ambassadors: "Ambasadorii noștri de ajutor:" classes: archmage_title: "Archmage" archmage_title_description: "(Programator)" artisan_title: "Artizan" artisan_title_description: "(Creator de nivele)" adventurer_title: "Aventurier" adventurer_title_description: "(Playtester de nivele)" scribe_title: "Scrib" scribe_title_description: "(Editor de articole)" diplomat_title: "Diplomat" diplomat_title_description: "(Translator)" ambassador_title: "Ambasador" ambassador_title_description: "(Suport)" counselor_title: "Consilier" counselor_title_description: "(Expert/Profesor)" ladder: please_login: "Vă rugăm să vă autentificați înainte de a juca un meci de clasament." my_matches: "Jocurile mele" simulate: "Simulează" simulation_explanation: "Simulând jocuri poți afla poziția în clasament a jocului tău mai repede!" simulate_games: "Simulează Jocuri!" simulate_all: "RESETEAZĂ ȘI SIMULEAZĂ JOCURI" leaderboard: "Clasament" battle_as: "Luptă ca " summary_your: "Al tău " summary_matches: "Meciuri - " summary_wins: " Victorii, " summary_losses: " Înfrângeri" rank_no_code: "Nici un Cod nou pentru Clasament" rank_my_game: "Plasează-mi jocul in Clasament!" rank_submitting: "Se trimite..." rank_submitted: "Se trimite pentru Clasament" rank_failed: "A eșuat plasarea in clasament" rank_being_ranked: "Jocul se plasează in Clasament" code_being_simulated: "Codul tău este simulat de alți jucători pentru clasament. Se va actualiza cum apar meciuri." no_ranked_matches_pre: "Nici un meci de clasament pentru " no_ranked_matches_post: " echipă! Joacă împotriva unor concurenți și revino apoi aici pentr a-ți plasa meciul in clasament." choose_opponent: "Alege un adversar" tutorial_play: "Joacă Tutorial-ul" tutorial_recommended: "Recomandat dacă nu ai mai jucat niciodată înainte" tutorial_skip: "Sari peste Tutorial" tutorial_not_sure: "Nu ești sigur ce se întâmplă?" tutorial_play_first: "Joacă Tutorial-ul mai întâi." simple_ai: "AI simplu" warmup: "Încălzire" vs: "VS" # multiplayer_launch: # introducing_dungeon_arena: "Introducing Dungeon Arena" # new_way: "March 17, 2014: The new way to compete with code." # to_battle: "To Battle, Developers!" # modern_day_sorcerer: "You know how to code? That's badass. You're a modern-day sorcerer! Isn't about time that you used your magic coding powers to command your minions in epic combat? And we're not talking robots here." # arenas_are_here: "CodeCombat head-to-head multiplayer arenas are here." # ladder_explanation: "Choose your heroes, enchant your human or ogre armies, and climb your way over defeated fellow Wizards to reach the top of the ladders–then challenge your friends in our glorious, asynchronous multiplayer coding arenas. If you're feeling creative, you can even" # fork_our_arenas: "fork our arenas" # create_worlds: "and create your own worlds." # javascript_rusty: "JavaScript a bit rusty? Don't worry; there's a" # tutorial: "tutorial" # new_to_programming: ". New to programming? Hit our beginner campaign to skill up." # so_ready: "I Am So Ready for This"
63202
module.exports = nativeDescription: "limba română", englishDescription: "Romanian", translation: common: loading: "Se incarcă..." saving: "Se salvează..." sending: "Se trimite..." cancel: "Anulează" save: "Salvează" delay_1_sec: "1 secundă" delay_3_sec: "3 secunde" delay_5_sec: "5 secunde" manual: "Manual" fork: "Fork" play: "Joaca" modal: close: "Inchide" okay: "Okay" not_found: page_not_found: "Pagina nu a fost gasită" nav: play: "Nivele" editor: "Editor" blog: "Blog" forum: "Forum" admin: "Admin" home: "Acasa" contribute: "Contribuie" legal: "Confidențialitate și termeni" about: "Despre" contact: "Contact" twitter_follow: "Urmărește" employers: "Angajați" versions: save_version_title: "Salvează noua versiune" new_major_version: "Versiune nouă majoră" cla_prefix: "Pentru a salva modificările mai intâi trebuie sa fiți de acord cu" cla_url: "CLA" cla_suffix: "." cla_agree: "SUNT DE ACORD" login: sign_up: "Crează cont" log_in: "Log In" log_out: "Log Out" recover: "recuperează cont" recover: recover_account_title: "Recuperează Cont" send_password: "<PASSWORD>" signup: create_account_title: "Crează cont pentru a salva progresul" description: "Este gratis. Doar un scurt formular inainte si poți continua:" email_announcements: "Primește notificări prin emaill" coppa: "13+ sau non-USA " coppa_why: "(De ce?)" creating: "Se crează contul..." sign_up: "Înscrie-te" log_in: "loghează-te cu parola" home: slogan: "Învață sa scri JavaScript jucându-te" no_ie: "CodeCombat nu merge pe Internet Explorer 9 sau mai vechi. Scuze!" no_mobile: "CodeCombat nu a fost proiectat pentru dispozitive mobile si s-ar putea sa nu meargâ!" play: "Joacâ" # old_browser: "Uh oh, your browser is too old to run CodeCombat. Sorry!" # old_browser_suffix: "You can try anyway, but it probably won't work." # campaign: "Campaign" # for_beginners: "For Beginners" # multiplayer: "Multiplayer" # for_developers: "For Developers" play: choose_your_level: "Alege nivelul" adventurer_prefix: "Poți să sari la orice nivel de mai jos" adventurer_forum: "forumul Aventurierului" adventurer_suffix: "." campaign_beginner: "Campanie pentru Începători" campaign_beginner_description: "... în care se învață tainele programării." campaign_dev: "Nivele aleatoare mai grele" campaign_dev_description: "... în care se învață interfața, cu o dificultate puțin mai mare." campaign_multiplayer: "Arene Multiplayer" campaign_multiplayer_description: "... în care te lupți cap-la-cap contra alti jucători." campaign_player_created: "Create de jucători" campaign_player_created_description: "... în care ai ocazia să testezi creativitatea colegilor tai <a href=\"/contribute#artisan\">Artisan Wizards</a>." level_difficulty: "Dificultate: " play_as: "Alege-ți echipa" # spectate: "Spectate" contact: contact_us: "Contact CodeCombat" welcome: "Folosiți acest formular pentru a ne trimite email. " contribute_prefix: "Dacă sunteți interesați in a contribui uitați-vă pe " contribute_page: "pagina de contribuție" contribute_suffix: "!" forum_prefix: "Pentru orice altceva vă rugăm sa incercați " forum_page: "forumul nostru" forum_suffix: " în schimb." send: "Trimite Feedback" diplomat_suggestion: title: "Ajută-ne să traducem CodeCombat!" sub_heading: "Avem nevoie de abilitățile tale lingvistice." pitch_body: "CodeCombat este dezvoltat in limba engleza , dar deja avem jucatări din toate colțurile lumii.Mulți dintre ei vor să joace in română și nu vorbesc engleză.Dacă poți vorbi ambele te rugăm să te gândești dacă ai dori să devi un Diplomat și să ne ajuți sa traducem atât jocul cât și site-ul." missing_translations: "Until we can translate everything into Romanian, you'll see English when Romanian isn't available." learn_more: "Află mai multe despre cum să fi un Diplomat" subscribe_as_diplomat: "Înscrie-te ca Diplomat" wizard_settings: title: "Setări Wizard" customize_avatar: "Personalizează-ți Avatarul" clothes: "Haine" trim: "Margine" cloud: "Nor" spell: "Vrajă" boots: "Încălțăminte" hue: "Culoare" saturation: "Saturație" lightness: "Luminozitate" account_settings: title: "Setări Cont" not_logged_in: "Loghează-te sau crează un cont nou pentru a schimba setările." autosave: "Modificările se salvează automat" me_tab: "Eu" picture_tab: "Poză" wizard_tab: "Wizard" password_tab: "<PASSWORD>" emails_tab: "Email-uri" admin: "Admin" gravatar_select: "Selectează ce poză Gravatar vrei să foloșesti" gravatar_add_photos: "Adaugă thumbnails și poze la un cont Gravatar pentru email-ul tău pentru a alege o imagine." gravatar_add_more_photos: "Adaugă mai multe poze la contul tău Gravatar pentru a le accesa aici." wizard_color: "Culoare haine pentru Wizard" new_password: "<PASSWORD>" new_password_verify: "<PASSWORD>" email_subscriptions: "Subscripție Email" email_announcements: "Anunțuri" email_notifications: "Notificări" email_notifications_description: "Primește notificări periodic pentru contul tău." email_announcements_description: "Primește email-uri cu ultimele știri despre CodeCombat." contributor_emails: "Contributor Class Emails" contribute_prefix: "Căutăm oameni să se alăture distracției! Intră pe " contribute_page: "pagina de contribuție" contribute_suffix: " pentru a afla mai multe." email_toggle: "Alege tot" error_saving: "Salvare erori" saved: "Modificări salvate" password_mismatch: "<PASSWORD>." account_profile: edit_settings: "Modifică setările" profile_for_prefix: "Profil pentru " profile_for_suffix: "" profile: "Profil" user_not_found: "Utilizator negăsit. Verifică URL-ul??" gravatar_not_found_mine: "N-am putut găsi profilul asociat cu:" gravatar_not_found_email_suffix: "." gravatar_signup_prefix: "Înscrie-te la " gravatar_signup_suffix: " pentru a fi gata!" gravatar_not_found_other: "Din păcate nu este asociat nici un profil cu această adresă de email." gravatar_contact: "Contact" gravatar_websites: "Website-uri" gravatar_accounts: "Așa cum apare la" gravatar_profile_link: "Full Gravatar Profile" play_level: level_load_error: "Nivelul nu a putut fi încărcat: " done: "Gata" grid: "Grilă" customize_wizard: "Personalizează Wizard-ul" home: "Acasă" guide: "Ghid" multiplayer: "Multiplayer" restart: "Restart" goals: "Obiective" action_timeline: "Timeline-ul acțiunii" click_to_select: "Apasă pe o unitate pentru a o selecta." reload_title: "Reîncarcă tot Codul?" reload_really: "Ești sigur că vrei să reîncarci nivelul de la început?" reload_confirm: "Reload All" victory_title_prefix: "" victory_title_suffix: " Terminat" victory_sign_up: "Înscrie-te pentru a salva progresul" victory_sign_up_poke: "Vrei să-ți salvezi codul? Crează un cont gratis!" victory_rate_the_level: "Apreciază nivelul: " victory_rank_my_game: "Plasează-mi jocul in clasament" victory_ranking_game: "Se trimite..." victory_return_to_ladder: "Înapoi la jocurile de clasament" victory_play_next_level: "Joacă nivelul următor" victory_go_home: "Acasă" victory_review: "Spune-ne mai multe!" victory_hour_of_code_done: "Ai terminat?" victory_hour_of_code_done_yes: "Da, am terminat Hour of Code™!" multiplayer_title: "Setări Multiplayer" multiplayer_link_description: "Împărtășește acest link cu cei care vor să ți se alăture." multiplayer_hint_label: "Hint:" multiplayer_hint: " Apasă pe link pentru a selecta tot, apoi apasă ⌘-C sau Ctrl-C pentru a copia link-ul." multiplayer_coming_soon: "Mai multe feature-uri multiplayer în curând!" guide_title: "Ghid" tome_minion_spells: "Vrăjile Minion-ilor tăi" tome_read_only_spells: "Vrăji Read-Only" tome_other_units: "Alte unități" tome_cast_button_castable: "Aplică Vraja" tome_cast_button_casting: "Se încarcă" tome_cast_button_cast: "Aplică Vraja" tome_autocast_delay: "Întârziere Autocast" tome_select_spell: "Alege o vrajă" tome_select_a_thang: "Alege pe cineva pentru " tome_available_spells: "Vrăjile disponibile" hud_continue: "Continuă (apasă shift-space)" spell_saved: "Vrajă salvată" skip_tutorial: "Sari peste (esc)" # editor_config: "Editor Config" # editor_config_title: "Editor Configuration" # editor_config_keybindings_label: "Key Bindings" # editor_config_keybindings_default: "Default (Ace)" # editor_config_keybindings_description: "Adds additional shortcuts known from the common editors." # editor_config_invisibles_label: "Show Invisibles" # editor_config_invisibles_description: "Displays invisibles such as spaces or tabs." # editor_config_indentguides_label: "Show Indent Guides" # editor_config_indentguides_description: "Displays vertical lines to see indentation better." # editor_config_behaviors_label: "Smart Behaviors" # editor_config_behaviors_description: "Autocompletes brackets, braces, and quotes." admin: av_title: "Admin vede" av_entities_sub_title: "Entități" av_entities_users_url: "Utilizatori" av_entities_active_instances_url: "Instanțe active" av_other_sub_title: "Altele" av_other_debug_base_url: "Base (pentru debugging base.jade)" u_title: "Listă utilizatori" lg_title: "Ultimele jocuri" editor: main_title: "Editori CodeCombat" main_description: "Construiește propriile nivele,campanii,unități și conținut educațional.Noi îți furnizăm toate uneltele necesare!" article_title: "Editor Articol" article_description: "Scrie articole care oferă jucătorilor cunoștințe despre conceptele de programare care pot fi folosite pe o varietate de nivele și campanii." thang_title: "Editor Thang" thang_description: "Construiește unități ,definește logica lor,grafica și sunetul.Momentan suportă numai importare de grafică vectorială exportată din Flash." level_title: "Editor Nivele" level_description: "Include uneltele pentru scriptare, upload audio, și construcție de logică costum pentru toate tipurile de nivele.Tot ce folosim noi înșine!" security_notice: "Multe setări majore de securitate în aceste editoare nu sunt momentan disponibile.Pe măsură ce îmbunătățim securitatea acestor sisteme, ele vor deveni disponibile. Dacă doriți să folosiți aceste setări mai devrme, " contact_us: "contactați-ne!" hipchat_prefix: "Ne puteți de asemenea găsi la" hipchat_url: "HipChat." revert: "Revino la versiunea anterioară" revert_models: "Resetează Modelele" level_some_options: "Opțiuni?" level_tab_thangs: "Thangs" level_tab_scripts: "Script-uri" level_tab_settings: "Setări" level_tab_components: "Componente" level_tab_systems: "Sisteme" level_tab_thangs_title: "Thangs actuali" level_tab_thangs_conditions: "Condiți inițiale" level_tab_thangs_add: "Adaugă Thangs" level_settings_title: "Setări" level_component_tab_title: "Componente actuale" level_component_btn_new: "Crează componentă nouă" level_systems_tab_title: "Sisteme actuale" level_systems_btn_new: "Crează sistem nou" level_systems_btn_add: "Adaugă Sistem" level_components_title: "Înapoi la toți Thangs" level_components_type: "Tip" level_component_edit_title: "Editează Componenta" level_component_config_schema: "Schema Config" level_component_settings: "Setări" level_system_edit_title: "Editează Sistem" create_system_title: "Crează sistem nou" new_component_title: "Crează componentă nouă" new_component_field_system: "Sistem" new_article_title: "Crează un articol nou" new_thang_title: "Crează un nou tip de Thang" new_level_title: "Crează un nivel nou" article_search_title: "Caută articole aici" thang_search_title: "Caută tipuri de Thang aici" level_search_title: "Caută nivele aici" article: edit_btn_preview: "Preview" edit_article_title: "Editează Articol" general: and: "și" name: "<NAME>" body: "<NAME>" version: "Versiune" commit_msg: "Înregistrează Mesajul" history: "Istoric" version_history_for: "Versiune istorie pentru: " result: "Rezultat" results: "Resultate" description: "Descriere" or: "sau" email: "Email" password: "<PASSWORD>" message: "Mesaj" code: "Cod" ladder: "Clasament" when: "când" opponent: "oponent" rank: "Rank" score: "Scor" win: "Victorie" loss: "Înfrângere" tie: "Remiză" easy: "Ușor" medium: "Mediu" hard: "Greu" about: who_is_codecombat: "Cine este CodeCombat?" why_codecombat: "De ce CodeCombat?" who_description_prefix: "au pornit împreuna CodeCombat în 2013. Tot noi am creat " who_description_suffix: "în 2008, dezvoltând aplicația web si iOS #1 de învățat cum să scri caractere Japoneze si Chinezești." who_description_ending: "Acum este timpul să învățăm oamenii să scrie cod." why_paragraph_1: "Când am dezolvat Skritter, <NAME> nu știa cum să programeze și era mereu frustat de inabilitatea sa de a putea implementa ideile sale. După aceea, a încercat să învețe, dar lecțiile erau prea lente. Colegul său , vrând să se reprofilze și să se lase de predat,a încercat Codecademy, dar \"s-a plictisit.\" În fiecare săptămână un alt prieten a început Codecademy, iar apoi s-a lăsat. Am realizat că este aceeași problemă care am rezolvat-u cu Skritter: oameni încercând să învețe ceva nou prin lecții lente și intensive când defapt ceea ce le trebuie sunt lecții rapide și multă practică. Noi știm cum să rezolvăm asta." why_paragraph_2: "Trebuie să înveți să programezi? Nu-ți trebuie lecții. Trebuie să scri mult cod și să te distrezi făcând asta." why_paragraph_3_prefix: "Despre asta este programarea. Trebuie să fie distractiv. Nu precum" why_paragraph_3_italic: "wow o insignă" why_paragraph_3_center: "ci" why_paragraph_3_italic_caps: "TREBUIE SĂ TERMIN ACEST NIVEL!" why_paragraph_3_suffix: "De aceea CodeCombat este un joc multiplayer, nu un curs transfigurat în joc. Nu ne vom opri până când tu nu te poți opri--și de data asta, e de bine." why_paragraph_4: "Dacă e să devi dependent de vreun joc, devino dependent de acesta și fi un vrăjitor al noii ere tehnologice." why_ending: "Nu uita, este totul gratis. " why_ending_url: "Devino un vrăjitor acum!" george_description: "CEO, business guy, web designer, game designer, și campion al programatorilor începători." scott_description: "Programmer extraordinaire, software architect, kitchen wizard, și maestru al finanțelor. <NAME>cott este cel rezonabil." nick_description: "Programming wizard, eccentric motivation mage, and upside-down experimenter. Nick poate să facă orice si a ales să dezvolte CodeCombat." jeremy_description: "Customer support mage, usability tester, and community organizer; probabil ca ați vorbit deja cu <NAME>." michael_description: "Programmer, sys-admin, and undergrad technical wunderkind, <NAME> este cel care ține serverele in picioare." legal: page_title: "Aspecte Legale" opensource_intro: "CodeCombat este free-to-play și complet open source." opensource_description_prefix: "Vizitează " github_url: "pagina noastră de GitHub" opensource_description_center: "și ajută-ne dacă îți place! CodeCombat este construit peste o mulțime de proiecte open source, care noi le iubim. Vizitați" archmage_wiki_url: "Archmage wiki" opensource_description_suffix: "pentru o listă cu software-ul care face acest joc posibil." practices_title: "Convenții" practices_description: "Acestea sunt promisiunile noastre către tine, jucătorul, fără așa mulți termeni legali." privacy_title: "Confidenţialitate şi termeni" privacy_description: "Noi nu vom vinde nici o informație personală. Intenționăm să obținem profit prin recrutare eventual, dar stați liniștiți , nu vă vom vinde informațiile personale companiilor interesate fără consimțământul vostru explicit." security_title: "Securitate" security_description: "Ne străduim să vă protejăm informațiile personale. Fiind un proiect open-source, site-ul nostru oferă oricui posibilitatea de a ne revizui și îmbunătăți sistemul de securitate." email_title: "Email" email_description_prefix: "Noi nu vă vom inunda cu spam. Prin" email_settings_url: "setările tale de email" email_description_suffix: " sau prin link-urile din email-urile care vi le trimitem, puteți să schimbați preferințele și să vâ dezabonați oricând." cost_title: "Cost" cost_description: "Momentan, CodeCombat este 100% gratis! Unul dintre obiectele noastre principale este să îl menținem așa, astfel încât să poată juca cât mai mulți oameni. Dacă va fi nevoie , s-ar putea să percepem o plată pentru o pentru anumite servici,dar am prefera să nu o facem. Cu puțin noroc, vom putea susține compania cu:" recruitment_title: "Recrutare" recruitment_description_prefix: "Aici la CodeCombat, vei deveni un vrăjitor puternic nu doar în joc , ci și în viața reală." url_hire_programmers: "Nimeni nu poate angaja programatori destul de rapid" recruitment_description_suffix: "așa că odată ce ți-ai dezvoltat abilitățile și esti de acord, noi vom trimite un demo cu cele mai bune realizări ale tale către miile de angajatori care se omoară să pună mâna pe tine. Pe noi ne plătesc puțin, pe tine te vor plăti" recruitment_description_italic: "mult" recruitment_description_ending: "site-ul rămâne gratis și toată lumea este fericită. Acesta este planul." copyrights_title: "Drepturi de autor și licențe" contributor_title: "Acord de licență Contributor" contributor_description_prefix: "Toți contribuitorii, atât pe site cât și pe GitHub-ul nostru, sunt supuși la" cla_url: "ALC" contributor_description_suffix: "la care trebuie să fi de accord înainte să poți contribui." code_title: "Code - MIT" code_description_prefix: "Tot codul deținut de CodeCombat sau hostat pe codecombat.com, atât pe GitHub cât și în baza de date codecombat.com, este licențiată sub" mit_license_url: "MIT license" code_description_suffix: "Asta include tot codul din Systems și Components care este oferit de către CodeCombat cu scopul de a crea nivele." art_title: "Artă/Muzică - Conținut Comun " art_description_prefix: "Tot conținutul creativ/artistic este valabil sub" cc_license_url: "Creative Commons Attribution 4.0 International License" art_description_suffix: "Conținut comun este orice făcut general valabil de către CodeCombat cu scopul de a crea nivele. Asta include:" art_music: "Muzică" art_sound: "Sunet" art_artwork: "Artwork" art_sprites: "Sprites" art_other: "Orice si toate celelalte creații non-cod care sunt disponibile când se crează nivele." art_access: "Momentan nu există nici un sistem universal,ușor pentru preluarea acestor bunuri. În general, preluați-le precum site-ul din URL-urile folosite, contactați-ne pentru asistență, sau ajutați-ne sa extindem site-ul pentru a face aceste bunuri mai ușor accesibile." art_paragraph_1: "Pentru atribuire, vă rugăm numiți și lăsați referire link la codecombat.com unde este folosită sursa sau unde este adecvat pentru mediu. De exemplu:" use_list_1: "Dacă este folosit într-un film sau alt joc, includeți codecombat.com la credite." use_list_2: "Dacă este folosit pe un site, includeți un link in apropiere, de exemplu sub o imagine, sau in pagina generală de atribuiri unde menționați și alte Bunuri Creative și software open source folosit pe site. Ceva care face referință explicit la CodeCombat, precum o postare pe un blog care menționează CodeCombat, nu trebuie să facă o atribuire separată." art_paragraph_2: "Dacă conținutul folosit nu este creat de către CodeCombat ci de către un utilizator al codecombat.com,atunci faceți referință către ei, și urmăriți indicațiile de atribuire prevăzute în descrierea resursei dacă există." rights_title: "Drepturi rezervate" rights_desc: "Toate drepturile sunt rezervate pentru Nivele în sine. Asta include" rights_scripts: "Script-uri" rights_unit: "Configurații de unități" rights_description: "Descriere" rights_writings: "Scrieri" rights_media: "Media (sunete, muzică) și orice alt conținut creativ dezvoltat special pentru acel nivel care nu este valabil în mod normal pentru creat nivele." rights_clarification: "Pentru a clarifica, orice este valabil in Editorul de Nivele pentru scopul de a crea nivele se află sub CC,pe când conținutul creat cu Editorul de Nivele sau încărcat pentru a face nivelul nu se află." nutshell_title: "Pe scurt" nutshell_description: "Orice resurse vă punem la dispoziție în Editorul de Nivele puteți folosi liber cum vreți pentru a crea nivele. Dar ne rezervăm dreptul de a rezerva distribuția de nivele în sine (care sunt create pe codecombat.com) astfel încât să se poată percepe o taxă pentru ele pe vitor, dacă se va ajunge la așa ceva." canonical: "Versiunea in engleză a acestui document este cea definitivă, versiunea canonică. Dacă există orice discrepanțe între traduceri, documentul in engleză are prioritate." contribute: page_title: "Contribuțtii" character_classes_title: "Clase de caractere" introduction_desc_intro: "Avem speranțe mari pentru CodeCombat." introduction_desc_pref: "Vrem să fie locul unde programatori de toate rangurile vin să învețe și să se distreze împreună, introduc pe alții in minunata lume a programării, și reflectă cele mai bune părți ale comunității. Nu vrem și nu putem să facem asta singuri; ceea ce face proiectele precum GitHub, Stack Overflow și Linux geniale sunt oameni care le folosesc și construiec peste ele. Cu scopul acesta, " introduction_desc_github_url: "CodeCombat este complet open source" introduction_desc_suf: ", și ne propunem să vă punem la dispoziție pe cât de mult posibil modalități de a lua parte la acest proiect pentru a-l face la fel de mult as vostru cât și al nostru." introduction_desc_ending: "Sperăm să vă placă petrecerea noastră!" introduction_desc_signature: "- <NAME>, <NAME>, <NAME>, <NAME>, și <NAME>" alert_account_message_intro: "Salutare!" alert_account_message_pref: "Pentru a te abona la email-uri de clasă, va trebui să " alert_account_message_suf: "mai întâi." alert_account_message_create_url: "creați un cont" archmage_summary: "Interesat să lucrezi la grafica jocului, interfața grafică cu utilizatorul, baze de date și organizare server , multiplayer networking, fizică, sunet, sau performanțe game engine ? Vrei să ajuți la construirea unui joc pentru a învăța pe alții ceea ce te pricepi? Avem o grămadă de făcut dacă ești un programator experimentat și vrei sa dezvolți pentru CodeCombat, această clasă este pentru tine. Ne-ar plăcea să ne ajuți să construim cel mai bun joc de programare făcut vreodată." archmage_introduction: "Una dintre cele mai bune părți despre construirea unui joc este că sintetizează atât de multe lucruri diferite. Grafică, sunet, networking în timp real, social networking, și desigur multe dintre aspectele comune ale programării, de la gestiune low-level a bazelor de date , și administrare server până la construirea de interfețe. Este mult de muncă, și dacă ești un programator cu experiență, cu un dor de a se arunca cu capul înainte îm CodeCombat, această clasă ți se potrivește. Ne-ar plăcea să ne ajuți să construim cel mai bun joc de programare făcut vreodată." class_attributes: "Atribute pe clase" archmage_attribute_1_pref: "Cunoștințe în " archmage_attribute_1_suf: ", sau o dorință de a învăța. Majoritatea codului este în acest limbaj. Dacă ești fan Ruby sau Python, te vei simți ca acasă. Este JavaScript, dar cu o sintaxă mai frumoasă." archmage_attribute_2: "Ceva experiență în programare și inițiativă personală. Te vom ajuta să te orientezi, dar nu putem aloca prea mult timp pentru a te pregăti." how_to_join: "Cum să ni te alături" join_desc_1: "Oricine poate să ajute! Doar intrați pe " join_desc_2: "pentru a începe, și bifați căsuța de dedesubt pentru a te marca ca un Archmage curajos și pentru a primi ultimele știri pe email. Vrei să discuți despre ce să faci sau cum să te implici mai mult? " join_desc_3: ", sau găsește-ne în " join_desc_4: "și pornim de acolo!" join_url_email: "Trimite-ne Email" join_url_hipchat: "public HipChat room" more_about_archmage: "Învață mai multe despre cum să devi un Archmage" archmage_subscribe_desc: "Primește email-uri despre noi oportunități de progrmare și anunțuri." artisan_summary_pref: "Vrei să creezi nivele și să extinzi arsenalul CodeCombat? Oamenii ne termină nivelele mai repede decât putem să le creăm! Momentan, editorul nostru de nivele este rudimentar, așa că aveți grijă. Crearea de nivele va fi o mică provocare și va mai avea câteva bug-uri. Dacă ai viziuni cu campanii care cuprind loop-uri for pentru" artisan_summary_suf: "atunci asta e clasa pentru tine." artisan_introduction_pref: "Trebuie să construim nivele adiționale! Oamenii sunt nerăbdători pentru mai mult conținut, și noi putem face doar atât singuri. Momentan editorul de nivele abia este utilizabil până și de creatorii lui, așa că aveți grijă. Dacă ai viziuni cu campanii care cuprind loop-uri for pentru" artisan_introduction_suf: "atunci aceasta ar fi clasa pentru tine." artisan_attribute_1: "Orice experiență în crearea de conținut ca acesta ar fi de preferat, precum folosirea editoarelor de nivele de la Blizzard. Dar nu este obligatoriu!" artisan_attribute_2: "Un chef de a face o mulțime de teste și iterări. Pentru a face nivele bune, trebuie să testați pe mai mulți oameni și să obțineți feedback, și să fiți pregăți să reparați o mulțime de lucruri." artisan_attribute_3: "Pentru moment trebui să ai nervi de oțel. Editorul nostru de nivele este abia la început și încă are multe probleme. Ai fost avertizat!" artisan_join_desc: "Folosiți editorul de nivele urmărind acești pași , mai mult sau mai puțin:" artisan_join_step1: "Citește documentația." artisan_join_step2: "Crează un nivel nou și explorează nivelele deja existente." artisan_join_step3: "Găsește-ne pe chatul nostru de Hipchat pentru ajutor." artisan_join_step4: "Postează nivelele tale pe forum pentru feedback." more_about_artisan: "Învață mai multe despre ce înseamnă să devi un Artizan" artisan_subscribe_desc: "Primește email-uri despre update-uri legate de Editorul de Nivele și anunțuri." adventurer_summary: "Să fie clar ce implică rolul tău: tu ești tancul. Vei avea multe de îndurat. Avem nevoie de oameni care să testeze nivelele noi și să ne ajute să găsim moduri noi de a le îmbunătăți. Va fi greu; să creezi jocuri bune este un proces dificil și nimeni nu o face perfect din prima. Dacă crezi că poți îndura , atunci aceasta este clasa pentru tine." adventurer_introduction: "Să fie clar ce implică rolul tău: tu ești tancul. Vei avea multe de îndurat. Avem nevoie de oameni care să testeze nivelele noi și să ne ajute să găsim moduri noi de a le îmbunătăți. Va fi greu; să creezi jocuri bune este un proces dificil și nimeni nu o face perfect din prima. Dacă crezi că poți îndura , atunci aceasta este clasa pentru tine." adventurer_attribute_1: "O sete de cunoaștere. Tu vrei să înveți cum să programezi și noi vrem să te învățăm. Cel mai probabil tu vei fi cel care va preda mai mult în acest caz." adventurer_attribute_2: "Carismatic. Formulează într-un mod clar ceea ce trebuie îmbunătățit și oferă sugestii." adventurer_join_pref: "Ori fă echipă (sau recrutează!) cu un Artizan și lucrează cu el, sau bifează căsuța de mai jos pentru a primi email când sunt noi nivele de testat. De asemenea vom posta despre nivele care trebuiesc revizuite pe rețelele noastre precum" adventurer_forum_url: "forumul nostru" adventurer_join_suf: "deci dacă preferi să fi înștiințat în acele moduri ,înscrie-te acolo!" more_about_adventurer: "Învață mai multe despre ce înseamnă să devi un Aventurier" adventurer_subscribe_desc: "Primește email-uri când sunt noi nivele de testat." # scribe_summary_pref: "CodeCombat is not just going to be a bunch of levels. It will also be a resource of programming knowledge that players can hook into. That way, each Artisan can link to a detailed article that for the player's edification: documentation akin to what the " # scribe_summary_suf: " has built. If you enjoy explaining programming concepts, then this class is for you." # scribe_introduction_pref: "CodeCombat isn't just going to be a bunch of levels. It will also include a resource for knowledge, a wiki of programming concepts that levels can hook into. That way rather than each Artisan having to describe in detail what a comparison operator is, they can simply link their level to the Article describing them that is already written for the player's edification. Something along the lines of what the " # scribe_introduction_url_mozilla: "Mozilla Developer Network" # scribe_introduction_suf: " has built. If your idea of fun is articulating the concepts of programming in Markdown form, then this class might be for you." # scribe_attribute_1: "Skill in words is pretty much all you need. Not only grammar and spelling, but able to convey complicated ideas to others." # contact_us_url: "Contact us" # scribe_join_description: "tell us a little about yourself, your experience with programming and what sort of things you'd like to write about. We'll go from there!" # more_about_scribe: "Learn More About Becoming a Scribe" # scribe_subscribe_desc: "Get emails about article writing announcements." # diplomat_summary: "There is a large interest in CodeCombat in other countries that do not speak English! We are looking for translators who are willing to spend their time translating the site's corpus of words so that CodeCombat is accessible across the world as soon as possible. If you'd like to help getting CodeCombat international, then this class is for you." # diplomat_introduction_pref: "So, if there's one thing we learned from the " # diplomat_launch_url: "launch in October" # diplomat_introduction_suf: "it's that there is sizeable interest in CodeCombat in other countries! We're building a corps of translators eager to turn one set of words into another set of words to get CodeCombat as accessible across the world as possible. If you like getting sneak peeks at upcoming content and getting these levels to your fellow nationals ASAP, then this class might be for you." # diplomat_attribute_1: "Fluency in English and the language you would like to translate to. When conveying complicated ideas, it's important to have a strong grasp in both!" # diplomat_join_pref_github: "Find your language locale file " # diplomat_github_url: "on GitHub" # diplomat_join_suf_github: ", edit it online, and submit a pull request. Also, check this box below to keep up-to-date on new internationalization developments!" # more_about_diplomat: "Learn More About Becoming a Diplomat" # diplomat_subscribe_desc: "Get emails about i18n developments and levels to translate." # ambassador_summary: "We are trying to build a community, and every community needs a support team when there are troubles. We have got chats, emails, and social networks so that our users can get acquainted with the game. If you want to help people get involved, have fun, and learn some programming, then this class is for you." # ambassador_introduction: "This is a community we're building, and you are the connections. We've got Olark chats, emails, and social networks with lots of people to talk with and help get acquainted with the game and learn from. If you want to help people get involved and have fun, and get a good feel of the pulse of CodeCombat and where we're going, then this class might be for you." # ambassador_attribute_1: "Communication skills. Be able to identify the problems players are having and help them solve them. Also, keep the rest of us informed about what players are saying, what they like and don't like and want more of!" # ambassador_join_desc: "tell us a little about yourself, what you've done and what you'd be interested in doing. We'll go from there!" # ambassador_join_note_strong: "Note" # ambassador_join_note_desc: "One of our top priorities is to build multiplayer where players having difficulty solving levels can summon higher level wizards to help them. This will be a great way for ambassadors to do their thing. We'll keep you posted!" # more_about_ambassador: "Learn More About Becoming an Ambassador" # ambassador_subscribe_desc: "Get emails on support updates and multiplayer developments." # counselor_summary: "None of the above roles fit what you are interested in? Do not worry, we are on the lookout for anybody who wants a hand in the development of CodeCombat! If you are interested in teaching, game development, open source management, or anything else that you think will be relevant to us, then this class is for you." # counselor_introduction_1: "Do you have life experience? A different perspective on things that can help us decide how to shape CodeCombat? Of all these roles, this will probably take the least time, but individually you may make the most difference. We're on the lookout for wisened sages, particularly in areas like: teaching, game development, open source project management, technical recruiting, entrepreneurship, or design." # counselor_introduction_2: "Or really anything that is relevant to the development of CodeCombat. If you have knowledge and want to share it to help grow this project, then this class might be for you." # counselor_attribute_1: "Experience, in any of the areas above or something you think might be helpful." # counselor_attribute_2: "A little bit of free time!" # counselor_join_desc: "tell us a little about yourself, what you've done and what you'd be interested in doing. We'll put you in our contact list and be in touch when we could use advice (not too often)." more_about_counselor: "Află mai multe despre ce înseamna să devi Consilier" changes_auto_save: "Modificările sunt salvate automat când apeși checkbox-uri." diligent_scribes: "Scribii noștri:" powerful_archmages: "Bravii noștri Archmage:" creative_artisans: "Artizanii noștri creativi:" brave_adventurers: "Aventurierii noștri neînfricați:" translating_diplomats: "Diplomații noștri abili:" helpful_ambassadors: "Ambasadorii noștri de ajutor:" classes: archmage_title: "Archmage" archmage_title_description: "(Programator)" artisan_title: "Artizan" artisan_title_description: "(Creator de nivele)" adventurer_title: "Aventurier" adventurer_title_description: "(Playtester de nivele)" scribe_title: "Scrib" scribe_title_description: "(Editor de articole)" diplomat_title: "Diplomat" diplomat_title_description: "(Translator)" ambassador_title: "Ambasador" ambassador_title_description: "(Suport)" counselor_title: "Consilier" counselor_title_description: "(Expert/Profesor)" ladder: please_login: "Vă rugăm să vă autentificați înainte de a juca un meci de clasament." my_matches: "Jocurile mele" simulate: "Simulează" simulation_explanation: "Simulând jocuri poți afla poziția în clasament a jocului tău mai repede!" simulate_games: "Simulează Jocuri!" simulate_all: "RESETEAZĂ ȘI SIMULEAZĂ JOCURI" leaderboard: "Clasament" battle_as: "Luptă ca " summary_your: "Al tău " summary_matches: "Meciuri - " summary_wins: " Victorii, " summary_losses: " Înfrângeri" rank_no_code: "Nici un Cod nou pentru Clasament" rank_my_game: "Plasează-mi jocul in Clasament!" rank_submitting: "Se trimite..." rank_submitted: "Se trimite pentru Clasament" rank_failed: "A eșuat plasarea in clasament" rank_being_ranked: "Jocul se plasează in Clasament" code_being_simulated: "Codul tău este simulat de alți jucători pentru clasament. Se va actualiza cum apar meciuri." no_ranked_matches_pre: "Nici un meci de clasament pentru " no_ranked_matches_post: " echipă! Joacă împotriva unor concurenți și revino apoi aici pentr a-ți plasa meciul in clasament." choose_opponent: "Alege un adversar" tutorial_play: "Joacă Tutorial-ul" tutorial_recommended: "Recomandat dacă nu ai mai jucat niciodată înainte" tutorial_skip: "Sari peste Tutorial" tutorial_not_sure: "Nu ești sigur ce se întâmplă?" tutorial_play_first: "Joacă Tutorial-ul mai întâi." simple_ai: "AI simplu" warmup: "Încălzire" vs: "VS" # multiplayer_launch: # introducing_dungeon_arena: "Introducing Dungeon Arena" # new_way: "March 17, 2014: The new way to compete with code." # to_battle: "To Battle, Developers!" # modern_day_sorcerer: "You know how to code? That's badass. You're a modern-day sorcerer! Isn't about time that you used your magic coding powers to command your minions in epic combat? And we're not talking robots here." # arenas_are_here: "CodeCombat head-to-head multiplayer arenas are here." # ladder_explanation: "Choose your heroes, enchant your human or ogre armies, and climb your way over defeated fellow Wizards to reach the top of the ladders–then challenge your friends in our glorious, asynchronous multiplayer coding arenas. If you're feeling creative, you can even" # fork_our_arenas: "fork our arenas" # create_worlds: "and create your own worlds." # javascript_rusty: "JavaScript a bit rusty? Don't worry; there's a" # tutorial: "tutorial" # new_to_programming: ". New to programming? Hit our beginner campaign to skill up." # so_ready: "I Am So Ready for This"
true
module.exports = nativeDescription: "limba română", englishDescription: "Romanian", translation: common: loading: "Se incarcă..." saving: "Se salvează..." sending: "Se trimite..." cancel: "Anulează" save: "Salvează" delay_1_sec: "1 secundă" delay_3_sec: "3 secunde" delay_5_sec: "5 secunde" manual: "Manual" fork: "Fork" play: "Joaca" modal: close: "Inchide" okay: "Okay" not_found: page_not_found: "Pagina nu a fost gasită" nav: play: "Nivele" editor: "Editor" blog: "Blog" forum: "Forum" admin: "Admin" home: "Acasa" contribute: "Contribuie" legal: "Confidențialitate și termeni" about: "Despre" contact: "Contact" twitter_follow: "Urmărește" employers: "Angajați" versions: save_version_title: "Salvează noua versiune" new_major_version: "Versiune nouă majoră" cla_prefix: "Pentru a salva modificările mai intâi trebuie sa fiți de acord cu" cla_url: "CLA" cla_suffix: "." cla_agree: "SUNT DE ACORD" login: sign_up: "Crează cont" log_in: "Log In" log_out: "Log Out" recover: "recuperează cont" recover: recover_account_title: "Recuperează Cont" send_password: "PI:PASSWORD:<PASSWORD>END_PI" signup: create_account_title: "Crează cont pentru a salva progresul" description: "Este gratis. Doar un scurt formular inainte si poți continua:" email_announcements: "Primește notificări prin emaill" coppa: "13+ sau non-USA " coppa_why: "(De ce?)" creating: "Se crează contul..." sign_up: "Înscrie-te" log_in: "loghează-te cu parola" home: slogan: "Învață sa scri JavaScript jucându-te" no_ie: "CodeCombat nu merge pe Internet Explorer 9 sau mai vechi. Scuze!" no_mobile: "CodeCombat nu a fost proiectat pentru dispozitive mobile si s-ar putea sa nu meargâ!" play: "Joacâ" # old_browser: "Uh oh, your browser is too old to run CodeCombat. Sorry!" # old_browser_suffix: "You can try anyway, but it probably won't work." # campaign: "Campaign" # for_beginners: "For Beginners" # multiplayer: "Multiplayer" # for_developers: "For Developers" play: choose_your_level: "Alege nivelul" adventurer_prefix: "Poți să sari la orice nivel de mai jos" adventurer_forum: "forumul Aventurierului" adventurer_suffix: "." campaign_beginner: "Campanie pentru Începători" campaign_beginner_description: "... în care se învață tainele programării." campaign_dev: "Nivele aleatoare mai grele" campaign_dev_description: "... în care se învață interfața, cu o dificultate puțin mai mare." campaign_multiplayer: "Arene Multiplayer" campaign_multiplayer_description: "... în care te lupți cap-la-cap contra alti jucători." campaign_player_created: "Create de jucători" campaign_player_created_description: "... în care ai ocazia să testezi creativitatea colegilor tai <a href=\"/contribute#artisan\">Artisan Wizards</a>." level_difficulty: "Dificultate: " play_as: "Alege-ți echipa" # spectate: "Spectate" contact: contact_us: "Contact CodeCombat" welcome: "Folosiți acest formular pentru a ne trimite email. " contribute_prefix: "Dacă sunteți interesați in a contribui uitați-vă pe " contribute_page: "pagina de contribuție" contribute_suffix: "!" forum_prefix: "Pentru orice altceva vă rugăm sa incercați " forum_page: "forumul nostru" forum_suffix: " în schimb." send: "Trimite Feedback" diplomat_suggestion: title: "Ajută-ne să traducem CodeCombat!" sub_heading: "Avem nevoie de abilitățile tale lingvistice." pitch_body: "CodeCombat este dezvoltat in limba engleza , dar deja avem jucatări din toate colțurile lumii.Mulți dintre ei vor să joace in română și nu vorbesc engleză.Dacă poți vorbi ambele te rugăm să te gândești dacă ai dori să devi un Diplomat și să ne ajuți sa traducem atât jocul cât și site-ul." missing_translations: "Until we can translate everything into Romanian, you'll see English when Romanian isn't available." learn_more: "Află mai multe despre cum să fi un Diplomat" subscribe_as_diplomat: "Înscrie-te ca Diplomat" wizard_settings: title: "Setări Wizard" customize_avatar: "Personalizează-ți Avatarul" clothes: "Haine" trim: "Margine" cloud: "Nor" spell: "Vrajă" boots: "Încălțăminte" hue: "Culoare" saturation: "Saturație" lightness: "Luminozitate" account_settings: title: "Setări Cont" not_logged_in: "Loghează-te sau crează un cont nou pentru a schimba setările." autosave: "Modificările se salvează automat" me_tab: "Eu" picture_tab: "Poză" wizard_tab: "Wizard" password_tab: "PI:PASSWORD:<PASSWORD>END_PI" emails_tab: "Email-uri" admin: "Admin" gravatar_select: "Selectează ce poză Gravatar vrei să foloșesti" gravatar_add_photos: "Adaugă thumbnails și poze la un cont Gravatar pentru email-ul tău pentru a alege o imagine." gravatar_add_more_photos: "Adaugă mai multe poze la contul tău Gravatar pentru a le accesa aici." wizard_color: "Culoare haine pentru Wizard" new_password: "PI:PASSWORD:<PASSWORD>END_PI" new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI" email_subscriptions: "Subscripție Email" email_announcements: "Anunțuri" email_notifications: "Notificări" email_notifications_description: "Primește notificări periodic pentru contul tău." email_announcements_description: "Primește email-uri cu ultimele știri despre CodeCombat." contributor_emails: "Contributor Class Emails" contribute_prefix: "Căutăm oameni să se alăture distracției! Intră pe " contribute_page: "pagina de contribuție" contribute_suffix: " pentru a afla mai multe." email_toggle: "Alege tot" error_saving: "Salvare erori" saved: "Modificări salvate" password_mismatch: "PI:PASSWORD:<PASSWORD>END_PI." account_profile: edit_settings: "Modifică setările" profile_for_prefix: "Profil pentru " profile_for_suffix: "" profile: "Profil" user_not_found: "Utilizator negăsit. Verifică URL-ul??" gravatar_not_found_mine: "N-am putut găsi profilul asociat cu:" gravatar_not_found_email_suffix: "." gravatar_signup_prefix: "Înscrie-te la " gravatar_signup_suffix: " pentru a fi gata!" gravatar_not_found_other: "Din păcate nu este asociat nici un profil cu această adresă de email." gravatar_contact: "Contact" gravatar_websites: "Website-uri" gravatar_accounts: "Așa cum apare la" gravatar_profile_link: "Full Gravatar Profile" play_level: level_load_error: "Nivelul nu a putut fi încărcat: " done: "Gata" grid: "Grilă" customize_wizard: "Personalizează Wizard-ul" home: "Acasă" guide: "Ghid" multiplayer: "Multiplayer" restart: "Restart" goals: "Obiective" action_timeline: "Timeline-ul acțiunii" click_to_select: "Apasă pe o unitate pentru a o selecta." reload_title: "Reîncarcă tot Codul?" reload_really: "Ești sigur că vrei să reîncarci nivelul de la început?" reload_confirm: "Reload All" victory_title_prefix: "" victory_title_suffix: " Terminat" victory_sign_up: "Înscrie-te pentru a salva progresul" victory_sign_up_poke: "Vrei să-ți salvezi codul? Crează un cont gratis!" victory_rate_the_level: "Apreciază nivelul: " victory_rank_my_game: "Plasează-mi jocul in clasament" victory_ranking_game: "Se trimite..." victory_return_to_ladder: "Înapoi la jocurile de clasament" victory_play_next_level: "Joacă nivelul următor" victory_go_home: "Acasă" victory_review: "Spune-ne mai multe!" victory_hour_of_code_done: "Ai terminat?" victory_hour_of_code_done_yes: "Da, am terminat Hour of Code™!" multiplayer_title: "Setări Multiplayer" multiplayer_link_description: "Împărtășește acest link cu cei care vor să ți se alăture." multiplayer_hint_label: "Hint:" multiplayer_hint: " Apasă pe link pentru a selecta tot, apoi apasă ⌘-C sau Ctrl-C pentru a copia link-ul." multiplayer_coming_soon: "Mai multe feature-uri multiplayer în curând!" guide_title: "Ghid" tome_minion_spells: "Vrăjile Minion-ilor tăi" tome_read_only_spells: "Vrăji Read-Only" tome_other_units: "Alte unități" tome_cast_button_castable: "Aplică Vraja" tome_cast_button_casting: "Se încarcă" tome_cast_button_cast: "Aplică Vraja" tome_autocast_delay: "Întârziere Autocast" tome_select_spell: "Alege o vrajă" tome_select_a_thang: "Alege pe cineva pentru " tome_available_spells: "Vrăjile disponibile" hud_continue: "Continuă (apasă shift-space)" spell_saved: "Vrajă salvată" skip_tutorial: "Sari peste (esc)" # editor_config: "Editor Config" # editor_config_title: "Editor Configuration" # editor_config_keybindings_label: "Key Bindings" # editor_config_keybindings_default: "Default (Ace)" # editor_config_keybindings_description: "Adds additional shortcuts known from the common editors." # editor_config_invisibles_label: "Show Invisibles" # editor_config_invisibles_description: "Displays invisibles such as spaces or tabs." # editor_config_indentguides_label: "Show Indent Guides" # editor_config_indentguides_description: "Displays vertical lines to see indentation better." # editor_config_behaviors_label: "Smart Behaviors" # editor_config_behaviors_description: "Autocompletes brackets, braces, and quotes." admin: av_title: "Admin vede" av_entities_sub_title: "Entități" av_entities_users_url: "Utilizatori" av_entities_active_instances_url: "Instanțe active" av_other_sub_title: "Altele" av_other_debug_base_url: "Base (pentru debugging base.jade)" u_title: "Listă utilizatori" lg_title: "Ultimele jocuri" editor: main_title: "Editori CodeCombat" main_description: "Construiește propriile nivele,campanii,unități și conținut educațional.Noi îți furnizăm toate uneltele necesare!" article_title: "Editor Articol" article_description: "Scrie articole care oferă jucătorilor cunoștințe despre conceptele de programare care pot fi folosite pe o varietate de nivele și campanii." thang_title: "Editor Thang" thang_description: "Construiește unități ,definește logica lor,grafica și sunetul.Momentan suportă numai importare de grafică vectorială exportată din Flash." level_title: "Editor Nivele" level_description: "Include uneltele pentru scriptare, upload audio, și construcție de logică costum pentru toate tipurile de nivele.Tot ce folosim noi înșine!" security_notice: "Multe setări majore de securitate în aceste editoare nu sunt momentan disponibile.Pe măsură ce îmbunătățim securitatea acestor sisteme, ele vor deveni disponibile. Dacă doriți să folosiți aceste setări mai devrme, " contact_us: "contactați-ne!" hipchat_prefix: "Ne puteți de asemenea găsi la" hipchat_url: "HipChat." revert: "Revino la versiunea anterioară" revert_models: "Resetează Modelele" level_some_options: "Opțiuni?" level_tab_thangs: "Thangs" level_tab_scripts: "Script-uri" level_tab_settings: "Setări" level_tab_components: "Componente" level_tab_systems: "Sisteme" level_tab_thangs_title: "Thangs actuali" level_tab_thangs_conditions: "Condiți inițiale" level_tab_thangs_add: "Adaugă Thangs" level_settings_title: "Setări" level_component_tab_title: "Componente actuale" level_component_btn_new: "Crează componentă nouă" level_systems_tab_title: "Sisteme actuale" level_systems_btn_new: "Crează sistem nou" level_systems_btn_add: "Adaugă Sistem" level_components_title: "Înapoi la toți Thangs" level_components_type: "Tip" level_component_edit_title: "Editează Componenta" level_component_config_schema: "Schema Config" level_component_settings: "Setări" level_system_edit_title: "Editează Sistem" create_system_title: "Crează sistem nou" new_component_title: "Crează componentă nouă" new_component_field_system: "Sistem" new_article_title: "Crează un articol nou" new_thang_title: "Crează un nou tip de Thang" new_level_title: "Crează un nivel nou" article_search_title: "Caută articole aici" thang_search_title: "Caută tipuri de Thang aici" level_search_title: "Caută nivele aici" article: edit_btn_preview: "Preview" edit_article_title: "Editează Articol" general: and: "și" name: "PI:NAME:<NAME>END_PI" body: "PI:NAME:<NAME>END_PI" version: "Versiune" commit_msg: "Înregistrează Mesajul" history: "Istoric" version_history_for: "Versiune istorie pentru: " result: "Rezultat" results: "Resultate" description: "Descriere" or: "sau" email: "Email" password: "PI:PASSWORD:<PASSWORD>END_PI" message: "Mesaj" code: "Cod" ladder: "Clasament" when: "când" opponent: "oponent" rank: "Rank" score: "Scor" win: "Victorie" loss: "Înfrângere" tie: "Remiză" easy: "Ușor" medium: "Mediu" hard: "Greu" about: who_is_codecombat: "Cine este CodeCombat?" why_codecombat: "De ce CodeCombat?" who_description_prefix: "au pornit împreuna CodeCombat în 2013. Tot noi am creat " who_description_suffix: "în 2008, dezvoltând aplicația web si iOS #1 de învățat cum să scri caractere Japoneze si Chinezești." who_description_ending: "Acum este timpul să învățăm oamenii să scrie cod." why_paragraph_1: "Când am dezolvat Skritter, PI:NAME:<NAME>END_PI nu știa cum să programeze și era mereu frustat de inabilitatea sa de a putea implementa ideile sale. După aceea, a încercat să învețe, dar lecțiile erau prea lente. Colegul său , vrând să se reprofilze și să se lase de predat,a încercat Codecademy, dar \"s-a plictisit.\" În fiecare săptămână un alt prieten a început Codecademy, iar apoi s-a lăsat. Am realizat că este aceeași problemă care am rezolvat-u cu Skritter: oameni încercând să învețe ceva nou prin lecții lente și intensive când defapt ceea ce le trebuie sunt lecții rapide și multă practică. Noi știm cum să rezolvăm asta." why_paragraph_2: "Trebuie să înveți să programezi? Nu-ți trebuie lecții. Trebuie să scri mult cod și să te distrezi făcând asta." why_paragraph_3_prefix: "Despre asta este programarea. Trebuie să fie distractiv. Nu precum" why_paragraph_3_italic: "wow o insignă" why_paragraph_3_center: "ci" why_paragraph_3_italic_caps: "TREBUIE SĂ TERMIN ACEST NIVEL!" why_paragraph_3_suffix: "De aceea CodeCombat este un joc multiplayer, nu un curs transfigurat în joc. Nu ne vom opri până când tu nu te poți opri--și de data asta, e de bine." why_paragraph_4: "Dacă e să devi dependent de vreun joc, devino dependent de acesta și fi un vrăjitor al noii ere tehnologice." why_ending: "Nu uita, este totul gratis. " why_ending_url: "Devino un vrăjitor acum!" george_description: "CEO, business guy, web designer, game designer, și campion al programatorilor începători." scott_description: "Programmer extraordinaire, software architect, kitchen wizard, și maestru al finanțelor. PI:NAME:<NAME>END_PIcott este cel rezonabil." nick_description: "Programming wizard, eccentric motivation mage, and upside-down experimenter. Nick poate să facă orice si a ales să dezvolte CodeCombat." jeremy_description: "Customer support mage, usability tester, and community organizer; probabil ca ați vorbit deja cu PI:NAME:<NAME>END_PI." michael_description: "Programmer, sys-admin, and undergrad technical wunderkind, PI:NAME:<NAME>END_PI este cel care ține serverele in picioare." legal: page_title: "Aspecte Legale" opensource_intro: "CodeCombat este free-to-play și complet open source." opensource_description_prefix: "Vizitează " github_url: "pagina noastră de GitHub" opensource_description_center: "și ajută-ne dacă îți place! CodeCombat este construit peste o mulțime de proiecte open source, care noi le iubim. Vizitați" archmage_wiki_url: "Archmage wiki" opensource_description_suffix: "pentru o listă cu software-ul care face acest joc posibil." practices_title: "Convenții" practices_description: "Acestea sunt promisiunile noastre către tine, jucătorul, fără așa mulți termeni legali." privacy_title: "Confidenţialitate şi termeni" privacy_description: "Noi nu vom vinde nici o informație personală. Intenționăm să obținem profit prin recrutare eventual, dar stați liniștiți , nu vă vom vinde informațiile personale companiilor interesate fără consimțământul vostru explicit." security_title: "Securitate" security_description: "Ne străduim să vă protejăm informațiile personale. Fiind un proiect open-source, site-ul nostru oferă oricui posibilitatea de a ne revizui și îmbunătăți sistemul de securitate." email_title: "Email" email_description_prefix: "Noi nu vă vom inunda cu spam. Prin" email_settings_url: "setările tale de email" email_description_suffix: " sau prin link-urile din email-urile care vi le trimitem, puteți să schimbați preferințele și să vâ dezabonați oricând." cost_title: "Cost" cost_description: "Momentan, CodeCombat este 100% gratis! Unul dintre obiectele noastre principale este să îl menținem așa, astfel încât să poată juca cât mai mulți oameni. Dacă va fi nevoie , s-ar putea să percepem o plată pentru o pentru anumite servici,dar am prefera să nu o facem. Cu puțin noroc, vom putea susține compania cu:" recruitment_title: "Recrutare" recruitment_description_prefix: "Aici la CodeCombat, vei deveni un vrăjitor puternic nu doar în joc , ci și în viața reală." url_hire_programmers: "Nimeni nu poate angaja programatori destul de rapid" recruitment_description_suffix: "așa că odată ce ți-ai dezvoltat abilitățile și esti de acord, noi vom trimite un demo cu cele mai bune realizări ale tale către miile de angajatori care se omoară să pună mâna pe tine. Pe noi ne plătesc puțin, pe tine te vor plăti" recruitment_description_italic: "mult" recruitment_description_ending: "site-ul rămâne gratis și toată lumea este fericită. Acesta este planul." copyrights_title: "Drepturi de autor și licențe" contributor_title: "Acord de licență Contributor" contributor_description_prefix: "Toți contribuitorii, atât pe site cât și pe GitHub-ul nostru, sunt supuși la" cla_url: "ALC" contributor_description_suffix: "la care trebuie să fi de accord înainte să poți contribui." code_title: "Code - MIT" code_description_prefix: "Tot codul deținut de CodeCombat sau hostat pe codecombat.com, atât pe GitHub cât și în baza de date codecombat.com, este licențiată sub" mit_license_url: "MIT license" code_description_suffix: "Asta include tot codul din Systems și Components care este oferit de către CodeCombat cu scopul de a crea nivele." art_title: "Artă/Muzică - Conținut Comun " art_description_prefix: "Tot conținutul creativ/artistic este valabil sub" cc_license_url: "Creative Commons Attribution 4.0 International License" art_description_suffix: "Conținut comun este orice făcut general valabil de către CodeCombat cu scopul de a crea nivele. Asta include:" art_music: "Muzică" art_sound: "Sunet" art_artwork: "Artwork" art_sprites: "Sprites" art_other: "Orice si toate celelalte creații non-cod care sunt disponibile când se crează nivele." art_access: "Momentan nu există nici un sistem universal,ușor pentru preluarea acestor bunuri. În general, preluați-le precum site-ul din URL-urile folosite, contactați-ne pentru asistență, sau ajutați-ne sa extindem site-ul pentru a face aceste bunuri mai ușor accesibile." art_paragraph_1: "Pentru atribuire, vă rugăm numiți și lăsați referire link la codecombat.com unde este folosită sursa sau unde este adecvat pentru mediu. De exemplu:" use_list_1: "Dacă este folosit într-un film sau alt joc, includeți codecombat.com la credite." use_list_2: "Dacă este folosit pe un site, includeți un link in apropiere, de exemplu sub o imagine, sau in pagina generală de atribuiri unde menționați și alte Bunuri Creative și software open source folosit pe site. Ceva care face referință explicit la CodeCombat, precum o postare pe un blog care menționează CodeCombat, nu trebuie să facă o atribuire separată." art_paragraph_2: "Dacă conținutul folosit nu este creat de către CodeCombat ci de către un utilizator al codecombat.com,atunci faceți referință către ei, și urmăriți indicațiile de atribuire prevăzute în descrierea resursei dacă există." rights_title: "Drepturi rezervate" rights_desc: "Toate drepturile sunt rezervate pentru Nivele în sine. Asta include" rights_scripts: "Script-uri" rights_unit: "Configurații de unități" rights_description: "Descriere" rights_writings: "Scrieri" rights_media: "Media (sunete, muzică) și orice alt conținut creativ dezvoltat special pentru acel nivel care nu este valabil în mod normal pentru creat nivele." rights_clarification: "Pentru a clarifica, orice este valabil in Editorul de Nivele pentru scopul de a crea nivele se află sub CC,pe când conținutul creat cu Editorul de Nivele sau încărcat pentru a face nivelul nu se află." nutshell_title: "Pe scurt" nutshell_description: "Orice resurse vă punem la dispoziție în Editorul de Nivele puteți folosi liber cum vreți pentru a crea nivele. Dar ne rezervăm dreptul de a rezerva distribuția de nivele în sine (care sunt create pe codecombat.com) astfel încât să se poată percepe o taxă pentru ele pe vitor, dacă se va ajunge la așa ceva." canonical: "Versiunea in engleză a acestui document este cea definitivă, versiunea canonică. Dacă există orice discrepanțe între traduceri, documentul in engleză are prioritate." contribute: page_title: "Contribuțtii" character_classes_title: "Clase de caractere" introduction_desc_intro: "Avem speranțe mari pentru CodeCombat." introduction_desc_pref: "Vrem să fie locul unde programatori de toate rangurile vin să învețe și să se distreze împreună, introduc pe alții in minunata lume a programării, și reflectă cele mai bune părți ale comunității. Nu vrem și nu putem să facem asta singuri; ceea ce face proiectele precum GitHub, Stack Overflow și Linux geniale sunt oameni care le folosesc și construiec peste ele. Cu scopul acesta, " introduction_desc_github_url: "CodeCombat este complet open source" introduction_desc_suf: ", și ne propunem să vă punem la dispoziție pe cât de mult posibil modalități de a lua parte la acest proiect pentru a-l face la fel de mult as vostru cât și al nostru." introduction_desc_ending: "Sperăm să vă placă petrecerea noastră!" introduction_desc_signature: "- PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, și PI:NAME:<NAME>END_PI" alert_account_message_intro: "Salutare!" alert_account_message_pref: "Pentru a te abona la email-uri de clasă, va trebui să " alert_account_message_suf: "mai întâi." alert_account_message_create_url: "creați un cont" archmage_summary: "Interesat să lucrezi la grafica jocului, interfața grafică cu utilizatorul, baze de date și organizare server , multiplayer networking, fizică, sunet, sau performanțe game engine ? Vrei să ajuți la construirea unui joc pentru a învăța pe alții ceea ce te pricepi? Avem o grămadă de făcut dacă ești un programator experimentat și vrei sa dezvolți pentru CodeCombat, această clasă este pentru tine. Ne-ar plăcea să ne ajuți să construim cel mai bun joc de programare făcut vreodată." archmage_introduction: "Una dintre cele mai bune părți despre construirea unui joc este că sintetizează atât de multe lucruri diferite. Grafică, sunet, networking în timp real, social networking, și desigur multe dintre aspectele comune ale programării, de la gestiune low-level a bazelor de date , și administrare server până la construirea de interfețe. Este mult de muncă, și dacă ești un programator cu experiență, cu un dor de a se arunca cu capul înainte îm CodeCombat, această clasă ți se potrivește. Ne-ar plăcea să ne ajuți să construim cel mai bun joc de programare făcut vreodată." class_attributes: "Atribute pe clase" archmage_attribute_1_pref: "Cunoștințe în " archmage_attribute_1_suf: ", sau o dorință de a învăța. Majoritatea codului este în acest limbaj. Dacă ești fan Ruby sau Python, te vei simți ca acasă. Este JavaScript, dar cu o sintaxă mai frumoasă." archmage_attribute_2: "Ceva experiență în programare și inițiativă personală. Te vom ajuta să te orientezi, dar nu putem aloca prea mult timp pentru a te pregăti." how_to_join: "Cum să ni te alături" join_desc_1: "Oricine poate să ajute! Doar intrați pe " join_desc_2: "pentru a începe, și bifați căsuța de dedesubt pentru a te marca ca un Archmage curajos și pentru a primi ultimele știri pe email. Vrei să discuți despre ce să faci sau cum să te implici mai mult? " join_desc_3: ", sau găsește-ne în " join_desc_4: "și pornim de acolo!" join_url_email: "Trimite-ne Email" join_url_hipchat: "public HipChat room" more_about_archmage: "Învață mai multe despre cum să devi un Archmage" archmage_subscribe_desc: "Primește email-uri despre noi oportunități de progrmare și anunțuri." artisan_summary_pref: "Vrei să creezi nivele și să extinzi arsenalul CodeCombat? Oamenii ne termină nivelele mai repede decât putem să le creăm! Momentan, editorul nostru de nivele este rudimentar, așa că aveți grijă. Crearea de nivele va fi o mică provocare și va mai avea câteva bug-uri. Dacă ai viziuni cu campanii care cuprind loop-uri for pentru" artisan_summary_suf: "atunci asta e clasa pentru tine." artisan_introduction_pref: "Trebuie să construim nivele adiționale! Oamenii sunt nerăbdători pentru mai mult conținut, și noi putem face doar atât singuri. Momentan editorul de nivele abia este utilizabil până și de creatorii lui, așa că aveți grijă. Dacă ai viziuni cu campanii care cuprind loop-uri for pentru" artisan_introduction_suf: "atunci aceasta ar fi clasa pentru tine." artisan_attribute_1: "Orice experiență în crearea de conținut ca acesta ar fi de preferat, precum folosirea editoarelor de nivele de la Blizzard. Dar nu este obligatoriu!" artisan_attribute_2: "Un chef de a face o mulțime de teste și iterări. Pentru a face nivele bune, trebuie să testați pe mai mulți oameni și să obțineți feedback, și să fiți pregăți să reparați o mulțime de lucruri." artisan_attribute_3: "Pentru moment trebui să ai nervi de oțel. Editorul nostru de nivele este abia la început și încă are multe probleme. Ai fost avertizat!" artisan_join_desc: "Folosiți editorul de nivele urmărind acești pași , mai mult sau mai puțin:" artisan_join_step1: "Citește documentația." artisan_join_step2: "Crează un nivel nou și explorează nivelele deja existente." artisan_join_step3: "Găsește-ne pe chatul nostru de Hipchat pentru ajutor." artisan_join_step4: "Postează nivelele tale pe forum pentru feedback." more_about_artisan: "Învață mai multe despre ce înseamnă să devi un Artizan" artisan_subscribe_desc: "Primește email-uri despre update-uri legate de Editorul de Nivele și anunțuri." adventurer_summary: "Să fie clar ce implică rolul tău: tu ești tancul. Vei avea multe de îndurat. Avem nevoie de oameni care să testeze nivelele noi și să ne ajute să găsim moduri noi de a le îmbunătăți. Va fi greu; să creezi jocuri bune este un proces dificil și nimeni nu o face perfect din prima. Dacă crezi că poți îndura , atunci aceasta este clasa pentru tine." adventurer_introduction: "Să fie clar ce implică rolul tău: tu ești tancul. Vei avea multe de îndurat. Avem nevoie de oameni care să testeze nivelele noi și să ne ajute să găsim moduri noi de a le îmbunătăți. Va fi greu; să creezi jocuri bune este un proces dificil și nimeni nu o face perfect din prima. Dacă crezi că poți îndura , atunci aceasta este clasa pentru tine." adventurer_attribute_1: "O sete de cunoaștere. Tu vrei să înveți cum să programezi și noi vrem să te învățăm. Cel mai probabil tu vei fi cel care va preda mai mult în acest caz." adventurer_attribute_2: "Carismatic. Formulează într-un mod clar ceea ce trebuie îmbunătățit și oferă sugestii." adventurer_join_pref: "Ori fă echipă (sau recrutează!) cu un Artizan și lucrează cu el, sau bifează căsuța de mai jos pentru a primi email când sunt noi nivele de testat. De asemenea vom posta despre nivele care trebuiesc revizuite pe rețelele noastre precum" adventurer_forum_url: "forumul nostru" adventurer_join_suf: "deci dacă preferi să fi înștiințat în acele moduri ,înscrie-te acolo!" more_about_adventurer: "Învață mai multe despre ce înseamnă să devi un Aventurier" adventurer_subscribe_desc: "Primește email-uri când sunt noi nivele de testat." # scribe_summary_pref: "CodeCombat is not just going to be a bunch of levels. It will also be a resource of programming knowledge that players can hook into. That way, each Artisan can link to a detailed article that for the player's edification: documentation akin to what the " # scribe_summary_suf: " has built. If you enjoy explaining programming concepts, then this class is for you." # scribe_introduction_pref: "CodeCombat isn't just going to be a bunch of levels. It will also include a resource for knowledge, a wiki of programming concepts that levels can hook into. That way rather than each Artisan having to describe in detail what a comparison operator is, they can simply link their level to the Article describing them that is already written for the player's edification. Something along the lines of what the " # scribe_introduction_url_mozilla: "Mozilla Developer Network" # scribe_introduction_suf: " has built. If your idea of fun is articulating the concepts of programming in Markdown form, then this class might be for you." # scribe_attribute_1: "Skill in words is pretty much all you need. Not only grammar and spelling, but able to convey complicated ideas to others." # contact_us_url: "Contact us" # scribe_join_description: "tell us a little about yourself, your experience with programming and what sort of things you'd like to write about. We'll go from there!" # more_about_scribe: "Learn More About Becoming a Scribe" # scribe_subscribe_desc: "Get emails about article writing announcements." # diplomat_summary: "There is a large interest in CodeCombat in other countries that do not speak English! We are looking for translators who are willing to spend their time translating the site's corpus of words so that CodeCombat is accessible across the world as soon as possible. If you'd like to help getting CodeCombat international, then this class is for you." # diplomat_introduction_pref: "So, if there's one thing we learned from the " # diplomat_launch_url: "launch in October" # diplomat_introduction_suf: "it's that there is sizeable interest in CodeCombat in other countries! We're building a corps of translators eager to turn one set of words into another set of words to get CodeCombat as accessible across the world as possible. If you like getting sneak peeks at upcoming content and getting these levels to your fellow nationals ASAP, then this class might be for you." # diplomat_attribute_1: "Fluency in English and the language you would like to translate to. When conveying complicated ideas, it's important to have a strong grasp in both!" # diplomat_join_pref_github: "Find your language locale file " # diplomat_github_url: "on GitHub" # diplomat_join_suf_github: ", edit it online, and submit a pull request. Also, check this box below to keep up-to-date on new internationalization developments!" # more_about_diplomat: "Learn More About Becoming a Diplomat" # diplomat_subscribe_desc: "Get emails about i18n developments and levels to translate." # ambassador_summary: "We are trying to build a community, and every community needs a support team when there are troubles. We have got chats, emails, and social networks so that our users can get acquainted with the game. If you want to help people get involved, have fun, and learn some programming, then this class is for you." # ambassador_introduction: "This is a community we're building, and you are the connections. We've got Olark chats, emails, and social networks with lots of people to talk with and help get acquainted with the game and learn from. If you want to help people get involved and have fun, and get a good feel of the pulse of CodeCombat and where we're going, then this class might be for you." # ambassador_attribute_1: "Communication skills. Be able to identify the problems players are having and help them solve them. Also, keep the rest of us informed about what players are saying, what they like and don't like and want more of!" # ambassador_join_desc: "tell us a little about yourself, what you've done and what you'd be interested in doing. We'll go from there!" # ambassador_join_note_strong: "Note" # ambassador_join_note_desc: "One of our top priorities is to build multiplayer where players having difficulty solving levels can summon higher level wizards to help them. This will be a great way for ambassadors to do their thing. We'll keep you posted!" # more_about_ambassador: "Learn More About Becoming an Ambassador" # ambassador_subscribe_desc: "Get emails on support updates and multiplayer developments." # counselor_summary: "None of the above roles fit what you are interested in? Do not worry, we are on the lookout for anybody who wants a hand in the development of CodeCombat! If you are interested in teaching, game development, open source management, or anything else that you think will be relevant to us, then this class is for you." # counselor_introduction_1: "Do you have life experience? A different perspective on things that can help us decide how to shape CodeCombat? Of all these roles, this will probably take the least time, but individually you may make the most difference. We're on the lookout for wisened sages, particularly in areas like: teaching, game development, open source project management, technical recruiting, entrepreneurship, or design." # counselor_introduction_2: "Or really anything that is relevant to the development of CodeCombat. If you have knowledge and want to share it to help grow this project, then this class might be for you." # counselor_attribute_1: "Experience, in any of the areas above or something you think might be helpful." # counselor_attribute_2: "A little bit of free time!" # counselor_join_desc: "tell us a little about yourself, what you've done and what you'd be interested in doing. We'll put you in our contact list and be in touch when we could use advice (not too often)." more_about_counselor: "Află mai multe despre ce înseamna să devi Consilier" changes_auto_save: "Modificările sunt salvate automat când apeși checkbox-uri." diligent_scribes: "Scribii noștri:" powerful_archmages: "Bravii noștri Archmage:" creative_artisans: "Artizanii noștri creativi:" brave_adventurers: "Aventurierii noștri neînfricați:" translating_diplomats: "Diplomații noștri abili:" helpful_ambassadors: "Ambasadorii noștri de ajutor:" classes: archmage_title: "Archmage" archmage_title_description: "(Programator)" artisan_title: "Artizan" artisan_title_description: "(Creator de nivele)" adventurer_title: "Aventurier" adventurer_title_description: "(Playtester de nivele)" scribe_title: "Scrib" scribe_title_description: "(Editor de articole)" diplomat_title: "Diplomat" diplomat_title_description: "(Translator)" ambassador_title: "Ambasador" ambassador_title_description: "(Suport)" counselor_title: "Consilier" counselor_title_description: "(Expert/Profesor)" ladder: please_login: "Vă rugăm să vă autentificați înainte de a juca un meci de clasament." my_matches: "Jocurile mele" simulate: "Simulează" simulation_explanation: "Simulând jocuri poți afla poziția în clasament a jocului tău mai repede!" simulate_games: "Simulează Jocuri!" simulate_all: "RESETEAZĂ ȘI SIMULEAZĂ JOCURI" leaderboard: "Clasament" battle_as: "Luptă ca " summary_your: "Al tău " summary_matches: "Meciuri - " summary_wins: " Victorii, " summary_losses: " Înfrângeri" rank_no_code: "Nici un Cod nou pentru Clasament" rank_my_game: "Plasează-mi jocul in Clasament!" rank_submitting: "Se trimite..." rank_submitted: "Se trimite pentru Clasament" rank_failed: "A eșuat plasarea in clasament" rank_being_ranked: "Jocul se plasează in Clasament" code_being_simulated: "Codul tău este simulat de alți jucători pentru clasament. Se va actualiza cum apar meciuri." no_ranked_matches_pre: "Nici un meci de clasament pentru " no_ranked_matches_post: " echipă! Joacă împotriva unor concurenți și revino apoi aici pentr a-ți plasa meciul in clasament." choose_opponent: "Alege un adversar" tutorial_play: "Joacă Tutorial-ul" tutorial_recommended: "Recomandat dacă nu ai mai jucat niciodată înainte" tutorial_skip: "Sari peste Tutorial" tutorial_not_sure: "Nu ești sigur ce se întâmplă?" tutorial_play_first: "Joacă Tutorial-ul mai întâi." simple_ai: "AI simplu" warmup: "Încălzire" vs: "VS" # multiplayer_launch: # introducing_dungeon_arena: "Introducing Dungeon Arena" # new_way: "March 17, 2014: The new way to compete with code." # to_battle: "To Battle, Developers!" # modern_day_sorcerer: "You know how to code? That's badass. You're a modern-day sorcerer! Isn't about time that you used your magic coding powers to command your minions in epic combat? And we're not talking robots here." # arenas_are_here: "CodeCombat head-to-head multiplayer arenas are here." # ladder_explanation: "Choose your heroes, enchant your human or ogre armies, and climb your way over defeated fellow Wizards to reach the top of the ladders–then challenge your friends in our glorious, asynchronous multiplayer coding arenas. If you're feeling creative, you can even" # fork_our_arenas: "fork our arenas" # create_worlds: "and create your own worlds." # javascript_rusty: "JavaScript a bit rusty? Don't worry; there's a" # tutorial: "tutorial" # new_to_programming: ". New to programming? Hit our beginner campaign to skill up." # so_ready: "I Am So Ready for This"
[ { "context": "ored data when required\n#\n# adapted from a post by Dustin Sallings (@dustin on GitHub)\n# http://dustin.sallings.org/", "end": 431, "score": 0.9998815655708313, "start": 416, "tag": "NAME", "value": "Dustin Sallings" }, { "context": "equired\n#\n# adapted from a post by Dustin Sallings (@dustin on GitHub)\n# http://dustin.sallings.org/2011/02/1", "end": 440, "score": 0.9995995163917542, "start": 432, "tag": "USERNAME", "value": "(@dustin" } ]
src/mc-array.coffee
mgduk/mc-array
0
Promise = require 'bluebird' # This module allows arrays of values to be stored in memcached # # Features include # - values can be added and removed from the array with a single append call # - doesn't require full set of values to be fetched to add or remove values # - no locks are required to add/remove # - automatically garbage collects to compact the stored data when required # # adapted from a post by Dustin Sallings (@dustin on GitHub) # http://dustin.sallings.org/2011/02/17/memcached-set.html # class mc_array # the number of redundant values to allow before the array # is compacted GARBAGE_THRESHOLD: 50 # using characters that aren't in base64 ADD_OP: '*' REMOVE_OP: '-' # Requires an instance of mc.Client from the 'mc' memcache package # key is the string key under which data is stored in memcache constructor: (@cache, @key) -> # convert nodeback-style methods to return promises @cache[func] = Promise.promisify @cache[func] for func in ['append', 'set', 'gets', 'cas'] # Encode an array of values to modify the set. # # encodeSet ['a', 'b', 'c'] # => '*a *b *c ' # encodeSet: (values, op = @ADD_OP) -> values = for v in values when v # JSON encode then base64 encode b = new Buffer JSON.stringify v op + b.toString('base64') + ' ' values.join '' # Decode a cached string into an array of strings # # Also returns a garbage count indicating how many items in the # stored data are now redundant. # # decodeSet '*a *b *c -b -x' # => { garbage: 2, values: ['a', 'c'] } # decodeSet: (s) -> values = [] garbage = 0 if s and typeof s is 'string' tokens = s.split ' ' for token in tokens when token isnt '' op = token[0] value = token.substring(1) # for now, we handle them as base64 strings so we can # compare them easily if op is @ADD_OP values.push value else if op is @REMOVE_OP position = values.indexOf value # remove value from array values.splice position, 1 unless position is -1 garbage++ # decode the values values = for value in values b = new Buffer value, 'base64' JSON.parse b.toString() garbage: garbage, values: values # returns a promise that resolves to a boolean indicating store success modify: (op, values) => encoded = @encodeSet values, op @cache.append @key, encoded .catch (e) => e.type .then (status) => # item removed from empty value is successful as # the item is not there if status is 'STORED' or op isnt @ADD_OP return true # If we can't append, and we're adding to the set, # we are trying to create the index, so do that. else return @cache.set @key, encoded .then (status) -> return status is 'STORED' # Add the given value or array of values to the given array # # string|array values # Returns a promise that resolves to a success boolean add: (values) => values = [values] unless Array.isArray values @modify @ADD_OP, values # Remove the given value or array of values from the given array # # string|array values # Returns a promise that resolves to a success boolean remove: (values) => values = [values] unless Array.isArray values @modify @REMOVE_OP, values # Retrieve the current values from the set. # This may trigger compacting if you ask it to or the encoding is # too dirty. # # Returns a promise that resolves to an array of strings get: (forceCompacting = false) => @cache.gets @key .catch (err) => return [] .then (response) => return [] unless response?[@key] # 'cas' is the 'check and store' ID, to ensure # we only write back if no other client has written # to this key in the meantime {cas, val: data} = response[@key] {garbage, values} = @decodeSet data if forceCompacting or garbage > @GARBAGE_THRESHOLD compacted = @encodeSet values # hit and hope — worst case is that the value remains # uncompacted until next time @cache.cas @key, cas, compacted return values module.exports = mc_array
172291
Promise = require 'bluebird' # This module allows arrays of values to be stored in memcached # # Features include # - values can be added and removed from the array with a single append call # - doesn't require full set of values to be fetched to add or remove values # - no locks are required to add/remove # - automatically garbage collects to compact the stored data when required # # adapted from a post by <NAME> (@dustin on GitHub) # http://dustin.sallings.org/2011/02/17/memcached-set.html # class mc_array # the number of redundant values to allow before the array # is compacted GARBAGE_THRESHOLD: 50 # using characters that aren't in base64 ADD_OP: '*' REMOVE_OP: '-' # Requires an instance of mc.Client from the 'mc' memcache package # key is the string key under which data is stored in memcache constructor: (@cache, @key) -> # convert nodeback-style methods to return promises @cache[func] = Promise.promisify @cache[func] for func in ['append', 'set', 'gets', 'cas'] # Encode an array of values to modify the set. # # encodeSet ['a', 'b', 'c'] # => '*a *b *c ' # encodeSet: (values, op = @ADD_OP) -> values = for v in values when v # JSON encode then base64 encode b = new Buffer JSON.stringify v op + b.toString('base64') + ' ' values.join '' # Decode a cached string into an array of strings # # Also returns a garbage count indicating how many items in the # stored data are now redundant. # # decodeSet '*a *b *c -b -x' # => { garbage: 2, values: ['a', 'c'] } # decodeSet: (s) -> values = [] garbage = 0 if s and typeof s is 'string' tokens = s.split ' ' for token in tokens when token isnt '' op = token[0] value = token.substring(1) # for now, we handle them as base64 strings so we can # compare them easily if op is @ADD_OP values.push value else if op is @REMOVE_OP position = values.indexOf value # remove value from array values.splice position, 1 unless position is -1 garbage++ # decode the values values = for value in values b = new Buffer value, 'base64' JSON.parse b.toString() garbage: garbage, values: values # returns a promise that resolves to a boolean indicating store success modify: (op, values) => encoded = @encodeSet values, op @cache.append @key, encoded .catch (e) => e.type .then (status) => # item removed from empty value is successful as # the item is not there if status is 'STORED' or op isnt @ADD_OP return true # If we can't append, and we're adding to the set, # we are trying to create the index, so do that. else return @cache.set @key, encoded .then (status) -> return status is 'STORED' # Add the given value or array of values to the given array # # string|array values # Returns a promise that resolves to a success boolean add: (values) => values = [values] unless Array.isArray values @modify @ADD_OP, values # Remove the given value or array of values from the given array # # string|array values # Returns a promise that resolves to a success boolean remove: (values) => values = [values] unless Array.isArray values @modify @REMOVE_OP, values # Retrieve the current values from the set. # This may trigger compacting if you ask it to or the encoding is # too dirty. # # Returns a promise that resolves to an array of strings get: (forceCompacting = false) => @cache.gets @key .catch (err) => return [] .then (response) => return [] unless response?[@key] # 'cas' is the 'check and store' ID, to ensure # we only write back if no other client has written # to this key in the meantime {cas, val: data} = response[@key] {garbage, values} = @decodeSet data if forceCompacting or garbage > @GARBAGE_THRESHOLD compacted = @encodeSet values # hit and hope — worst case is that the value remains # uncompacted until next time @cache.cas @key, cas, compacted return values module.exports = mc_array
true
Promise = require 'bluebird' # This module allows arrays of values to be stored in memcached # # Features include # - values can be added and removed from the array with a single append call # - doesn't require full set of values to be fetched to add or remove values # - no locks are required to add/remove # - automatically garbage collects to compact the stored data when required # # adapted from a post by PI:NAME:<NAME>END_PI (@dustin on GitHub) # http://dustin.sallings.org/2011/02/17/memcached-set.html # class mc_array # the number of redundant values to allow before the array # is compacted GARBAGE_THRESHOLD: 50 # using characters that aren't in base64 ADD_OP: '*' REMOVE_OP: '-' # Requires an instance of mc.Client from the 'mc' memcache package # key is the string key under which data is stored in memcache constructor: (@cache, @key) -> # convert nodeback-style methods to return promises @cache[func] = Promise.promisify @cache[func] for func in ['append', 'set', 'gets', 'cas'] # Encode an array of values to modify the set. # # encodeSet ['a', 'b', 'c'] # => '*a *b *c ' # encodeSet: (values, op = @ADD_OP) -> values = for v in values when v # JSON encode then base64 encode b = new Buffer JSON.stringify v op + b.toString('base64') + ' ' values.join '' # Decode a cached string into an array of strings # # Also returns a garbage count indicating how many items in the # stored data are now redundant. # # decodeSet '*a *b *c -b -x' # => { garbage: 2, values: ['a', 'c'] } # decodeSet: (s) -> values = [] garbage = 0 if s and typeof s is 'string' tokens = s.split ' ' for token in tokens when token isnt '' op = token[0] value = token.substring(1) # for now, we handle them as base64 strings so we can # compare them easily if op is @ADD_OP values.push value else if op is @REMOVE_OP position = values.indexOf value # remove value from array values.splice position, 1 unless position is -1 garbage++ # decode the values values = for value in values b = new Buffer value, 'base64' JSON.parse b.toString() garbage: garbage, values: values # returns a promise that resolves to a boolean indicating store success modify: (op, values) => encoded = @encodeSet values, op @cache.append @key, encoded .catch (e) => e.type .then (status) => # item removed from empty value is successful as # the item is not there if status is 'STORED' or op isnt @ADD_OP return true # If we can't append, and we're adding to the set, # we are trying to create the index, so do that. else return @cache.set @key, encoded .then (status) -> return status is 'STORED' # Add the given value or array of values to the given array # # string|array values # Returns a promise that resolves to a success boolean add: (values) => values = [values] unless Array.isArray values @modify @ADD_OP, values # Remove the given value or array of values from the given array # # string|array values # Returns a promise that resolves to a success boolean remove: (values) => values = [values] unless Array.isArray values @modify @REMOVE_OP, values # Retrieve the current values from the set. # This may trigger compacting if you ask it to or the encoding is # too dirty. # # Returns a promise that resolves to an array of strings get: (forceCompacting = false) => @cache.gets @key .catch (err) => return [] .then (response) => return [] unless response?[@key] # 'cas' is the 'check and store' ID, to ensure # we only write back if no other client has written # to this key in the meantime {cas, val: data} = response[@key] {garbage, values} = @decodeSet data if forceCompacting or garbage > @GARBAGE_THRESHOLD compacted = @encodeSet values # hit and hope — worst case is that the value remains # uncompacted until next time @cache.cas @key, cas, compacted return values module.exports = mc_array
[ { "context": " DOM.input\n name: 'userName'\n initialValue: @props.userName\n", "end": 648, "score": 0.994084358215332, "start": 640, "tag": "USERNAME", "value": "userName" }, { "context": " DOM.input\n type: 'password'\n name: 'password'\n ", "end": 902, "score": 0.9102686047554016, "start": 894, "tag": "PASSWORD", "value": "password" }, { "context": " type: 'password'\n name: 'password'\n , ''\n DOM.tr null,\n ", "end": 937, "score": 0.9505267143249512, "start": 929, "tag": "PASSWORD", "value": "password" } ]
src/components/login.coffee
brianshaler/kerplunk-admin
0
React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass render: -> DOM.section className: 'content login-form' , DOM.h1 null, 'Login!' DOM.p null, DOM.form method: 'post' action: '/admin/login' , DOM.input type: 'hidden' name: 'redirectUrl' defaultValue: @props.redirectUrl , '' DOM.table null, DOM.tr null, DOM.td null, DOM.strong null, 'User name:' DOM.td null, DOM.input name: 'userName' initialValue: @props.userName , '' DOM.tr null, DOM.td null, DOM.strong null, 'Password:' DOM.td null, DOM.input type: 'password' name: 'password' , '' DOM.tr null, DOM.td null, '' DOM.td null, DOM.input type: 'submit' value: 'Login' , ''
167514
React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass render: -> DOM.section className: 'content login-form' , DOM.h1 null, 'Login!' DOM.p null, DOM.form method: 'post' action: '/admin/login' , DOM.input type: 'hidden' name: 'redirectUrl' defaultValue: @props.redirectUrl , '' DOM.table null, DOM.tr null, DOM.td null, DOM.strong null, 'User name:' DOM.td null, DOM.input name: 'userName' initialValue: @props.userName , '' DOM.tr null, DOM.td null, DOM.strong null, 'Password:' DOM.td null, DOM.input type: '<PASSWORD>' name: '<PASSWORD>' , '' DOM.tr null, DOM.td null, '' DOM.td null, DOM.input type: 'submit' value: 'Login' , ''
true
React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass render: -> DOM.section className: 'content login-form' , DOM.h1 null, 'Login!' DOM.p null, DOM.form method: 'post' action: '/admin/login' , DOM.input type: 'hidden' name: 'redirectUrl' defaultValue: @props.redirectUrl , '' DOM.table null, DOM.tr null, DOM.td null, DOM.strong null, 'User name:' DOM.td null, DOM.input name: 'userName' initialValue: @props.userName , '' DOM.tr null, DOM.td null, DOM.strong null, 'Password:' DOM.td null, DOM.input type: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'PI:PASSWORD:<PASSWORD>END_PI' , '' DOM.tr null, DOM.td null, '' DOM.td null, DOM.input type: 'submit' value: 'Login' , ''
[ { "context": " = @slackbot.robot\n @slackbot.options.token = \"ABC123\"\n @slackbot.run() -\n logger.logs[\"error\"", "end": 783, "score": 0.7577043175697327, "start": 780, "tag": "KEY", "value": "ABC" }, { "context": "@slackbot.robot\n @slackbot.options.token = \"ABC123\"\n @slackbot.run() -\n logger.logs[\"error\"].l", "end": 786, "score": 0.7530770301818848, "start": 783, "tag": "PASSWORD", "value": "123" }, { "context": " @client.send {room: 'name'}, {text: 'foo', user: @stubs.user, channel: @stubs.channel}\n @stubs._opts.as_use", "end": 1960, "score": 0.98858642578125, "start": 1949, "tag": "USERNAME", "value": "@stubs.user" }, { "context": " @client.send {room: 'name'}, {text: 'foo', user: @stubs.user, channel: @stubs.channel, as_user: false}\n @st", "end": 2151, "score": 0.9902082085609436, "start": 2140, "tag": "USERNAME", "value": "@stubs.user" }, { "context": "nel', ->\n sentMessages = @slackbot.reply {user: @stubs.user, room: @stubs.channel.id}, 'message'\n sentMess", "end": 2387, "score": 0.991040825843811, "start": 2376, "tag": "USERNAME", "value": "@stubs.user" }, { "context": "nel', ->\n sentMessages = @slackbot.reply {user: @stubs.user, room: @stubs.channel.id}, 'one', 'two', 'three'\n", "end": 2656, "score": 0.989874005317688, "start": 2645, "tag": "USERNAME", "value": "@stubs.user" }, { "context": "id}>: one\"\n sentMessages[1].should.equal \"<@#{@stubs.user.id}>: two\"\n sentMessages[2].should.equal ", "end": 2850, "score": 0.5507698059082031, "start": 2845, "tag": "USERNAME", "value": "stubs" }, { "context": "pty', ->\n sentMessages = @slackbot.reply {user: @stubs.user, room: @stubs.channel.id}, ''\n sentMessages.le", "end": 3037, "score": 0.9897250533103943, "start": 3026, "tag": "USERNAME", "value": "@stubs.user" }, { "context": " DM', ->\n sentMessages = @slackbot.reply {user: @stubs.user, room: 'D123'}, 'message'\n sentMessages.length", "end": 3224, "score": 0.9920238852500916, "start": 3213, "tag": "USERNAME", "value": "@stubs.user" }, { "context": " @slackbot.teamJoin {type: 'team_join', user: '1234'}\n @hit.should.equal true\n\ndescribe 'Handling ", "end": 4210, "score": 0.8070003390312195, "start": 4207, "tag": "USERNAME", "value": "234" }, { "context": "med', ->\n @slackbot.message {text: 'foo', user: @stubs.user, channel: @stubs.channel}\n @stubs._received.te", "end": 4399, "score": 0.9572912454605103, "start": 4388, "tag": "USERNAME", "value": "@stubs.user" }, { "context": " DM', ->\n @slackbot.message {text: 'foo', user: @stubs.user, channel: @stubs.DM}\n @stubs._received.text.sh", "end": 4597, "score": 0.9504859447479248, "start": 4586, "tag": "USERNAME", "value": "@stubs.user" }, { "context": " @slackbot.message {subtype: 'channel_join', user: @stubs.user, channel: @stubs.channel}\n should.equal (@stub", "end": 4813, "score": 0.9418613910675049, "start": 4802, "tag": "USERNAME", "value": "@stubs.user" }, { "context": "@slackbot.message {subtype: 'channel_leave', user: @stubs.user, channel: @stubs.channel}\n should.equal (@stub", "end": 5090, "score": 0.9553917646408081, "start": 5079, "tag": "USERNAME", "value": "@stubs.user" }, { "context": "@slackbot.message {subtype: 'channel_topic', user: @stubs.user, channel: @stubs.channel}\n should.equal (@stub", "end": 5367, "score": 0.9771260023117065, "start": 5356, "tag": "USERNAME", "value": "@stubs.user" }, { "context": " @slackbot.message {subtype: 'group_join', user: @stubs.user, channel: @stubs.channel}\n should.equal (@stub", "end": 5638, "score": 0.9326233267784119, "start": 5627, "tag": "USERNAME", "value": "@stubs.user" }, { "context": " @slackbot.message {subtype: 'group_leave', user: @stubs.user, channel: @stubs.channel}\n should.equal (@stub", "end": 5911, "score": 0.9724953770637512, "start": 5900, "tag": "USERNAME", "value": "@stubs.user" }, { "context": ", true\n @stubs._received.user.id.should.equal @stubs.user.id\n\n it 'Should handle group_topic events a", "end": 6052, "score": 0.587240993976593, "start": 6047, "tag": "USERNAME", "value": "stubs" }, { "context": " @slackbot.message {subtype: 'group_topic', user: @stubs.user, channel: @stubs.channel}\n should.equal (@stub", "end": 6184, "score": 0.9621144533157349, "start": 6173, "tag": "USERNAME", "value": "@stubs.user" }, { "context": "\n @slackbot.message {subtype: 'hidey_ho', user: @stubs.user, channel: @stubs.channel}\n should.equal (@stub", "end": 6449, "score": 0.983501136302948, "start": 6438, "tag": "USERNAME", "value": "@stubs.user" }, { "context": "kbot.message { subtype: 'bot_message', bot: @stubs.bot, channel: @stubs.channel, text: 'Pushing is the a", "end": 6655, "score": 0.5444936156272888, "start": 6652, "tag": "USERNAME", "value": "bot" }, { "context": " @slackbot.message { subtype: 'bot_message', user: @stubs.self, channel: @stubs.channel, text: 'Ignore me' }\n ", "end": 6894, "score": 0.9431565999984741, "start": 6883, "tag": "USERNAME", "value": "@stubs.self" }, { "context": " @slackbot.message { subtype: 'bot_message', bot: @stubs.self_bot, channel: @stubs.channel, text: 'Ignore me' }\n ", "end": 7126, "score": 0.9644875526428223, "start": 7111, "tag": "USERNAME", "value": "@stubs.self_bot" } ]
test/bot.coffee
EdtechFoundry/hubot-slack
0
should = require 'should' {Adapter, TextMessage, EnterMessage, LeaveMessage, TopicMessage, Message, CatchAllMessage} = require.main.require 'hubot' describe 'Adapter', -> it 'Should initialize with a robot', -> @slackbot.robot.should.eql @stubs.robot describe 'Login', -> it 'Should set the robot name', -> @slackbot.robot.name.should.equal 'bot' describe 'Logger', -> it 'It should log missing token error', -> {logger} = @slackbot.robot @slackbot.options.token = null @slackbot.run() logger.logs["error"].length.should.be.above(0) logger.logs["error"][logger.logs["error"].length-1].should.equal 'No service token provided to Hubot' it 'It should log invalid token error', -> {logger} = @slackbot.robot @slackbot.options.token = "ABC123" @slackbot.run() - logger.logs["error"].length.should.be.above(0) logger.logs["error"][logger.logs["error"].length-1].should.equal 'Invalid service token provided, please follow the upgrade instructions' describe 'Send Messages', -> it 'Should send a message', -> sentMessages = @slackbot.send {room: 'general'}, 'message' sentMessages.length.should.equal 1 sentMessages[0].should.equal 'message' it 'Should send multiple messages', -> sentMessages = @slackbot.send {room: 'general'}, 'one', 'two', 'three' sentMessages.length.should.equal 3 it 'Should not send empty messages', -> sentMessages = @slackbot.send {room: 'general'}, 'Hello', '', '', 'world!' sentMessages.length.should.equal 2 it 'Should open a DM channel if needed', -> msg = 'Test' @slackbot.send {room: 'name'}, msg @stubs._msg.should.eql 'Test' it 'Should use an existing DM channel if possible', -> msg = 'Test' @slackbot.send {room: 'user2'}, msg @stubs._dmmsg.should.eql 'Test' describe 'Client sending message', -> it 'Should append as_user = true', -> @client.send {room: 'name'}, {text: 'foo', user: @stubs.user, channel: @stubs.channel} @stubs._opts.as_user.should.eql true it 'Should append as_user = true only as a default', -> @client.send {room: 'name'}, {text: 'foo', user: @stubs.user, channel: @stubs.channel, as_user: false} @stubs._opts.as_user.should.eql false describe 'Reply to Messages', -> it 'Should mention the user in a reply sent in a channel', -> sentMessages = @slackbot.reply {user: @stubs.user, room: @stubs.channel.id}, 'message' sentMessages.length.should.equal 1 sentMessages[0].should.equal "<@#{@stubs.user.id}>: message" it 'Should mention the user in multiple replies sent in a channel', -> sentMessages = @slackbot.reply {user: @stubs.user, room: @stubs.channel.id}, 'one', 'two', 'three' sentMessages.length.should.equal 3 sentMessages[0].should.equal "<@#{@stubs.user.id}>: one" sentMessages[1].should.equal "<@#{@stubs.user.id}>: two" sentMessages[2].should.equal "<@#{@stubs.user.id}>: three" it 'Should send nothing if messages are empty', -> sentMessages = @slackbot.reply {user: @stubs.user, room: @stubs.channel.id}, '' sentMessages.length.should.equal 0 it 'Should NOT mention the user in a reply sent in a DM', -> sentMessages = @slackbot.reply {user: @stubs.user, room: 'D123'}, 'message' sentMessages.length.should.equal 1 sentMessages[0].should.equal "message" describe 'Setting the channel topic', -> it 'Should set the topic in channels', -> @slackbot.topic {room: @stubs.channel.id}, 'channel' @stubs._topic.should.equal 'channel' it 'Should NOT set the topic in DMs', -> @slackbot.topic {room: 'D1232'}, 'DM' should.not.exists(@stubs._topic) describe 'Receiving an error event', -> it 'Should propogate that error', -> @hit = false @slackbot.robot.on 'error', (error) => error.msg.should.equal 'ohno' @hit = true @hit.should.equal false @slackbot.error {msg: 'ohno', code: -2} @hit.should.equal true describe 'Receiving a team_join event', -> it 'Should propagate that event', -> @hit = false @slackbot.robot.on 'team_join', (user) => user.should.equal '1234' @hit = true @hit.should.equal false @slackbot.teamJoin {type: 'team_join', user: '1234'} @hit.should.equal true describe 'Handling incoming messages', -> it 'Should handle regular messages as hoped and dreamed', -> @slackbot.message {text: 'foo', user: @stubs.user, channel: @stubs.channel} @stubs._received.text.should.equal 'foo' it 'Should prepend our name to a message addressed to us in a DM', -> @slackbot.message {text: 'foo', user: @stubs.user, channel: @stubs.DM} @stubs._received.text.should.equal "#{@slackbot.robot.name} foo" it 'Should handle channel_join events as envisioned', -> @slackbot.message {subtype: 'channel_join', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof EnterMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle channel_leave events as envisioned', -> @slackbot.message {subtype: 'channel_leave', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof LeaveMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle channel_topic events as envisioned', -> @slackbot.message {subtype: 'channel_topic', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof TopicMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle group_join events as envisioned', -> @slackbot.message {subtype: 'group_join', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof EnterMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle group_leave events as envisioned', -> @slackbot.message {subtype: 'group_leave', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof LeaveMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle group_topic events as envisioned', -> @slackbot.message {subtype: 'group_topic', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof TopicMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle unknown events as catchalls', -> @slackbot.message {subtype: 'hidey_ho', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof CatchAllMessage), true it 'Should not crash with bot messages', -> @slackbot.message { subtype: 'bot_message', bot: @stubs.bot, channel: @stubs.channel, text: 'Pushing is the answer' } should.equal (@stubs._received instanceof TextMessage), true it 'Should ignore messages it sent itself', -> @slackbot.message { subtype: 'bot_message', user: @stubs.self, channel: @stubs.channel, text: 'Ignore me' } should.equal @stubs._received, undefined it 'Should ignore messages it sent itself, if sent as a botuser', -> @slackbot.message { subtype: 'bot_message', bot: @stubs.self_bot, channel: @stubs.channel, text: 'Ignore me' } should.equal @stubs._received, undefined
219421
should = require 'should' {Adapter, TextMessage, EnterMessage, LeaveMessage, TopicMessage, Message, CatchAllMessage} = require.main.require 'hubot' describe 'Adapter', -> it 'Should initialize with a robot', -> @slackbot.robot.should.eql @stubs.robot describe 'Login', -> it 'Should set the robot name', -> @slackbot.robot.name.should.equal 'bot' describe 'Logger', -> it 'It should log missing token error', -> {logger} = @slackbot.robot @slackbot.options.token = null @slackbot.run() logger.logs["error"].length.should.be.above(0) logger.logs["error"][logger.logs["error"].length-1].should.equal 'No service token provided to Hubot' it 'It should log invalid token error', -> {logger} = @slackbot.robot @slackbot.options.token = "<KEY> <PASSWORD>" @slackbot.run() - logger.logs["error"].length.should.be.above(0) logger.logs["error"][logger.logs["error"].length-1].should.equal 'Invalid service token provided, please follow the upgrade instructions' describe 'Send Messages', -> it 'Should send a message', -> sentMessages = @slackbot.send {room: 'general'}, 'message' sentMessages.length.should.equal 1 sentMessages[0].should.equal 'message' it 'Should send multiple messages', -> sentMessages = @slackbot.send {room: 'general'}, 'one', 'two', 'three' sentMessages.length.should.equal 3 it 'Should not send empty messages', -> sentMessages = @slackbot.send {room: 'general'}, 'Hello', '', '', 'world!' sentMessages.length.should.equal 2 it 'Should open a DM channel if needed', -> msg = 'Test' @slackbot.send {room: 'name'}, msg @stubs._msg.should.eql 'Test' it 'Should use an existing DM channel if possible', -> msg = 'Test' @slackbot.send {room: 'user2'}, msg @stubs._dmmsg.should.eql 'Test' describe 'Client sending message', -> it 'Should append as_user = true', -> @client.send {room: 'name'}, {text: 'foo', user: @stubs.user, channel: @stubs.channel} @stubs._opts.as_user.should.eql true it 'Should append as_user = true only as a default', -> @client.send {room: 'name'}, {text: 'foo', user: @stubs.user, channel: @stubs.channel, as_user: false} @stubs._opts.as_user.should.eql false describe 'Reply to Messages', -> it 'Should mention the user in a reply sent in a channel', -> sentMessages = @slackbot.reply {user: @stubs.user, room: @stubs.channel.id}, 'message' sentMessages.length.should.equal 1 sentMessages[0].should.equal "<@#{@stubs.user.id}>: message" it 'Should mention the user in multiple replies sent in a channel', -> sentMessages = @slackbot.reply {user: @stubs.user, room: @stubs.channel.id}, 'one', 'two', 'three' sentMessages.length.should.equal 3 sentMessages[0].should.equal "<@#{@stubs.user.id}>: one" sentMessages[1].should.equal "<@#{@stubs.user.id}>: two" sentMessages[2].should.equal "<@#{@stubs.user.id}>: three" it 'Should send nothing if messages are empty', -> sentMessages = @slackbot.reply {user: @stubs.user, room: @stubs.channel.id}, '' sentMessages.length.should.equal 0 it 'Should NOT mention the user in a reply sent in a DM', -> sentMessages = @slackbot.reply {user: @stubs.user, room: 'D123'}, 'message' sentMessages.length.should.equal 1 sentMessages[0].should.equal "message" describe 'Setting the channel topic', -> it 'Should set the topic in channels', -> @slackbot.topic {room: @stubs.channel.id}, 'channel' @stubs._topic.should.equal 'channel' it 'Should NOT set the topic in DMs', -> @slackbot.topic {room: 'D1232'}, 'DM' should.not.exists(@stubs._topic) describe 'Receiving an error event', -> it 'Should propogate that error', -> @hit = false @slackbot.robot.on 'error', (error) => error.msg.should.equal 'ohno' @hit = true @hit.should.equal false @slackbot.error {msg: 'ohno', code: -2} @hit.should.equal true describe 'Receiving a team_join event', -> it 'Should propagate that event', -> @hit = false @slackbot.robot.on 'team_join', (user) => user.should.equal '1234' @hit = true @hit.should.equal false @slackbot.teamJoin {type: 'team_join', user: '1234'} @hit.should.equal true describe 'Handling incoming messages', -> it 'Should handle regular messages as hoped and dreamed', -> @slackbot.message {text: 'foo', user: @stubs.user, channel: @stubs.channel} @stubs._received.text.should.equal 'foo' it 'Should prepend our name to a message addressed to us in a DM', -> @slackbot.message {text: 'foo', user: @stubs.user, channel: @stubs.DM} @stubs._received.text.should.equal "#{@slackbot.robot.name} foo" it 'Should handle channel_join events as envisioned', -> @slackbot.message {subtype: 'channel_join', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof EnterMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle channel_leave events as envisioned', -> @slackbot.message {subtype: 'channel_leave', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof LeaveMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle channel_topic events as envisioned', -> @slackbot.message {subtype: 'channel_topic', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof TopicMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle group_join events as envisioned', -> @slackbot.message {subtype: 'group_join', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof EnterMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle group_leave events as envisioned', -> @slackbot.message {subtype: 'group_leave', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof LeaveMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle group_topic events as envisioned', -> @slackbot.message {subtype: 'group_topic', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof TopicMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle unknown events as catchalls', -> @slackbot.message {subtype: 'hidey_ho', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof CatchAllMessage), true it 'Should not crash with bot messages', -> @slackbot.message { subtype: 'bot_message', bot: @stubs.bot, channel: @stubs.channel, text: 'Pushing is the answer' } should.equal (@stubs._received instanceof TextMessage), true it 'Should ignore messages it sent itself', -> @slackbot.message { subtype: 'bot_message', user: @stubs.self, channel: @stubs.channel, text: 'Ignore me' } should.equal @stubs._received, undefined it 'Should ignore messages it sent itself, if sent as a botuser', -> @slackbot.message { subtype: 'bot_message', bot: @stubs.self_bot, channel: @stubs.channel, text: 'Ignore me' } should.equal @stubs._received, undefined
true
should = require 'should' {Adapter, TextMessage, EnterMessage, LeaveMessage, TopicMessage, Message, CatchAllMessage} = require.main.require 'hubot' describe 'Adapter', -> it 'Should initialize with a robot', -> @slackbot.robot.should.eql @stubs.robot describe 'Login', -> it 'Should set the robot name', -> @slackbot.robot.name.should.equal 'bot' describe 'Logger', -> it 'It should log missing token error', -> {logger} = @slackbot.robot @slackbot.options.token = null @slackbot.run() logger.logs["error"].length.should.be.above(0) logger.logs["error"][logger.logs["error"].length-1].should.equal 'No service token provided to Hubot' it 'It should log invalid token error', -> {logger} = @slackbot.robot @slackbot.options.token = "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI" @slackbot.run() - logger.logs["error"].length.should.be.above(0) logger.logs["error"][logger.logs["error"].length-1].should.equal 'Invalid service token provided, please follow the upgrade instructions' describe 'Send Messages', -> it 'Should send a message', -> sentMessages = @slackbot.send {room: 'general'}, 'message' sentMessages.length.should.equal 1 sentMessages[0].should.equal 'message' it 'Should send multiple messages', -> sentMessages = @slackbot.send {room: 'general'}, 'one', 'two', 'three' sentMessages.length.should.equal 3 it 'Should not send empty messages', -> sentMessages = @slackbot.send {room: 'general'}, 'Hello', '', '', 'world!' sentMessages.length.should.equal 2 it 'Should open a DM channel if needed', -> msg = 'Test' @slackbot.send {room: 'name'}, msg @stubs._msg.should.eql 'Test' it 'Should use an existing DM channel if possible', -> msg = 'Test' @slackbot.send {room: 'user2'}, msg @stubs._dmmsg.should.eql 'Test' describe 'Client sending message', -> it 'Should append as_user = true', -> @client.send {room: 'name'}, {text: 'foo', user: @stubs.user, channel: @stubs.channel} @stubs._opts.as_user.should.eql true it 'Should append as_user = true only as a default', -> @client.send {room: 'name'}, {text: 'foo', user: @stubs.user, channel: @stubs.channel, as_user: false} @stubs._opts.as_user.should.eql false describe 'Reply to Messages', -> it 'Should mention the user in a reply sent in a channel', -> sentMessages = @slackbot.reply {user: @stubs.user, room: @stubs.channel.id}, 'message' sentMessages.length.should.equal 1 sentMessages[0].should.equal "<@#{@stubs.user.id}>: message" it 'Should mention the user in multiple replies sent in a channel', -> sentMessages = @slackbot.reply {user: @stubs.user, room: @stubs.channel.id}, 'one', 'two', 'three' sentMessages.length.should.equal 3 sentMessages[0].should.equal "<@#{@stubs.user.id}>: one" sentMessages[1].should.equal "<@#{@stubs.user.id}>: two" sentMessages[2].should.equal "<@#{@stubs.user.id}>: three" it 'Should send nothing if messages are empty', -> sentMessages = @slackbot.reply {user: @stubs.user, room: @stubs.channel.id}, '' sentMessages.length.should.equal 0 it 'Should NOT mention the user in a reply sent in a DM', -> sentMessages = @slackbot.reply {user: @stubs.user, room: 'D123'}, 'message' sentMessages.length.should.equal 1 sentMessages[0].should.equal "message" describe 'Setting the channel topic', -> it 'Should set the topic in channels', -> @slackbot.topic {room: @stubs.channel.id}, 'channel' @stubs._topic.should.equal 'channel' it 'Should NOT set the topic in DMs', -> @slackbot.topic {room: 'D1232'}, 'DM' should.not.exists(@stubs._topic) describe 'Receiving an error event', -> it 'Should propogate that error', -> @hit = false @slackbot.robot.on 'error', (error) => error.msg.should.equal 'ohno' @hit = true @hit.should.equal false @slackbot.error {msg: 'ohno', code: -2} @hit.should.equal true describe 'Receiving a team_join event', -> it 'Should propagate that event', -> @hit = false @slackbot.robot.on 'team_join', (user) => user.should.equal '1234' @hit = true @hit.should.equal false @slackbot.teamJoin {type: 'team_join', user: '1234'} @hit.should.equal true describe 'Handling incoming messages', -> it 'Should handle regular messages as hoped and dreamed', -> @slackbot.message {text: 'foo', user: @stubs.user, channel: @stubs.channel} @stubs._received.text.should.equal 'foo' it 'Should prepend our name to a message addressed to us in a DM', -> @slackbot.message {text: 'foo', user: @stubs.user, channel: @stubs.DM} @stubs._received.text.should.equal "#{@slackbot.robot.name} foo" it 'Should handle channel_join events as envisioned', -> @slackbot.message {subtype: 'channel_join', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof EnterMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle channel_leave events as envisioned', -> @slackbot.message {subtype: 'channel_leave', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof LeaveMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle channel_topic events as envisioned', -> @slackbot.message {subtype: 'channel_topic', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof TopicMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle group_join events as envisioned', -> @slackbot.message {subtype: 'group_join', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof EnterMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle group_leave events as envisioned', -> @slackbot.message {subtype: 'group_leave', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof LeaveMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle group_topic events as envisioned', -> @slackbot.message {subtype: 'group_topic', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof TopicMessage), true @stubs._received.user.id.should.equal @stubs.user.id it 'Should handle unknown events as catchalls', -> @slackbot.message {subtype: 'hidey_ho', user: @stubs.user, channel: @stubs.channel} should.equal (@stubs._received instanceof CatchAllMessage), true it 'Should not crash with bot messages', -> @slackbot.message { subtype: 'bot_message', bot: @stubs.bot, channel: @stubs.channel, text: 'Pushing is the answer' } should.equal (@stubs._received instanceof TextMessage), true it 'Should ignore messages it sent itself', -> @slackbot.message { subtype: 'bot_message', user: @stubs.self, channel: @stubs.channel, text: 'Ignore me' } should.equal @stubs._received, undefined it 'Should ignore messages it sent itself, if sent as a botuser', -> @slackbot.message { subtype: 'bot_message', bot: @stubs.self_bot, channel: @stubs.channel, text: 'Ignore me' } should.equal @stubs._received, undefined
[ { "context": " blog_path: 'blog/'\n blog_name: \"My Blog\"\n default_author: \"Admin\"\n ", "end": 195, "score": 0.6276156306266785, "start": 193, "tag": "NAME", "value": "My" }, { "context": " blog_name: \"My Blog\"\n default_author: \"Admin\"\n site_url: \"http://www.example.com/\"\n ", "end": 234, "score": 0.7166694402694702, "start": 229, "tag": "NAME", "value": "Admin" } ]
Gruntfile.coffee
ocupop/grunt-ocublog
0
module.exports = (grunt)-> grunt.initConfig { pkg: grunt.file.readJSON 'package.json' ocublog: { dist: { options: { blog_path: 'blog/' blog_name: "My Blog" default_author: "Admin" site_url: "http://www.example.com/" rss: true } files: [{ expand: true cwd: 'blog/' src: ['*.{md,html}'] dest: 'build/blog/' }] } } mochaTest: { test: { src: ['test/*.coffee'] } } clean: ['build/'] } grunt.loadNpmTasks 'grunt-mocha-test' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadTasks 'tasks' grunt.registerTask 'test', ['mochaTest'] grunt.registerTask 'default', ['test', 'ocublog', 'clean']
205738
module.exports = (grunt)-> grunt.initConfig { pkg: grunt.file.readJSON 'package.json' ocublog: { dist: { options: { blog_path: 'blog/' blog_name: "<NAME> Blog" default_author: "<NAME>" site_url: "http://www.example.com/" rss: true } files: [{ expand: true cwd: 'blog/' src: ['*.{md,html}'] dest: 'build/blog/' }] } } mochaTest: { test: { src: ['test/*.coffee'] } } clean: ['build/'] } grunt.loadNpmTasks 'grunt-mocha-test' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadTasks 'tasks' grunt.registerTask 'test', ['mochaTest'] grunt.registerTask 'default', ['test', 'ocublog', 'clean']
true
module.exports = (grunt)-> grunt.initConfig { pkg: grunt.file.readJSON 'package.json' ocublog: { dist: { options: { blog_path: 'blog/' blog_name: "PI:NAME:<NAME>END_PI Blog" default_author: "PI:NAME:<NAME>END_PI" site_url: "http://www.example.com/" rss: true } files: [{ expand: true cwd: 'blog/' src: ['*.{md,html}'] dest: 'build/blog/' }] } } mochaTest: { test: { src: ['test/*.coffee'] } } clean: ['build/'] } grunt.loadNpmTasks 'grunt-mocha-test' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadTasks 'tasks' grunt.registerTask 'test', ['mochaTest'] grunt.registerTask 'default', ['test', 'ocublog', 'clean']
[ { "context": "config.port\n path: config.path\n token: @token.get()\n\n @termView = new TerminalView(@term, nu", "end": 1780, "score": 0.4346208870410919, "start": 1775, "tag": "KEY", "value": "token" }, { "context": ".port\n path: config.path\n token: @token.get()\n\n @termView = new TerminalView(@term, null, ", "end": 1784, "score": 0.44870084524154663, "start": 1781, "tag": "KEY", "value": "get" } ]
lib/learn-ide.coffee
learn-co/mastermind
1
localStorage = require './local-storage' {CompositeDisposable} = require 'atom' Terminal = require './terminal' TerminalView = require './views/terminal' StatusView = require './views/status' {BrowserWindow} = require 'remote' {EventEmitter} = require 'events' Notifier = require './notifier' atomHelper = require './atom-helper' auth = require './auth' bus = require('./event-bus')() config = require './config' {shell} = require 'electron' updater = require './updater' version = require './version' {name} = require '../package.json' ABOUT_URL = 'https://help.learn.co/hc/en-us/categories/204144547-The-Learn-IDE' module.exports = token: require('./token') activate: (state) -> console.log 'activating learn ide' @checkForV1WindowsInstall() @registerWindowsProtocol() @disableFormerPackage() @subscriptions = new CompositeDisposable @subscribeToLogin() @waitForAuth = auth().then => @activateIDE(state) console.log('successfully authenticated') .catch => @activateIDE(state) console.error('failed to authenticate') activateIDE: (state) -> @isRestartAfterUpdate = (localStorage.get('restartingForUpdate') is 'true') if @isRestartAfterUpdate updater.didRestartAfterUpdate() localStorage.delete('restartingForUpdate') @isTerminalWindow = (localStorage.get('popoutTerminal') is 'true') if @isTerminalWindow window.resizeTo(750, 500) localStorage.delete('popoutTerminal') @activateTerminal() @activateStatusView(state) @activateEventHandlers() @activateSubscriptions() @activateNotifier() @activateUpdater() activateTerminal: -> @term = new Terminal host: config.host port: config.port path: config.path token: @token.get() @termView = new TerminalView(@term, null, @isTerminalWindow) @termView.toggle() activateStatusView: (state) -> @statusView = new StatusView state, @term, {@isTerminalWindow} bus.on 'terminal:popin', () => @statusView.onTerminalPopIn() @termView.showAndFocus() @statusView.on 'terminal:popout', => @termView.toggle() activateEventHandlers: -> atomHelper.trackFocusedWindow() # listen for learn:open event from other render processes (url handler) bus.on 'learn:open', (lab) => @termView.openLab(lab.slug) atom.getCurrentWindow().focus() # tidy up when the window closes atom.getCurrentWindow().on 'close', => @cleanup() if @isTerminalWindow bus.emit('terminal:popin', Date.now()) activateSubscriptions: -> @subscriptions.add atom.commands.add 'atom-workspace', 'learn-ide:open': (e) => @termView.openLab(e.detail.path) 'learn-ide:toggle-terminal': () => @termView.toggle() 'learn-ide:toggle-focus': => @termView.toggleFocus() 'learn-ide:focus': => @termView.fullFocus() 'learn-ide:toggle:debugger': => @term.toggleDebugger() 'learn-ide:reset-connection': => @term.reset() 'learn-ide:view-version': => @viewVersion() 'learn-ide:update-check': -> updater.checkForUpdate() 'learn-ide:about': => @about() atom.config.onDidChange "#{name}.terminalFontColor", ({newValue}) => @termView.updateFontColor(newValue) atom.config.onDidChange "#{name}.terminalBackgroundColor", ({newValue}) => @termView.updateBackgroundColor(newValue) atom.config.onDidChange "#{name}.notifier", ({newValue}) => if newValue then @activateNotifier() else @notifier.deactivate() openPath = localStorage.get('learnOpenLabOnActivation') if openPath localStorage.delete('learnOpenLabOnActivation') @termView.openLab(openPath) activateNotifier: -> if atom.config.get("#{name}.notifier") @notifier = new Notifier(@token.get()) @notifier.activate() activateUpdater: -> if not @isRestartAfterUpdate updater.autoCheck() deactivate: -> localStorage.delete('disableTreeView') localStorage.delete('terminalOut') @termView = null @statusView = null @subscriptions.dispose() subscribeToLogin: -> @subscriptions.add atom.commands.add 'atom-workspace', 'learn-ide:log-in-out': => @logInOrOut() cleanup: -> atomHelper.cleanup() consumeStatusBar: (statusBar) -> @waitForAuth.then => @addLearnToStatusBar(statusBar) logInOrOut: -> if @token.get()? @logout() else atomHelper.resetPackage() logout: -> @token.unset() github = new BrowserWindow(show: false) github.webContents.on 'did-finish-load', -> github.show() github.loadURL('https://github.com/logout') learn = new BrowserWindow(show: false) learn.webContents.on 'did-finish-load', -> learn.destroy() learn.loadURL("#{config.learnCo}/sign_out") atomHelper.emit('learn-ide:logout') atomHelper.closePaneItems() atom.reload() checkForV1WindowsInstall: -> require('./windows') registerWindowsProtocol: -> if process.platform == 'win32' require('./protocol') disableFormerPackage: -> ilePkg = atom.packages.loadPackage('integrated-learn-environment') if ilePkg? ilePkg.disable() addLearnToStatusBar: (statusBar) -> leftTiles = Array.from(statusBar.getLeftTiles()) rightTiles = Array.from(statusBar.getRightTiles()) rightMostTile = rightTiles[rightTiles.length - 1] if @isTerminalWindow leftTiles.concat(rightTiles).forEach (tile) -> tile.destroy() priority = (rightMostTile?.priority || 0) - 1 statusBar.addRightTile({item: @statusView, priority}) about: -> shell.openExternal(ABOUT_URL) viewVersion: -> atom.notifications.addInfo("Learn IDE: v#{version}")
189812
localStorage = require './local-storage' {CompositeDisposable} = require 'atom' Terminal = require './terminal' TerminalView = require './views/terminal' StatusView = require './views/status' {BrowserWindow} = require 'remote' {EventEmitter} = require 'events' Notifier = require './notifier' atomHelper = require './atom-helper' auth = require './auth' bus = require('./event-bus')() config = require './config' {shell} = require 'electron' updater = require './updater' version = require './version' {name} = require '../package.json' ABOUT_URL = 'https://help.learn.co/hc/en-us/categories/204144547-The-Learn-IDE' module.exports = token: require('./token') activate: (state) -> console.log 'activating learn ide' @checkForV1WindowsInstall() @registerWindowsProtocol() @disableFormerPackage() @subscriptions = new CompositeDisposable @subscribeToLogin() @waitForAuth = auth().then => @activateIDE(state) console.log('successfully authenticated') .catch => @activateIDE(state) console.error('failed to authenticate') activateIDE: (state) -> @isRestartAfterUpdate = (localStorage.get('restartingForUpdate') is 'true') if @isRestartAfterUpdate updater.didRestartAfterUpdate() localStorage.delete('restartingForUpdate') @isTerminalWindow = (localStorage.get('popoutTerminal') is 'true') if @isTerminalWindow window.resizeTo(750, 500) localStorage.delete('popoutTerminal') @activateTerminal() @activateStatusView(state) @activateEventHandlers() @activateSubscriptions() @activateNotifier() @activateUpdater() activateTerminal: -> @term = new Terminal host: config.host port: config.port path: config.path token: @<KEY>.<KEY>() @termView = new TerminalView(@term, null, @isTerminalWindow) @termView.toggle() activateStatusView: (state) -> @statusView = new StatusView state, @term, {@isTerminalWindow} bus.on 'terminal:popin', () => @statusView.onTerminalPopIn() @termView.showAndFocus() @statusView.on 'terminal:popout', => @termView.toggle() activateEventHandlers: -> atomHelper.trackFocusedWindow() # listen for learn:open event from other render processes (url handler) bus.on 'learn:open', (lab) => @termView.openLab(lab.slug) atom.getCurrentWindow().focus() # tidy up when the window closes atom.getCurrentWindow().on 'close', => @cleanup() if @isTerminalWindow bus.emit('terminal:popin', Date.now()) activateSubscriptions: -> @subscriptions.add atom.commands.add 'atom-workspace', 'learn-ide:open': (e) => @termView.openLab(e.detail.path) 'learn-ide:toggle-terminal': () => @termView.toggle() 'learn-ide:toggle-focus': => @termView.toggleFocus() 'learn-ide:focus': => @termView.fullFocus() 'learn-ide:toggle:debugger': => @term.toggleDebugger() 'learn-ide:reset-connection': => @term.reset() 'learn-ide:view-version': => @viewVersion() 'learn-ide:update-check': -> updater.checkForUpdate() 'learn-ide:about': => @about() atom.config.onDidChange "#{name}.terminalFontColor", ({newValue}) => @termView.updateFontColor(newValue) atom.config.onDidChange "#{name}.terminalBackgroundColor", ({newValue}) => @termView.updateBackgroundColor(newValue) atom.config.onDidChange "#{name}.notifier", ({newValue}) => if newValue then @activateNotifier() else @notifier.deactivate() openPath = localStorage.get('learnOpenLabOnActivation') if openPath localStorage.delete('learnOpenLabOnActivation') @termView.openLab(openPath) activateNotifier: -> if atom.config.get("#{name}.notifier") @notifier = new Notifier(@token.get()) @notifier.activate() activateUpdater: -> if not @isRestartAfterUpdate updater.autoCheck() deactivate: -> localStorage.delete('disableTreeView') localStorage.delete('terminalOut') @termView = null @statusView = null @subscriptions.dispose() subscribeToLogin: -> @subscriptions.add atom.commands.add 'atom-workspace', 'learn-ide:log-in-out': => @logInOrOut() cleanup: -> atomHelper.cleanup() consumeStatusBar: (statusBar) -> @waitForAuth.then => @addLearnToStatusBar(statusBar) logInOrOut: -> if @token.get()? @logout() else atomHelper.resetPackage() logout: -> @token.unset() github = new BrowserWindow(show: false) github.webContents.on 'did-finish-load', -> github.show() github.loadURL('https://github.com/logout') learn = new BrowserWindow(show: false) learn.webContents.on 'did-finish-load', -> learn.destroy() learn.loadURL("#{config.learnCo}/sign_out") atomHelper.emit('learn-ide:logout') atomHelper.closePaneItems() atom.reload() checkForV1WindowsInstall: -> require('./windows') registerWindowsProtocol: -> if process.platform == 'win32' require('./protocol') disableFormerPackage: -> ilePkg = atom.packages.loadPackage('integrated-learn-environment') if ilePkg? ilePkg.disable() addLearnToStatusBar: (statusBar) -> leftTiles = Array.from(statusBar.getLeftTiles()) rightTiles = Array.from(statusBar.getRightTiles()) rightMostTile = rightTiles[rightTiles.length - 1] if @isTerminalWindow leftTiles.concat(rightTiles).forEach (tile) -> tile.destroy() priority = (rightMostTile?.priority || 0) - 1 statusBar.addRightTile({item: @statusView, priority}) about: -> shell.openExternal(ABOUT_URL) viewVersion: -> atom.notifications.addInfo("Learn IDE: v#{version}")
true
localStorage = require './local-storage' {CompositeDisposable} = require 'atom' Terminal = require './terminal' TerminalView = require './views/terminal' StatusView = require './views/status' {BrowserWindow} = require 'remote' {EventEmitter} = require 'events' Notifier = require './notifier' atomHelper = require './atom-helper' auth = require './auth' bus = require('./event-bus')() config = require './config' {shell} = require 'electron' updater = require './updater' version = require './version' {name} = require '../package.json' ABOUT_URL = 'https://help.learn.co/hc/en-us/categories/204144547-The-Learn-IDE' module.exports = token: require('./token') activate: (state) -> console.log 'activating learn ide' @checkForV1WindowsInstall() @registerWindowsProtocol() @disableFormerPackage() @subscriptions = new CompositeDisposable @subscribeToLogin() @waitForAuth = auth().then => @activateIDE(state) console.log('successfully authenticated') .catch => @activateIDE(state) console.error('failed to authenticate') activateIDE: (state) -> @isRestartAfterUpdate = (localStorage.get('restartingForUpdate') is 'true') if @isRestartAfterUpdate updater.didRestartAfterUpdate() localStorage.delete('restartingForUpdate') @isTerminalWindow = (localStorage.get('popoutTerminal') is 'true') if @isTerminalWindow window.resizeTo(750, 500) localStorage.delete('popoutTerminal') @activateTerminal() @activateStatusView(state) @activateEventHandlers() @activateSubscriptions() @activateNotifier() @activateUpdater() activateTerminal: -> @term = new Terminal host: config.host port: config.port path: config.path token: @PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI() @termView = new TerminalView(@term, null, @isTerminalWindow) @termView.toggle() activateStatusView: (state) -> @statusView = new StatusView state, @term, {@isTerminalWindow} bus.on 'terminal:popin', () => @statusView.onTerminalPopIn() @termView.showAndFocus() @statusView.on 'terminal:popout', => @termView.toggle() activateEventHandlers: -> atomHelper.trackFocusedWindow() # listen for learn:open event from other render processes (url handler) bus.on 'learn:open', (lab) => @termView.openLab(lab.slug) atom.getCurrentWindow().focus() # tidy up when the window closes atom.getCurrentWindow().on 'close', => @cleanup() if @isTerminalWindow bus.emit('terminal:popin', Date.now()) activateSubscriptions: -> @subscriptions.add atom.commands.add 'atom-workspace', 'learn-ide:open': (e) => @termView.openLab(e.detail.path) 'learn-ide:toggle-terminal': () => @termView.toggle() 'learn-ide:toggle-focus': => @termView.toggleFocus() 'learn-ide:focus': => @termView.fullFocus() 'learn-ide:toggle:debugger': => @term.toggleDebugger() 'learn-ide:reset-connection': => @term.reset() 'learn-ide:view-version': => @viewVersion() 'learn-ide:update-check': -> updater.checkForUpdate() 'learn-ide:about': => @about() atom.config.onDidChange "#{name}.terminalFontColor", ({newValue}) => @termView.updateFontColor(newValue) atom.config.onDidChange "#{name}.terminalBackgroundColor", ({newValue}) => @termView.updateBackgroundColor(newValue) atom.config.onDidChange "#{name}.notifier", ({newValue}) => if newValue then @activateNotifier() else @notifier.deactivate() openPath = localStorage.get('learnOpenLabOnActivation') if openPath localStorage.delete('learnOpenLabOnActivation') @termView.openLab(openPath) activateNotifier: -> if atom.config.get("#{name}.notifier") @notifier = new Notifier(@token.get()) @notifier.activate() activateUpdater: -> if not @isRestartAfterUpdate updater.autoCheck() deactivate: -> localStorage.delete('disableTreeView') localStorage.delete('terminalOut') @termView = null @statusView = null @subscriptions.dispose() subscribeToLogin: -> @subscriptions.add atom.commands.add 'atom-workspace', 'learn-ide:log-in-out': => @logInOrOut() cleanup: -> atomHelper.cleanup() consumeStatusBar: (statusBar) -> @waitForAuth.then => @addLearnToStatusBar(statusBar) logInOrOut: -> if @token.get()? @logout() else atomHelper.resetPackage() logout: -> @token.unset() github = new BrowserWindow(show: false) github.webContents.on 'did-finish-load', -> github.show() github.loadURL('https://github.com/logout') learn = new BrowserWindow(show: false) learn.webContents.on 'did-finish-load', -> learn.destroy() learn.loadURL("#{config.learnCo}/sign_out") atomHelper.emit('learn-ide:logout') atomHelper.closePaneItems() atom.reload() checkForV1WindowsInstall: -> require('./windows') registerWindowsProtocol: -> if process.platform == 'win32' require('./protocol') disableFormerPackage: -> ilePkg = atom.packages.loadPackage('integrated-learn-environment') if ilePkg? ilePkg.disable() addLearnToStatusBar: (statusBar) -> leftTiles = Array.from(statusBar.getLeftTiles()) rightTiles = Array.from(statusBar.getRightTiles()) rightMostTile = rightTiles[rightTiles.length - 1] if @isTerminalWindow leftTiles.concat(rightTiles).forEach (tile) -> tile.destroy() priority = (rightMostTile?.priority || 0) - 1 statusBar.addRightTile({item: @statusView, priority}) about: -> shell.openExternal(ABOUT_URL) viewVersion: -> atom.notifications.addInfo("Learn IDE: v#{version}")
[ { "context": "game -> REFUSING JOIN: A player #{@.decoded_token.d.id.blue} is attempting to join a game as #{playerId.", "end": 5757, "score": 0.5616366267204285, "start": 5753, "tag": "EMAIL", "value": "d.id" }, { "context": "\t\tplayerId: playerId,\n\t\t\t\tusername: spectateToken.u\n\t\t\t})\n\n\t.catch (e) ->\n\t\t# if we didn't join a gam", "end": 16884, "score": 0.6201755404472351, "start": 16883, "tag": "USERNAME", "value": "u" }, { "context": " if config.get('port') is 9001\n\t\t\t\tnewServerIp = \"127.0.0.1:#{port}\"\n\t\t\tmsg = \"Server is shutting down. You w", "end": 64552, "score": 0.9987425208091736, "start": 64543, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
server/game.coffee
willroberts/duelyst
0
### Game Server Pieces ### fs = require 'fs' os = require 'os' util = require 'util' _ = require 'underscore' colors = require 'colors' # used for console message coloring jwt = require 'jsonwebtoken' io = require 'socket.io' ioJwt = require 'socketio-jwt' Promise = require 'bluebird' kue = require 'kue' moment = require 'moment' request = require 'superagent' # Our modules shutdown = require './shutdown' SDK = require '../app/sdk.coffee' Logger = require '../app/common/logger.coffee' EVENTS = require '../app/common/event_types' UtilsGameSession = require '../app/common/utils/utils_game_session.coffee' exceptionReporter = require '@counterplay/exception-reporter' # lib Modules Consul = require './lib/consul' # Configuration object config = require '../config/config.js' env = config.get('env') firebaseToken = config.get('firebaseToken') # Boots up a basic HTTP server on port 8080 # Responds to /health endpoint with status 200 # Otherwise responds with status 404 Logger = require '../app/common/logger.coffee' CONFIG = require '../app/common/config' http = require 'http' url = require 'url' Promise = require 'bluebird' # perform DNS health check dnsHealthCheck = () -> if config.isDevelopment() return Promise.resolve({healthy: true}) nodename = "#{config.get('env')}-#{os.hostname().split('.')[0]}" return Consul.kv.get("nodes/#{nodename}/dns_name") .then (dnsName) -> return new Promise (resolve, reject) -> request.get("https://#{dnsName}/health") .end (err, res) -> if err return resolve({dnsName: dnsName, healthy: false}) if res? && res.status == 200 return resolve({dnsName: dnsName, healthy: true}) return ({dnsName: dnsName, healthy: false}) .catch (e) -> return {healthy: false} # create http server and respond to /health requests server = http.createServer (req, res) -> pathname = url.parse(req.url).pathname if pathname == '/health' Logger.module("GAME SERVER").debug "HTTP Health Ping" res.statusCode = 200 res.write JSON.stringify({players: playerCount, games: gameCount}) res.end() else res.statusCode = 404 res.end() # io server setup, binds to http server io = require('socket.io')().listen(server, { cors: { origin: "*" } }) io.use( ioJwt.authorize( secret:firebaseToken timeout: 15000 ) ) module.exports = io server.listen config.get('game_port'), () -> Logger.module("GAME SERVER").log "GAME Server <b>#{os.hostname()}</b> started." # redis {Redis, Jobs, GameManager} = require './redis/' # server id for this game server serverId = os.hostname() # the 'games' hash maps game IDs to References for those games games = {} # save some basic stats about this server into redis playerCount = 0 gameCount = 0 # turn times MAX_TURN_TIME = (CONFIG.TURN_DURATION + CONFIG.TURN_DURATION_LATENCY_BUFFER) * 1000.0 MAX_TURN_TIME_INACTIVE = (CONFIG.TURN_DURATION_INACTIVE + CONFIG.TURN_DURATION_LATENCY_BUFFER) * 1000.0 savePlayerCount = (playerCount) -> Redis.hsetAsync("servers:#{serverId}", "players", playerCount) saveGameCount = (gameCount) -> Redis.hsetAsync("servers:#{serverId}", "games", gameCount) # error 'domain' to deal with io.sockets uncaught errors d = require('domain').create() d.on 'error', shutdown.errorShutdown d.add(io.sockets) # health ping on socket namespace /health healthPing = io .of '/health' .on 'connection', (socket) -> socket.on 'ping', () -> Logger.module("GAME SERVER").debug "socket.io Health Ping" socket.emit 'pong' # run main io.sockets inside of the domain d.run () -> io.sockets.on "authenticated", (socket) -> # add the socket to the error domain d.add(socket) # Socket is now autheticated, continue to bind other handlers Logger.module("IO").debug "DECODED TOKEN ID: #{socket.decoded_token.d.id.blue}" savePlayerCount(++playerCount) # Send message to user that connection is succesful socket.emit "connected", message: "Successfully connected to server" # Bind socket event handlers socket.on EVENTS.join_game, onGamePlayerJoin socket.on EVENTS.spectate_game, onGameSpectatorJoin socket.on EVENTS.leave_game, onGameLeave socket.on EVENTS.network_game_event, onGameEvent socket.on "disconnect", onGameDisconnect getConnectedSpectatorsDataForGamePlayer = (gameId,playerId)-> spectators = [] for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"] socket = io.sockets.connected[socketId] if socket.playerId == playerId spectators.push({ id:socket.spectatorId, playerId:socket.playerId, username:socket.spectateToken?.u }) return spectators ### # socket handler for players joining game # @public # @param {Object} requestData Plain JS object with socket event data. ### onGamePlayerJoin = (requestData) -> # request parameters gameId = requestData.gameId playerId = requestData.playerId Logger.module("IO").debug "[G:#{gameId}]", "join_game -> player:#{requestData.playerId} is joining game:#{requestData.gameId}".cyan # you must have a playerId if not playerId Logger.module("IO").error "[G:#{gameId}]", "join_game -> REFUSING JOIN: A player #{playerId.blue} is not valid".red @emit "join_game_response", error:"Your player id seems to be blank (has your login expired?), so we can't join you to the game." return # must have a gameId if not gameId Logger.module("IO").error "[G:#{gameId}]", "join_game -> REFUSING JOIN: A gameId #{gameId.blue} is not valid".red @emit "join_game_response", error:"Invalid Game ID." return # if someone is trying to join a game they don't belong to as a player they are not authenticated as if @.decoded_token.d.id != playerId Logger.module("IO").error "[G:#{gameId}]", "join_game -> REFUSING JOIN: A player #{@.decoded_token.d.id.blue} is attempting to join a game as #{playerId.blue}".red @emit "join_game_response", error:"Your player id does not match the one you requested to join a game with. Are you sure you're joining the right game?" return # if a client is already in another game, leave it playerLeaveGameIfNeeded(this) # if this client already exists in this game, disconnect duplicate client for socketId,connected of io.sockets.adapter.rooms[gameId] socket = io.sockets.connected[socketId] if socket? and socket.playerId == playerId Logger.module("IO").error "[G:#{gameId}]", "join_game -> detected duplicate connection to #{gameId} GameSession for #{playerId.blue}. Disconnecting duplicate...".cyan playerLeaveGameIfNeeded(socket, silent=true) # initialize a server-side game session and join it initGameSession(gameId) .bind @ .spread (gameSession) -> #Logger.module("IO").debug "[G:#{gameId}]", "join_game -> players in data: ", gameSession.players # player player = _.find(gameSession.players, (p) -> return p.playerId == playerId) # get the opponent based on the game session data opponent = _.find(gameSession.players, (p) -> return p.playerId != playerId) Logger.module("IO").debug "[G:#{gameId}]", "join_game -> Got #{gameId} GameSession data #{playerId.blue}.".cyan if not player # oops looks like this player does not exist in the requested game # let the socket know we had an error @emit "join_game_response", error:"could not join game because your player id could not be found" # destroy the game data loaded so far if the opponent can't be defined and no one else is connected Logger.module("IO").error "[G:#{gameId}]", "onGameJoin -> DESTROYING local game cache due to join error".red destroyGameSessionIfNoConnectionsLeft(gameId) # stop any further processing return else if not opponent? # oops, looks like we can'f find an opponent in the game session? Logger.module("IO").error "[G:#{gameId}]", "join_game -> game #{gameId} ERROR: could not find opponent for #{playerId.blue}.".red # let the socket know we had an error @emit "join_game_response", error:"could not join game because the opponent could not be found" # issue a warning to our exceptionReporter error tracker exceptionReporter.notify(new Error("Error joining game: could not find opponent"), { severity: "warning" user: id: playerId game: id: gameId player1Id: gameSession?.players[0].playerId player2Id: gameSession?.players[1].playerId }) # destroy the game data loaded so far if the opponent can't be defined and no one else is connected Logger.module("IO").error "[G:#{gameId}]", "onGameJoin -> DESTROYING local game cache due to join error".red destroyGameSessionIfNoConnectionsLeft(gameId) # stop any further processing return else # rollback if it is this player's followup # this can happen if a player reconnects without properly disconnecting if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() == playerId gameSession.executeAction(gameSession.actionRollbackSnapshot()) # set some parameters for the socket @gameId = gameId @playerId = playerId # join game room @join(gameId) # update user count for game room games[gameId].connectedPlayers.push(playerId) Logger.module("IO").debug "[G:#{gameId}]", "join_game -> Game #{gameId} connected players so far: #{games[gameId].connectedPlayers.length}." # if only one player is in so far, start the disconnection timer if games[gameId].connectedPlayers.length == 1 # start disconnected player timeout for game startDisconnectedPlayerTimeout(gameId,opponent.playerId) else if games[gameId].connectedPlayers.length == 2 # clear timeout when we get two players clearDisconnectedPlayerTimeout(gameId) # prepare and scrub game session data for this player # if a followup is active and it isn't this player's followup, send them the rollback snapshot if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() != playerId gameSessionData = JSON.parse(gameSession.getRollbackSnapshotData()) else gameSessionData = JSON.parse(gameSession.serializeToJSON(gameSession)) UtilsGameSession.scrubGameSessionData(gameSession, gameSessionData, playerId) # respond to client with success and a scrubbed copy of the game session @emit "join_game_response", message: "successfully joined game" gameSessionData: gameSessionData connectedPlayers:games[gameId].connectedPlayers connectedSpectators: getConnectedSpectatorsDataForGamePlayer(gameId,playerId) # broadcast join to any other connected players @broadcast.to(gameId).emit("player_joined",playerId) .catch (e) -> Logger.module("IO").error "[G:#{gameId}]", "join_game -> player:#{playerId} failed to join game, error: #{e.message}".red Logger.module("IO").error "[G:#{gameId}]", "join_game -> player:#{playerId} failed to join game, error stack: #{e.stack}".red # if we didn't join a game, broadcast a failure @emit "join_game_response", error:"Could not join game: " + e?.message ### # socket handler for spectators joining game # @public # @param {Object} requestData Plain JS object with socket event data. ### onGameSpectatorJoin = (requestData) -> # request parameters # TODO : Sanitize these parameters to prevent crash if gameId = null gameId = requestData.gameId spectatorId = requestData.spectatorId playerId = requestData.playerId spectateToken = null # verify - synchronous try spectateToken = jwt.verify(requestData.spectateToken, firebaseToken) catch error Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> ERROR decoding spectate token: #{error?.message}".red if not spectateToken or spectateToken.b?.length == 0 Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A specate token #{spectateToken} is not valid".red @emit "spectate_game_response", error:"Your spectate token is invalid, so we can't join you to the game." return Logger.module("IO").debug "[G:#{gameId}]", "spectate_game -> token contents: ", spectateToken.b Logger.module("IO").debug "[G:#{gameId}]", "spectate_game -> playerId: ", playerId if not _.contains(spectateToken.b,playerId) Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: You do not have permission to specate this game".red @emit "spectate_game_response", error:"You do not have permission to specate this game." return # must have a spectatorId if not spectatorId Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A spectator #{spectatorId.blue} is not valid".red @emit "spectate_game_response", error:"Your login ID is blank (expired?), so we can't join you to the game." return # must have a playerId if not playerId Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A player #{playerId.blue} is not valid".red @emit "spectate_game_response", error:"Invalid player ID." return # must have a gameId if not gameId Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A gameId #{gameId.blue} is not valid".red @emit "spectate_game_response", error:"Invalid Game ID." return # if someone is trying to join a game they don't belong to as a player they are not authenticated as if @.decoded_token.d.id != spectatorId Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A player #{@.decoded_token.d.id.blue} is attempting to join a game as #{playerId.blue}".red @emit "spectate_game_response", error:"Your login ID does not match the one you requested to spectate the game with." return Logger.module("IO").debug "[G:#{gameId}]", "spectate_game -> spectator:#{spectatorId} is joining game:#{gameId}".cyan # if a client is already in another game, leave it spectatorLeaveGameIfNeeded(@) if games[gameId]?.connectedSpectators.length >= 10 # max out at 10 spectators @emit "spectate_game_response", error:"Maximum number of spectators already watching." return # initialize a server-side game session and join it initSpectatorGameSession(gameId) .bind @ .then (spectatorGameSession) -> # for spectators, use the delayed in-memory game session gameSession = spectatorGameSession Logger.module("IO").debug "[G:#{gameId}]", "spectate_game -> Got #{gameId} GameSession data.".cyan player = _.find(gameSession.players, (p) -> return p.playerId == playerId) opponent = _.find(gameSession.players, (p) -> return p.playerId != playerId) if not player # let the socket know we had an error @emit "spectate_game_response", error:"could not join game because the player id you requested could not be found" # destroy the game data loaded so far if the opponent can't be defined and no one else is connected Logger.module("IO").error "[G:#{gameId}]", "onGameSpectatorJoin -> DESTROYING local game cache due to join error".red destroyGameSessionIfNoConnectionsLeft(gameId) # stop any further processing return else # set some parameters for the socket @gameId = gameId @spectatorId = spectatorId @spectateToken = spectateToken @playerId = playerId # join game room @join("spectate-#{gameId}") # update user count for game room games[gameId].connectedSpectators.push(spectatorId) # prepare and scrub game session data for this player # if a followup is active and it isn't this player's followup, send them the rollback snapshot if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() != playerId gameSessionData = JSON.parse(gameSession.getRollbackSnapshotData()) else gameSessionData = JSON.parse(gameSession.serializeToJSON(gameSession)) UtilsGameSession.scrubGameSessionData(gameSession, gameSessionData, playerId, true) ### # if the spectator does not have the opponent in their buddy list if not _.contains(spectateToken.b,opponent.playerId) # scrub deck data and opponent hand data by passing in opponent ID scrubGameSessionDataForSpectators(gameSession, gameSessionData, opponent.playerId) else # otherwise just scrub deck data in a way you can see both decks # scrubGameSessionDataForSpectators(gameSession, gameSessionData) # NOTE: above line is disabled for now since it does some UI jankiness since when a cardId is present the tile layer updates when the spectated opponent starts to select cards # NOTE: besides, actions will be scrubbed so this idea of watching both players only sort of works right now scrubGameSessionDataForSpectators(gameSession, gameSessionData, opponent.playerId, true) ### # respond to client with success and a scrubbed copy of the game session @emit "spectate_game_response", message: "successfully joined game" gameSessionData: gameSessionData # broadcast to the game room that a spectator has joined @broadcast.to(gameId).emit("spectator_joined",{ id: spectatorId, playerId: playerId, username: spectateToken.u }) .catch (e) -> # if we didn't join a game, broadcast a failure @emit "spectate_game_response", error:"could not join game: #{e.message}" ### # socket handler for leaving a game. # @public # @param {Object} requestData Plain JS object with socket event data. ### onGameLeave = (requestData) -> if @.spectatorId Logger.module("IO").debug "[G:#{@.gameId}]", "leave_game -> spectator #{@.spectatorId} leaving #{@.gameId}" spectatorLeaveGameIfNeeded(@) else Logger.module("IO").debug "[G:#{@.gameId}]", "leave_game -> player #{@.playerId} leaving #{@.gameId}" playerLeaveGameIfNeeded(@) ###* # This method is called every time a socket handler recieves a game event and is executed within the context of the socket (this == sending socket). # @public # @param {Object} eventData Plain JS object with event data that contains one "event". ### onGameEvent = (eventData) -> # if for some reason spectator sockets start broadcasting game events if @.spectatorId Logger.module("IO").error "[G:#{@.gameId}]", "onGameEvent :: ERROR: spectator sockets can't submit game events. (type: #{eventData.type})".red return # Logger.module("IO").log "onGameEvent -> #{JSON.stringify(eventData)}".blue if not @gameId or not games[@gameId] @emit EVENTS.network_game_error, code:500 message:"could not broadcast game event because you are not currently in a game" return # gameSession = games[@gameId].session if eventData.type == EVENTS.step #Logger.module("IO").log "[G:#{@.gameId}]", "game_step -> #{JSON.stringify(eventData.step)}".green #Logger.module("IO").log "[G:#{@.gameId}]", "game_step -> #{eventData.step?.playerId} #{eventData.step?.action?.type}".green player = _.find(gameSession.players,(p)-> p.playerId == eventData.step?.playerId) player?.setLastActionTakenAt(Date.now()) try step = gameSession.deserializeStepFromFirebase(eventData.step) action = step.action if action? # clear out any implicit actions sent over the network and re-execute this as a fresh explicit action on the server # the reason is that we want to re-generate and re-validate all the game logic that happens as a result of this FIRST explicit action in the step action.resetForAuthoritativeExecution() # execute the action gameSession.executeAction(action) catch error Logger.module("IO").error "[G:#{@.gameId}]", "onGameStep:: error: #{JSON.stringify(error.message)}".red Logger.module("IO").error "[G:#{@.gameId}]", "onGameStep:: error stack: #{error.stack}".red # Report error to exceptionReporter with gameId + eventData exceptionReporter.notify(error, { errorName: "onGameStep Error", game: { gameId: @gameId eventData: eventData } }) # delete but don't destroy game destroyGameSessionIfNoConnectionsLeft(@gameId,true) # send error to client, forcing reconnect on client side io.to(@gameId).emit EVENTS.network_game_error, JSON.stringify(error.message) return else # transmit the non-step game events to players # step events are emitted automatically after executed on game session emitGameEvent(@, @gameId, eventData) ### # Socket Disconnect Event Handler. Handles rollback if in the middle of followup etc. # @public ### onGameDisconnect = () -> if @.spectatorId # make spectator leave game room spectatorLeaveGameIfNeeded(@) # remove the socket from the error domain, this = socket d.remove(@) else try clients_in_the_room = io.sockets.adapter.rooms[@.gameId] for clientId,socket of clients_in_the_room if socket.playerId == @.playerId Logger.module("IO").error "onGameDisconnect:: looks like the player #{@.playerId} we are trying to disconnect is still in the game #{@.gameId} room. ABORTING".red return for clientId,socket of io.sockets.connected if socket.playerId == @.playerId and not socket.spectatorId Logger.module("IO").error "onGameDisconnect:: looks like the player #{@.playerId} that allegedly disconnected is still alive and well.".red return catch error Logger.module("IO").error "onGameDisconnect:: Error #{error?.message}.".red # if we are in a buffering state # and the disconnecting player is in the middle of a followup gs = games[@gameId]?.session if gs? and gs.getIsBufferingEvents() and gs.getCurrentPlayerId() == @playerId # execute a rollback to reset server state # but do not send this action to the still connected player # because they do not care about rollbacks for the other player rollBackAction = gs.actionRollbackSnapshot() gs.executeAction(rollBackAction) # remove the socket from the error domain, this = socket d.remove(@) savePlayerCount(--playerCount) Logger.module("IO").debug "[G:#{@.gameId}]", "disconnect -> #{@.playerId}".red # if a client is already in another game, leave it playerLeaveGameIfNeeded(@) ###* * Leaves a game for a player socket if the socket is connected to a game * @public * @param {Socket} socket The socket which wants to leave a game. * @param {Boolean} [silent=false] whether to disconnect silently, as in the case of duplicate connections for same player ### playerLeaveGameIfNeeded = (socket, silent=false) -> if socket? gameId = socket.gameId playerId = socket.playerId # if a player is in a game if gameId? and playerId? Logger.module("...").debug "[G:#{gameId}]", "playerLeaveGame -> #{playerId} has left game #{gameId}".red if !silent # broadcast that player left socket.broadcast.to(gameId).emit("player_left",playerId) # leave that game room socket.leave(gameId) # update user count for game room game = games[gameId] if game? index = game.connectedPlayers.indexOf(playerId) game.connectedPlayers.splice(index,1) if !silent # start disconnected player timeout for game startDisconnectedPlayerTimeout(gameId,playerId) # destroy game if no one is connected anymore destroyGameSessionIfNoConnectionsLeft(gameId,true) # finally clear the existing gameId socket.gameId = null ### # This function leaves a game for a spectator socket if the socket is connected to a game # @public # @param {Socket} socket The socket which wants to leave a game. ### spectatorLeaveGameIfNeeded = (socket) -> # if a client is already in another game if socket.gameId Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} leaving game #{socket.gameId}." # broadcast that you left socket.broadcast.to(socket.gameId).emit("spectator_left",{ id:socket.spectatorId, playerId:socket.playerId, username:socket.spectateToken?.u }) # leave specator game room socket.leave("spectate-#{socket.gameId}") Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} left room for game #{socket.gameId}." # update spectator count for game room if games[socket.gameId] games[socket.gameId].connectedSpectators = _.without(games[socket.gameId].connectedSpectators,socket.spectatorId) Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} removed from list of spectators #{socket.gameId}." # if no spectators left, stop the delayed game interval and destroy spectator delayed game session tearDownSpectateSystemsIfNoSpectatorsLeft(socket.gameId) # destroy game if no one is connected anymore destroyGameSessionIfNoConnectionsLeft(socket.gameId,true) remainingSpectators = games[socket.gameId]?.connectedSpectators?.length || 0 Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} has left game #{socket.gameId}. remaining spectators #{remainingSpectators}" # finally clear the existing gameId socket.gameId = null ### # This function destroys in-memory game session of there is no one left connected # @public # @param {String} gameId The ID of the game to destroy. # @param {Boolean} persist Do we need to save/archive this game? ### destroyGameSessionIfNoConnectionsLeft = (gameId,persist=false)-> if games[gameId].connectedPlayers.length == 0 and games[gameId].connectedSpectators.length == 0 clearDisconnectedPlayerTimeout(gameId) stopTurnTimer(gameId) tearDownSpectateSystemsIfNoSpectatorsLeft(gameId) Logger.module("...").debug "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft() -> no players left DESTROYING local game cache".red unsubscribeFromGameSessionEvents(gameId) # TEMP: a way to upload unfinished game data to AWS S3 Archive. For example: errored out games. if persist and games?[gameId]?.session?.status != SDK.GameStatus.over data = games[gameId].session.serializeToJSON(games[gameId].session) mouseAndUIEventsData = JSON.stringify(games[gameId].mouseAndUIEvents) Promise.all([ GameManager.saveGameSession(gameId,data), GameManager.saveGameMouseUIData(gameId,mouseAndUIEventsData), ]) .then (results) -> Logger.module("...").debug "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft -> unfinished Game Archived to S3: #{results[1]}".green .catch (error)-> Logger.module("...").error "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft -> ERROR: failed to archive unfinished game to S3 due to error #{error.message}".red delete games[gameId] saveGameCount(--gameCount) else Logger.module("...").debug "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft() -> players left: #{games[gameId].connectedPlayers.length} spectators left: #{games[gameId].connectedSpectators.length}" ### # This function stops all spectate systems if 0 spectators left. # @public # @param {String} gameId The ID of the game to tear down spectate systems. ### tearDownSpectateSystemsIfNoSpectatorsLeft = (gameId)-> # if no spectators left, stop the delayed game interval and destroy spectator delayed game session if games[gameId]?.connectedSpectators.length == 0 Logger.module("IO").debug "[G:#{gameId}]", "tearDownSpectateSystemsIfNoSpectatorsLeft() -> no spectators left, stopping spectate systems" stopSpectatorDelayedGameInterval(gameId) games[gameId].spectatorDelayedGameSession = null games[gameId].spectateIsRunning = false games[gameId].spectatorOpponentEventDataBuffer.length = 0 games[gameId].spectatorGameEventBuffer.length = 0 ### # Clears timeout for disconnected players # @public # @param {String} gameId The ID of the game to clear disconnected timeout for. ### clearDisconnectedPlayerTimeout = (gameId) -> Logger.module("IO").debug "[G:#{gameId}]", "clearDisconnectedPlayerTimeout:: for game: #{gameId}".yellow clearTimeout(games[gameId]?.disconnectedPlayerTimeout) games[gameId]?.disconnectedPlayerTimeout = null ### # Starts timeout for disconnected players # @public # @param {String} gameId The ID of the game. # @param {String} playerId The player ID for who to start the timeout. ### startDisconnectedPlayerTimeout = (gameId,playerId) -> if games[gameId]?.disconnectedPlayerTimeout? clearDisconnectedPlayerTimeout(gameId) Logger.module("IO").debug "[G:#{gameId}]", "startDisconnectedPlayerTimeout:: for #{playerId} in game: #{gameId}".yellow games[gameId]?.disconnectedPlayerTimeout = setTimeout(()-> onDisconnectedPlayerTimeout(gameId,playerId) ,60000) ### # Resigns game for disconnected player. # @public # @param {String} gameId The ID of the game. # @param {String} playerId The player ID who is resigning. ### onDisconnectedPlayerTimeout = (gameId,playerId) -> Logger.module("IO").debug "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} for game: #{gameId}" clients_in_the_room = io.sockets.adapter.rooms[gameId] for clientId,socket of clients_in_the_room if socket.playerId == playerId Logger.module("IO").error "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: looks like the player #{playerId} we are trying to dis-connect is still in the game #{gameId} room. ABORTING".red return for clientId,socket of io.sockets.connected if socket.playerId == playerId and not socket.spectatorId Logger.module("IO").error "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: looks like the player #{playerId} we are trying to disconnect is still connected but not in the game #{gameId} room.".red return # grab the relevant game session gs = games[gameId]?.session # looks like we timed out for a game that's since ended if !gs or gs?.status == SDK.GameStatus.over Logger.module("IO").error "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} timed out for FINISHED or NULL game: #{gameId}".yellow return else Logger.module("IO").debug "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} auto-resigning game: #{gameId}".yellow # resign the player player = gs.getPlayerById(playerId) resignAction = player.actionResign() gs.executeAction(resignAction) ###* # Start/Restart server side game timer for a game # @public # @param {Object} gameId The game ID. ### restartTurnTimer = (gameId) -> stopTurnTimer(gameId) game = games[gameId] if game.session? game.turnTimerStartedAt = game.turnTimeTickAt = Date.now() game.turnTimer = setInterval((()-> onGameTimeTick(gameId)),1000) ###* # Stop server side game timer for a game # @public # @param {Object} gameId The game ID. ### stopTurnTimer = (gameId) -> game = games[gameId] if game? and game.turnTimer? clearInterval(game.turnTimer) game.turnTimer = null ###* # Server side game timer. After 90 seconds it will end the turn for the current player. # @public # @param {Object} gameId The game for which to iterate the time. ### onGameTimeTick = (gameId) -> game = games[gameId] gameSession = game?.session if gameSession? # allowed turn time is 90 seconds + slop buffer that clients don't see allowed_turn_time = MAX_TURN_TIME # grab the current player player = gameSession.getCurrentPlayer() # if we're past the 2nd turn, we can start checking backwards to see how long the PREVIOUS turn for this player took if player and gameSession.getTurns().length > 2 # find the current player's previous turn allTurns = gameSession.getTurns() playersPreviousTurn = null for i in [allTurns.length-1..0] by -1 if allTurns[i].playerId == player.playerId playersPreviousTurn = allTurns[i] # gameSession.getTurns()[gameSession.getTurns().length - 3] break #Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: last action at #{player.getLastActionTakenAt()} / last turn delta #{playersPreviousTurn?.createdAt - player.getLastActionTakenAt()}".red # if this player's previous action was on a turn older than the last one if playersPreviousTurn && (playersPreviousTurn.createdAt - player.getLastActionTakenAt() > 0) # you're only allowed 15 seconds + 3 second buffer that clients don't see allowed_turn_time = MAX_TURN_TIME_INACTIVE lastTurnTimeTickAt = game.turnTimeTickAt game.turnTimeTickAt = Date.now() delta_turn_time_tick = game.turnTimeTickAt - lastTurnTimeTickAt delta_since_timer_began = game.turnTimeTickAt - game.turnTimerStartedAt game.turnTimeRemaining = Math.max(0.0, allowed_turn_time - delta_since_timer_began + game.turnTimeBonus) game.turnTimeBonus = Math.max(0.0, game.turnTimeBonus - delta_turn_time_tick) #Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: delta #{delta_turn_time_tick/1000}, #{game.turnTimeRemaining/1000} time remaining, #{game.turnTimeBonus/1000} bonus remaining" turnTimeRemainingInSeconds = Math.ceil(game.turnTimeRemaining/1000) gameSession.setTurnTimeRemaining(turnTimeRemainingInSeconds) if game.turnTimeRemaining <= 0 # turn time has expired stopTurnTimer(gameId) if gameSession.status == SDK.GameStatus.new # force draw starting hand with current cards for player in gameSession.players if not player.getHasStartingHand() Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: mulligan timer up, submitting player #{player.playerId.blue} mulligan".red drawStartingHandAction = player.actionDrawStartingHand([]) gameSession.executeAction(drawStartingHandAction) else if gameSession.status == SDK.GameStatus.active # force end turn Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: turn timer up, submitting player #{gameSession.getCurrentPlayerId().blue} turn".red endTurnAction = gameSession.actionEndTurn() gameSession.executeAction(endTurnAction) else # if the turn timer has not expired, just send the time tick over to all clients totalStepCount = gameSession.getStepCount() - games[gameId].opponentEventDataBuffer.length emitGameEvent(null,gameId,{type: EVENTS.turn_time, time: turnTimeRemainingInSeconds, timestamp: Date.now(), stepCount: totalStepCount}) ###* # ... # @public # @param {Object} gameId The game ID. ### restartSpectatorDelayedGameInterval = (gameId) -> stopSpectatorDelayedGameInterval(gameId) Logger.module("IO").debug "[G:#{gameId}]", "restartSpectatorDelayedGameInterval" if games[gameId].spectateIsDelayed games[gameId].spectatorDelayTimer = setInterval((()-> onSpectatorDelayedGameTick(gameId)), 500) ###* # ... # @public # @param {Object} gameId The game ID. ### stopSpectatorDelayedGameInterval = (gameId) -> Logger.module("IO").debug "[G:#{gameId}]", "stopSpectatorDelayedGameInterval" clearInterval(games[gameId].spectatorDelayTimer) ###* # Ticks the spectator delayed game and usually flushes the buffer by calling `flushSpectatorNetworkEventBuffer`. # @public # @param {Object} gameId The game for which to iterate the time. ### onSpectatorDelayedGameTick = (gameId) -> if not games[gameId] Logger.module("Game").debug "onSpectatorDelayedGameTick() -> game [G:#{gameId}] seems to be destroyed. Stopping ticks." stopSpectatorDelayedGameInterval(gameId) return _logSpectatorTickInfo(gameId) # flush anything in the spectator buffer flushSpectatorNetworkEventBuffer(gameId) ###* # Runs actions delayed in the spectator buffer. # @public # @param {Object} gameId The game for which to iterate the time. ### flushSpectatorNetworkEventBuffer = (gameId) -> # if there is anything in the buffer if games[gameId].spectatorGameEventBuffer.length > 0 # Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer()" # remove all the NULLED out actions games[gameId].spectatorGameEventBuffer = _.compact(games[gameId].spectatorGameEventBuffer) # loop through the actions in order for eventData,i in games[gameId].spectatorGameEventBuffer timestamp = eventData.timestamp || eventData.step?.timestamp # if we are not delaying events or if the event time exceeds the delay show it to spectators if not games[gameId].spectateIsDelayed || timestamp and moment().utc().valueOf() - timestamp > games[gameId].spectateDelay # null out the event that is about to be broadcast so it can be compacted later games[gameId].spectatorGameEventBuffer[i] = null if (eventData.step) Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> broadcasting spectator step #{eventData.type} - #{eventData.step?.action?.type}" if games[gameId].spectateIsDelayed step = games[gameId].spectatorDelayedGameSession.deserializeStepFromFirebase(eventData.step) games[gameId].spectatorDelayedGameSession.executeAuthoritativeStep(step) # NOTE: we should be OK to contiue to use the eventData here since indices of all actions are the same becuase the delayed game sessions is running as non-authoriative # send events over to spectators of current player for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"] Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.name} to player's spectators" socket = io.sockets.connected[socketId] if socket? and socket.playerId == eventData.step.playerId # scrub the action data. this should not be skipped since some actions include entire deck that needs to be scrubbed because we don't want spectators deck sniping eventDataCopy = JSON.parse(JSON.stringify(eventData)) # TODO: we use session to scrub here but might need to use the delayed session UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId, true) socket.emit EVENTS.network_game_event, eventDataCopy # skip processing anything for the opponent if this is a RollbackToSnapshotAction since only the sender cares about that one if eventData.step.action.type == SDK.RollbackToSnapshotAction.type return # start buffering events until a followup is complete for the opponent since players can cancel out of a followup games[gameId].spectatorOpponentEventDataBuffer.push(eventData) # if we are delayed then check the delayed game session for if we are buffering, otherwise use the primary isSpectatorGameSessionBufferingFollowups = (games[gameId].spectateIsDelayed and games[gameId].spectatorDelayedGameSession?.getIsBufferingEvents()) || games[gameId].session.getIsBufferingEvents() Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> opponentEventDataBuffer at #{games[gameId].spectatorOpponentEventDataBuffer.length} ... buffering: #{isSpectatorGameSessionBufferingFollowups}" # if we have anything in the buffer and we are currently not buffering, flush the buffer over to your opponent's spectators if games[gameId].spectatorOpponentEventDataBuffer.length > 0 and !isSpectatorGameSessionBufferingFollowups # copy buffer and reset opponentEventDataBuffer = games[gameId].spectatorOpponentEventDataBuffer.slice(0) games[gameId].spectatorOpponentEventDataBuffer.length = 0 # broadcast whatever's in the buffer to the opponent _.each(opponentEventDataBuffer, (eventData) -> Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.name} to opponent's spectators" for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"] socket = io.sockets.connected[socketId] if socket? and socket.playerId != eventData.step.playerId eventDataCopy = JSON.parse(JSON.stringify(eventData)) # always scrub steps for sensitive data from opponent's spectator perspective UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId, true) socket.emit EVENTS.network_game_event, eventDataCopy ) else io.to("spectate-#{gameId}").emit EVENTS.network_game_event, eventData _logSpectatorTickInfo = _.debounce((gameId)-> Logger.module("Game").debug "onSpectatorDelayedGameTick() ... #{games[gameId]?.spectatorGameEventBuffer?.length} buffered" if games[gameId]?.spectatorGameEventBuffer for eventData,i in games[gameId]?.spectatorGameEventBuffer Logger.module("Game").debug "onSpectatorDelayedGameTick() eventData: ",eventData , 1000) ###* # Emit/Broadcast game event to appropriate destination. # @public # @param {Socket} event Originating socket. # @param {String} gameId The game id for which to broadcast. # @param {Object} eventData Data to broadcast. ### emitGameEvent = (fromSocket,gameId,eventData)-> if games[gameId]? if eventData.type == EVENTS.step Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> step #{eventData.step?.index?.toString().yellow} with timestamp #{eventData.step?.timestamp} and action #{eventData.step?.action?.type}" # only broadcast valid steps if eventData.step? and eventData.step.timestamp? and eventData.step.action? # send the step to the owner for socketId,connected of io.sockets.adapter.rooms[gameId] socket = io.sockets.connected[socketId] if socket? and socket.playerId == eventData.step.playerId eventDataCopy = JSON.parse(JSON.stringify(eventData)) # always scrub steps for sensitive data from player perspective UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId) Logger.module("IO").debug "[G:#{gameId}]", "emitGameEvent -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.type} to origin" socket.emit EVENTS.network_game_event, eventDataCopy # NOTE: don't BREAK here because there is a potential case that during reconnection 3 sockets are connected: # 2 for this current reconnecting player and 1 for the opponent # breaking here would essentially result in only the DEAD socket in process of disconnecting receiving the event # break # buffer actions for the opponent other than a rollback action since that should clear the buffer during followups and there's no need to be sent to the opponent # essentially: skip processing anything for the opponent if this is a RollbackToSnapshotAction since only the sender cares about that one if eventData.step.action.type != SDK.RollbackToSnapshotAction.type # start buffering events until a followup is complete for the opponent since players can cancel out of a followup games[gameId].opponentEventDataBuffer.push(eventData) # if we have anything in the buffer and we are currently not buffering, flush the buffer over to your opponent if games[gameId].opponentEventDataBuffer.length > 0 and !games[gameId].session.getIsBufferingEvents() # copy buffer and reset opponentEventDataBuffer = games[gameId].opponentEventDataBuffer.slice(0) games[gameId].opponentEventDataBuffer.length = 0 # broadcast whatever's in the buffer to the opponent _.each(opponentEventDataBuffer, (eventData) -> for socketId,connected of io.sockets.adapter.rooms[gameId] socket = io.sockets.connected[socketId] if socket? and socket.playerId != eventData.step.playerId eventDataCopy = JSON.parse(JSON.stringify(eventData)) # always scrub steps for sensitive data from player perspective UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId) Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.type} to opponent" socket.emit EVENTS.network_game_event, eventDataCopy ) else if eventData.type == EVENTS.invalid_action # send the invalid action notification to the owner for socketId,connected of io.sockets.adapter.rooms[gameId] socket = io.sockets.connected[socketId] if socket? and socket.playerId == eventData.playerId eventDataCopy = JSON.parse(JSON.stringify(eventData)) socket.emit EVENTS.network_game_event, eventDataCopy # NOTE: don't BREAK here because there is a potential case that during reconnection 3 sockets are connected: # 2 for this current reconnecting player and 1 for the opponent # breaking here would essentially result in only the DEAD socket in process of disconnecting receiving the event else if eventData.type == EVENTS.network_game_hover or eventData.type == EVENTS.network_game_select or eventData.type == EVENTS.network_game_mouse_clear or eventData.type == EVENTS.show_emote # save the player id of this event eventData.playerId ?= fromSocket?.playerId eventData.timestamp = moment().utc().valueOf() # mouse events, emotes, etc should be saved and persisted to S3 for replays games[gameId].mouseAndUIEvents ?= [] games[gameId].mouseAndUIEvents.push(eventData) if fromSocket? # send it along to other connected sockets in the game room fromSocket.broadcast.to(gameId).emit EVENTS.network_game_event, eventData else # send to all sockets connected to the game room io.to(gameId).emit EVENTS.network_game_event, eventData # push a deep clone of the event data to the spectator buffer if games[gameId]?.spectateIsRunning spectatorEventDataCopy = JSON.parse(JSON.stringify(eventData)) games[gameId].spectatorGameEventBuffer.push(spectatorEventDataCopy) # if we're not running a timed delay, just flush everything now if not games[gameId]?.spectateIsDelayed flushSpectatorNetworkEventBuffer(gameId) ### # start a game session if one doesn't exist and call a completion handler when done # @public # @param {Object} gameId The game ID to load. # @param {Function} onComplete Callback when done. ### initGameSession = (gameId,onComplete) -> if games[gameId]?.loadingPromise return games[gameId].loadingPromise # setup local cache reference if none already there if not games[gameId] games[gameId] = opponentEventDataBuffer:[] connectedPlayers:[] session:null connectedSpectators:[] spectateIsRunning:false spectateIsDelayed:false spectateDelay:30000 spectatorGameEventBuffer:[] spectatorOpponentEventDataBuffer:[] spectatorDelayedGameSession:null turnTimerStartedAt: 0 turnTimeTickAt: 0 turnTimeRemaining: 0 turnTimeBonus: 0 # return game session from redis games[gameId].loadingPromise = Promise.all([ GameManager.loadGameSession(gameId) GameManager.loadGameMouseUIData(gameId) ]) .spread (gameData,mouseData)-> return [ JSON.parse(gameData) JSON.parse(mouseData) ] .spread (gameDataIn,mouseData) -> Logger.module("IO").log "[G:#{gameId}]", "initGameSession -> loaded game data for game:#{gameId}" # deserialize game session gameSession = SDK.GameSession.create() gameSession.setIsRunningAsAuthoritative(true) gameSession.deserializeSessionFromFirebase(gameDataIn) if gameSession.isOver() throw new Error("Game is already over!") # store session games[gameId].session = gameSession # store mouse and ui event data games[gameId].mouseAndUIEvents = mouseData saveGameCount(++gameCount) # in case the server restarted or loading data for first time, set the last action at timestamp for both players to now # this timestamp is used to shorten turn timer if player has not made any moves for a long time _.each(gameSession.players,(player)-> player.setLastActionTakenAt(Date.now()) ) # this is ugly but a simple way to subscribe to turn change events to save the game session subscribeToGameSessionEvents(gameId) # start the turn timer restartTurnTimer(gameId) return Promise.resolve([ games[gameId].session ]) .catch (error) -> Logger.module("IO").log "[G:#{gameId}]", "initGameSession:: error: #{JSON.stringify(error.message)}".red Logger.module("IO").log "[G:#{gameId}]", "initGameSession:: error stack: #{error.stack}".red # Report error to exceptionReporter with gameId exceptionReporter.notify(error, { errorName: "initGameSession Error", severity: "error", game: { id: gameId } }) throw error ### # start a spectator game session if one doesn't exist and call a completion handler when done # @public # @param {Object} gameId The game ID to load. # @param {Function} onComplete Callback when done. ### initSpectatorGameSession = (gameId)-> if not games[gameId] return Promise.reject(new Error("This game is no longer in progress")) return Promise.resolve() .then ()-> # if we're not already running spectate systems if not games[gameId].spectateIsRunning # mark that we are running spectate systems games[gameId].spectateIsRunning = true # if we're in the middle of a followup and we have some buffered events, we need to copy them over to the spectate buffer if games[gameId].session.getIsBufferingEvents() and games[gameId].opponentEventDataBuffer.length > 0 games[gameId].spectatorOpponentEventDataBuffer.length = 0 for eventData in games[gameId].opponentEventDataBuffer eventDataCopy = JSON.parse(JSON.stringify(eventData)) games[gameId].spectatorOpponentEventDataBuffer.push(eventDataCopy) if games[gameId].spectateIsDelayed and not games[gameId].spectatorDelayedGameSession Logger.module("...").log "[G:#{gameId}]", "initSpectatorDelayedGameSession() -> creating delayed game session" # create delayedGameDataIn = games[gameId].session.serializeToJSON(games[gameId].session) delayedGameSession = SDK.GameSession.create() delayedGameSession.setIsRunningAsAuthoritative(false) delayedGameSession.deserializeSessionFromFirebase(JSON.parse(delayedGameDataIn)) delayedGameSession.gameId = "SPECTATE:#{delayedGameSession.gameId}" games[gameId].spectatorDelayedGameSession = delayedGameSession # start timer to execute delayed / buffered spectator game events restartSpectatorDelayedGameInterval(gameId) return Promise.resolve(games[gameId].spectatorDelayedGameSession) else return Promise.resolve(games[gameId].session) ###* * Handler for before a game session rolls back to a snapshot. ### onBeforeRollbackToSnapshot = (event) -> # clear the buffer just before rolling back gameSession = event.gameSession gameId = gameSession.gameId game = games[gameId] if game? game.opponentEventDataBuffer.length = 0 # TODO: this will break delayed game session, needs a recode game.spectatorOpponentEventDataBuffer.length = 0 ###* * Handler for a game session step. ### onStep = (event) -> gameSession = event.gameSession gameId = gameSession.gameId game = games[gameId] if game? step = event.step if step? and step.timestamp? and step.action? # send out step events stepEventData = {type: EVENTS.step, step: JSON.parse(game.session.serializeToJSON(step))} emitGameEvent(null, gameId, stepEventData) # special action cases action = step.action if action instanceof SDK.EndTurnAction # save game on end turn # delay so that we don't block sending the step back to the players _.delay((()-> if games[gameId]? and games[gameId].session? GameManager.saveGameSession(gameId, games[gameId].session.serializeToJSON(games[gameId].session)) ), 500) else if action instanceof SDK.StartTurnAction # restart the turn timer whenever a turn starts restartTurnTimer(gameId) else if action instanceof SDK.DrawStartingHandAction # restart turn timer if both players have a starting hand and this step is for a DrawStartingHandAction bothPlayersHaveStartingHand = _.reduce(game.session.players,((memo,player)-> memo && player.getHasStartingHand()),true) if bothPlayersHaveStartingHand restartTurnTimer(gameId) if action.getIsAutomatic() and !game.session.getIsFollowupActive() # add bonus to turn time for every automatic step # unless followup is active, to prevent rollbacks for infinite turn time # bonus as a separate parameter accounts for cases such as: # - battle pet automatic actions eating up your own time # - queuing up many actions and ending turn quickly to eat into opponent's time game.turnTimeBonus += 2000 # when game is over and we have the final step # we cannot archive game until final step event # because otherwise step won't be finished/signed correctly # so we must do this on step event and not on game_over event if game.session.status == SDK.GameStatus.over # stop any turn timers stopTurnTimer(gameId) if !game.isArchived? game.isArchived = true afterGameOver(gameId, game.session, game.mouseAndUIEvents) ###* * Handler for an invalid action. ### onInvalidAction = (event) -> # safety fallback: if player attempts to make an invalid explicit action, notify that player only gameSession = event.gameSession gameId = gameSession.gameId game = games[gameId] if game? action = event.action if !action.getIsImplicit() #Logger.module("...").log "[G:#{gameId}]", "onInvalidAction -> INVALID ACTION: #{action.getLogName()} / VALIDATED BY: #{action.getValidatorType()} / MESSAGE: #{action.getValidationMessage()}" invalidActionEventData = { type: EVENTS.invalid_action, playerId: action.getOwnerId(), action: JSON.parse(game.session.serializeToJSON(action)), validatorType: event.validatorType, validationMessage: event.validationMessage, validationMessagePosition: event.validationMessagePosition, desync: gameSession.isActive() and gameSession.getCurrentPlayerId() == action.getOwnerId() and gameSession.getTurnTimeRemaining() > CONFIG.TURN_DURATION_LATENCY_BUFFER } emitGameEvent(null, gameId, invalidActionEventData) ### # Subscribes to the gamesession's event bus. # Can be called multiple times in order to re-subscribe. # @public # @param {Object} gameId The game ID to subscribe for. ### subscribeToGameSessionEvents = (gameId)-> Logger.module("...").debug "[G:#{gameId}]", "subscribeToGameSessionEvents -> subscribing to GameSession events" game = games[gameId] if game? # unsubscribe from previous unsubscribeFromGameSessionEvents(gameId) # listen for game events game.session.getEventBus().on(EVENTS.before_rollback_to_snapshot, onBeforeRollbackToSnapshot) game.session.getEventBus().on(EVENTS.step, onStep) game.session.getEventBus().on(EVENTS.invalid_action, onInvalidAction) ### # Unsubscribe from event listeners on the game session for this game ID. # @public # @param {String} gameId The game ID that needs to be unsubscribed. ### unsubscribeFromGameSessionEvents = (gameId)-> Logger.module("...").debug "[G:#{gameId}]", "unsubscribeFromGameSessionEvents -> un-subscribing from GameSession events" game = games[gameId] if game? game.session.getEventBus().off(EVENTS.before_rollback_to_snapshot, onBeforeRollbackToSnapshot) game.session.getEventBus().off(EVENTS.step, onStep) game.session.getEventBus().off(EVENTS.invalid_action, onInvalidAction) ### # must be called after game is over # processes a game, saves to redis, and kicks-off post-game processing jobs # @public # @param {String} gameId The game ID that is over. # @param {Object} gameSession The game session data. # @param {Array} mouseAndUIEvents The mouse and UI events for this game. ### afterGameOver = (gameId, gameSession, mouseAndUIEvents) -> Logger.module("GAME-OVER").log "[G:#{gameId}]", "---------- ======= GAME #{gameId} OVER ======= ---------".green # Update User Ranking, Progression, Quests, Stats updateUser = (userId, opponentId, gameId, factionId, generalId, isWinner, isDraw, ticketId) -> Logger.module("GAME-OVER").log "[G:#{gameId}]", "UPDATING user #{userId}. (winner:#{isWinner})" player = gameSession.getPlayerById(userId) isFriendly = gameSession.isFriendly() # get game type for user gameType = gameSession.getGameType() if gameType == SDK.GameType.Casual and player.getIsRanked() # casual games should be processed as ranked for ranked players gameType = SDK.GameType.Ranked # check for isUnscored isUnscored = false # calculate based on number of resign status and number of actions # if the game didn't have a single turn, mark the game as unscored if gameSession.getPlayerById(userId).hasResigned and gameSession.getTurns().length == 0 Logger.module("GAME-OVER").debug "[G:#{gameId}]", "User: #{userId} CONCEDED a game with 0 turns. Marking as UNSCORED".yellow isUnscored = true else if not isWinner and not isDraw # otherwise check how many actions the player took playerActionCount = 0 meaningfulActionCount = 0 moveActionCount = 0 for a in gameSession.getActions() # explicit actions if a.getOwnerId() == userId && a.getIsImplicit() == false playerActionCount++ # meaningful actions if a instanceof SDK.AttackAction if a.getTarget().getIsGeneral() meaningfulActionCount += 2 else meaningfulActionCount += 1 if a instanceof SDK.PlayCardFromHandAction or a instanceof SDK.PlaySignatureCardAction meaningfulActionCount += 1 if a instanceof SDK.BonusManaAction meaningfulActionCount += 2 # move actions if a instanceof SDK.MoveAction moveActionCount += 1 # more than 9 explicit actions # more than 1 move action # more than 5 meaningful actions if playerActionCount > 9 and moveActionCount > 1 and meaningfulActionCount > 4 break ### what we're looking for: * more than 9 explicit actions * more than 1 move action * more than 5 meaningful actions ... otherwise mark the game as unscored ### # Logger.module("GAME-OVER").log "[G:#{gameId}]", "User: #{userId} #{playerActionCount}, #{moveActionCount}, #{meaningfulActionCount}".cyan if playerActionCount <= 9 or moveActionCount <= 1 or meaningfulActionCount <= 4 Logger.module("GAME-OVER").debug "[G:#{gameId}]", "User: #{userId} CONCEDED a game with too few meaningful actions. Marking as UNSCORED".yellow isUnscored = true # start the job to process the game for a user return Jobs.create("update-user-post-game", name: "Update User Ranking" title: util.format("User %s :: Game %s", userId, gameId) userId: userId opponentId: opponentId gameId: gameId gameType: gameType factionId: factionId generalId: generalId isWinner: isWinner isDraw: isDraw isUnscored: isUnscored ticketId: ticketId ).removeOnComplete(true) # wait to save job until ready to process updateUsersRatings = (player1UserId, player2UserId, gameId, player1IsWinner, isDraw) -> # Detect if one player is casual playing in a ranked game player1IsRanked = gameSession.getPlayerById(player1UserId).getIsRanked() player2IsRanked = gameSession.getPlayerById(player2UserId).getIsRanked() gameType = gameSession.getGameType() if gameType == SDK.GameType.Casual and (player1IsRanked || player2IsRanked) # casual games should be processed as ranked for ranked players gameType = SDK.GameType.Ranked isRanked = gameType == SDK.GameType.Ranked Logger.module("GAME-OVER").debug "[G:#{gameId}]", "UPDATING users [#{player1UserId},#{player2UserId}] ratings." # Ratings only process in NON-FRIENDLY matches where at least 1 player is rank 0 if isRanked # start the job to process the ratings for the players return Jobs.create("update-users-ratings", name: "Update User Rating" title: util.format("Users [%s,%s] :: Game %s", player1UserId,player2UserId, gameId) player1UserId: player1UserId player1IsRanked: player1IsRanked player2UserId: player2UserId player2IsRanked: player2IsRanked gameId: gameId player1IsWinner: player1IsWinner isDraw: isDraw ).removeOnComplete(true).save() else return Promise.resolve() # Save then archive game session archiveGame = (gameId, gameSession, mouseAndUIEvents) -> return Promise.all([ GameManager.saveGameMouseUIData(gameId, JSON.stringify(mouseAndUIEvents)), GameManager.saveGameSession(gameId, gameSession.serializeToJSON(gameSession)) ]).then () -> # Job: Archive Game Jobs.create("archive-game", name: "Archive Game" title: util.format("Archiving Game %s", gameId) gameId: gameId gameType: gameSession.getGameType() ).removeOnComplete(true).save() # Builds a promise for executing the user update ratings job after player update jobs have completed updateUserRatingsPromise = (updatePlayer1Job,updatePlayer2Job,player1Id,player2Id,gameId,player1IsWinner,isDraw) -> # Wait until both players update jobs have completed before updating ratings return Promise.all([ new Promise (resolve,reject) -> updatePlayer1Job.on("complete",resolve); updatePlayer1Job.on("error",reject), new Promise (resolve,reject) -> updatePlayer2Job.on("complete",resolve); updatePlayer2Job.on("error",reject) ]).then () -> updateUsersRatings(player1Id,player2Id,gameId,player1IsWinner,isDraw) .catch (error) -> Logger.module("GAME-OVER").error "[G:#{gameId}]", "ERROR: afterGameOver update player job failed #{error}".red # issue a warning to our exceptionReporter error tracker exceptionReporter.notify(error, { errorName: "afterGameOver update player job failed", severity: "error" game: id: gameId gameType: gameSession.gameType player1Id: player1Id player2Id: player2Id winnerId: winnerId loserId: loserId }) # gamesession player data player1Id = gameSession.getPlayer1Id() player2Id = gameSession.getPlayer2Id() player1FactionId = gameSession.getPlayer1SetupData()?.factionId player2FactionId = gameSession.getPlayer2SetupData()?.factionId player1GeneralId = gameSession.getPlayer1SetupData()?.generalId player2GeneralId = gameSession.getPlayer2SetupData()?.generalId player1TicketId = gameSession.getPlayer1SetupData()?.ticketId player2TicketId = gameSession.getPlayer2SetupData()?.ticketId winnerId = gameSession.getWinnerId() loserId = gameSession.getWinnerId() player1IsWinner = (player1Id == winnerId) isDraw = if !winnerId? then true else false # update promises promises = [] # update users updatePlayer1Job = updateUser(player1Id,player2Id,gameId,player1FactionId,player1GeneralId,(player1Id == winnerId),isDraw,player1TicketId) updatePlayer2Job = updateUser(player2Id,player1Id,gameId,player2FactionId,player2GeneralId,(player2Id == winnerId),isDraw,player2TicketId) # wait until both players update jobs have completed before updating ratings promises.push(updateUserRatingsPromise(updatePlayer1Job,updatePlayer2Job,player1Id,player2Id,gameId,player1IsWinner,isDraw)) updatePlayer1Job.save() updatePlayer2Job.save() # archive game promises.push(archiveGame(gameId, gameSession, mouseAndUIEvents)) # execute promises Promise.all(promises) .then () -> Logger.module("GAME-OVER").debug "[G:#{gameId}]", "afterGameOver done, game is being archived".green .catch (error) -> Logger.module("GAME-OVER").error "[G:#{gameId}]", "ERROR: afterGameOver failed #{error}".red # issue a warning to exceptionReporter exceptionReporter.notify(error, { errorName: "afterGameOver failed", severity: "error" game: id: gameId gameType: gameSession.getGameType() player1Id: player1Id player2Id: player2Id winnerId: winnerId loserId: loserId }) ### Shutdown Handler ### shutdown = () -> Logger.module("SERVER").log "Shutting down game server." Logger.module("SERVER").log "Active Players: #{playerCount}." Logger.module("SERVER").log "Active Games: #{gameCount}." if !config.get('consul.enabled') process.exit(0) return Consul.getReassignmentStatus() .then (reassign) -> if reassign == false Logger.module("SERVER").log "Reassignment disabled - exiting." process.exit(0) # Build an array of game IDs ids = [] _.each games, (game, id) -> ids.push(id) # Map to save each game to Redis before shutdown return Promise.map ids, (id) -> serializedData = games[id].session.serializeToJSON(games[id].session) return GameManager.saveGameSession(id, serializedData) .then () -> return Consul.getHealthyServers() .then (servers) -> # Filter 'yourself' from list of nodes filtered = _.reject servers, (server)-> return server["Node"]?["Node"] == os.hostname() if filtered.length == 0 Logger.module("SERVER").log "No servers available - exiting without re-assignment." process.exit(1) random_node = _.sample(filtered) node_name = random_node["Node"]?["Node"] return Consul.kv.get("nodes/#{node_name}/public_ip") .then (newServerIp) -> # Development override for testing, bounces between port 9000 & 9001 if config.isDevelopment() port = 9001 if config.get('port') is 9000 port = 9000 if config.get('port') is 9001 newServerIp = "127.0.0.1:#{port}" msg = "Server is shutting down. You will be reconnected automatically." io.emit "game_server_shutdown", {msg:msg,ip:newServerIp} Logger.module("SERVER").log "Players reconnecting to: #{newServerIp}" Logger.module("SERVER").log "Re-assignment complete. Exiting." process.exit(0) .catch (err) -> Logger.module("SERVER").log "Re-assignment failed: #{err.message}. Exiting." process.exit(1) process.on "SIGTERM", shutdown process.on "SIGINT", shutdown process.on "SIGHUP", shutdown process.on "SIGQUIT", shutdown
183371
### Game Server Pieces ### fs = require 'fs' os = require 'os' util = require 'util' _ = require 'underscore' colors = require 'colors' # used for console message coloring jwt = require 'jsonwebtoken' io = require 'socket.io' ioJwt = require 'socketio-jwt' Promise = require 'bluebird' kue = require 'kue' moment = require 'moment' request = require 'superagent' # Our modules shutdown = require './shutdown' SDK = require '../app/sdk.coffee' Logger = require '../app/common/logger.coffee' EVENTS = require '../app/common/event_types' UtilsGameSession = require '../app/common/utils/utils_game_session.coffee' exceptionReporter = require '@counterplay/exception-reporter' # lib Modules Consul = require './lib/consul' # Configuration object config = require '../config/config.js' env = config.get('env') firebaseToken = config.get('firebaseToken') # Boots up a basic HTTP server on port 8080 # Responds to /health endpoint with status 200 # Otherwise responds with status 404 Logger = require '../app/common/logger.coffee' CONFIG = require '../app/common/config' http = require 'http' url = require 'url' Promise = require 'bluebird' # perform DNS health check dnsHealthCheck = () -> if config.isDevelopment() return Promise.resolve({healthy: true}) nodename = "#{config.get('env')}-#{os.hostname().split('.')[0]}" return Consul.kv.get("nodes/#{nodename}/dns_name") .then (dnsName) -> return new Promise (resolve, reject) -> request.get("https://#{dnsName}/health") .end (err, res) -> if err return resolve({dnsName: dnsName, healthy: false}) if res? && res.status == 200 return resolve({dnsName: dnsName, healthy: true}) return ({dnsName: dnsName, healthy: false}) .catch (e) -> return {healthy: false} # create http server and respond to /health requests server = http.createServer (req, res) -> pathname = url.parse(req.url).pathname if pathname == '/health' Logger.module("GAME SERVER").debug "HTTP Health Ping" res.statusCode = 200 res.write JSON.stringify({players: playerCount, games: gameCount}) res.end() else res.statusCode = 404 res.end() # io server setup, binds to http server io = require('socket.io')().listen(server, { cors: { origin: "*" } }) io.use( ioJwt.authorize( secret:firebaseToken timeout: 15000 ) ) module.exports = io server.listen config.get('game_port'), () -> Logger.module("GAME SERVER").log "GAME Server <b>#{os.hostname()}</b> started." # redis {Redis, Jobs, GameManager} = require './redis/' # server id for this game server serverId = os.hostname() # the 'games' hash maps game IDs to References for those games games = {} # save some basic stats about this server into redis playerCount = 0 gameCount = 0 # turn times MAX_TURN_TIME = (CONFIG.TURN_DURATION + CONFIG.TURN_DURATION_LATENCY_BUFFER) * 1000.0 MAX_TURN_TIME_INACTIVE = (CONFIG.TURN_DURATION_INACTIVE + CONFIG.TURN_DURATION_LATENCY_BUFFER) * 1000.0 savePlayerCount = (playerCount) -> Redis.hsetAsync("servers:#{serverId}", "players", playerCount) saveGameCount = (gameCount) -> Redis.hsetAsync("servers:#{serverId}", "games", gameCount) # error 'domain' to deal with io.sockets uncaught errors d = require('domain').create() d.on 'error', shutdown.errorShutdown d.add(io.sockets) # health ping on socket namespace /health healthPing = io .of '/health' .on 'connection', (socket) -> socket.on 'ping', () -> Logger.module("GAME SERVER").debug "socket.io Health Ping" socket.emit 'pong' # run main io.sockets inside of the domain d.run () -> io.sockets.on "authenticated", (socket) -> # add the socket to the error domain d.add(socket) # Socket is now autheticated, continue to bind other handlers Logger.module("IO").debug "DECODED TOKEN ID: #{socket.decoded_token.d.id.blue}" savePlayerCount(++playerCount) # Send message to user that connection is succesful socket.emit "connected", message: "Successfully connected to server" # Bind socket event handlers socket.on EVENTS.join_game, onGamePlayerJoin socket.on EVENTS.spectate_game, onGameSpectatorJoin socket.on EVENTS.leave_game, onGameLeave socket.on EVENTS.network_game_event, onGameEvent socket.on "disconnect", onGameDisconnect getConnectedSpectatorsDataForGamePlayer = (gameId,playerId)-> spectators = [] for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"] socket = io.sockets.connected[socketId] if socket.playerId == playerId spectators.push({ id:socket.spectatorId, playerId:socket.playerId, username:socket.spectateToken?.u }) return spectators ### # socket handler for players joining game # @public # @param {Object} requestData Plain JS object with socket event data. ### onGamePlayerJoin = (requestData) -> # request parameters gameId = requestData.gameId playerId = requestData.playerId Logger.module("IO").debug "[G:#{gameId}]", "join_game -> player:#{requestData.playerId} is joining game:#{requestData.gameId}".cyan # you must have a playerId if not playerId Logger.module("IO").error "[G:#{gameId}]", "join_game -> REFUSING JOIN: A player #{playerId.blue} is not valid".red @emit "join_game_response", error:"Your player id seems to be blank (has your login expired?), so we can't join you to the game." return # must have a gameId if not gameId Logger.module("IO").error "[G:#{gameId}]", "join_game -> REFUSING JOIN: A gameId #{gameId.blue} is not valid".red @emit "join_game_response", error:"Invalid Game ID." return # if someone is trying to join a game they don't belong to as a player they are not authenticated as if @.decoded_token.d.id != playerId Logger.module("IO").error "[G:#{gameId}]", "join_game -> REFUSING JOIN: A player #{@.decoded_token.<EMAIL>.blue} is attempting to join a game as #{playerId.blue}".red @emit "join_game_response", error:"Your player id does not match the one you requested to join a game with. Are you sure you're joining the right game?" return # if a client is already in another game, leave it playerLeaveGameIfNeeded(this) # if this client already exists in this game, disconnect duplicate client for socketId,connected of io.sockets.adapter.rooms[gameId] socket = io.sockets.connected[socketId] if socket? and socket.playerId == playerId Logger.module("IO").error "[G:#{gameId}]", "join_game -> detected duplicate connection to #{gameId} GameSession for #{playerId.blue}. Disconnecting duplicate...".cyan playerLeaveGameIfNeeded(socket, silent=true) # initialize a server-side game session and join it initGameSession(gameId) .bind @ .spread (gameSession) -> #Logger.module("IO").debug "[G:#{gameId}]", "join_game -> players in data: ", gameSession.players # player player = _.find(gameSession.players, (p) -> return p.playerId == playerId) # get the opponent based on the game session data opponent = _.find(gameSession.players, (p) -> return p.playerId != playerId) Logger.module("IO").debug "[G:#{gameId}]", "join_game -> Got #{gameId} GameSession data #{playerId.blue}.".cyan if not player # oops looks like this player does not exist in the requested game # let the socket know we had an error @emit "join_game_response", error:"could not join game because your player id could not be found" # destroy the game data loaded so far if the opponent can't be defined and no one else is connected Logger.module("IO").error "[G:#{gameId}]", "onGameJoin -> DESTROYING local game cache due to join error".red destroyGameSessionIfNoConnectionsLeft(gameId) # stop any further processing return else if not opponent? # oops, looks like we can'f find an opponent in the game session? Logger.module("IO").error "[G:#{gameId}]", "join_game -> game #{gameId} ERROR: could not find opponent for #{playerId.blue}.".red # let the socket know we had an error @emit "join_game_response", error:"could not join game because the opponent could not be found" # issue a warning to our exceptionReporter error tracker exceptionReporter.notify(new Error("Error joining game: could not find opponent"), { severity: "warning" user: id: playerId game: id: gameId player1Id: gameSession?.players[0].playerId player2Id: gameSession?.players[1].playerId }) # destroy the game data loaded so far if the opponent can't be defined and no one else is connected Logger.module("IO").error "[G:#{gameId}]", "onGameJoin -> DESTROYING local game cache due to join error".red destroyGameSessionIfNoConnectionsLeft(gameId) # stop any further processing return else # rollback if it is this player's followup # this can happen if a player reconnects without properly disconnecting if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() == playerId gameSession.executeAction(gameSession.actionRollbackSnapshot()) # set some parameters for the socket @gameId = gameId @playerId = playerId # join game room @join(gameId) # update user count for game room games[gameId].connectedPlayers.push(playerId) Logger.module("IO").debug "[G:#{gameId}]", "join_game -> Game #{gameId} connected players so far: #{games[gameId].connectedPlayers.length}." # if only one player is in so far, start the disconnection timer if games[gameId].connectedPlayers.length == 1 # start disconnected player timeout for game startDisconnectedPlayerTimeout(gameId,opponent.playerId) else if games[gameId].connectedPlayers.length == 2 # clear timeout when we get two players clearDisconnectedPlayerTimeout(gameId) # prepare and scrub game session data for this player # if a followup is active and it isn't this player's followup, send them the rollback snapshot if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() != playerId gameSessionData = JSON.parse(gameSession.getRollbackSnapshotData()) else gameSessionData = JSON.parse(gameSession.serializeToJSON(gameSession)) UtilsGameSession.scrubGameSessionData(gameSession, gameSessionData, playerId) # respond to client with success and a scrubbed copy of the game session @emit "join_game_response", message: "successfully joined game" gameSessionData: gameSessionData connectedPlayers:games[gameId].connectedPlayers connectedSpectators: getConnectedSpectatorsDataForGamePlayer(gameId,playerId) # broadcast join to any other connected players @broadcast.to(gameId).emit("player_joined",playerId) .catch (e) -> Logger.module("IO").error "[G:#{gameId}]", "join_game -> player:#{playerId} failed to join game, error: #{e.message}".red Logger.module("IO").error "[G:#{gameId}]", "join_game -> player:#{playerId} failed to join game, error stack: #{e.stack}".red # if we didn't join a game, broadcast a failure @emit "join_game_response", error:"Could not join game: " + e?.message ### # socket handler for spectators joining game # @public # @param {Object} requestData Plain JS object with socket event data. ### onGameSpectatorJoin = (requestData) -> # request parameters # TODO : Sanitize these parameters to prevent crash if gameId = null gameId = requestData.gameId spectatorId = requestData.spectatorId playerId = requestData.playerId spectateToken = null # verify - synchronous try spectateToken = jwt.verify(requestData.spectateToken, firebaseToken) catch error Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> ERROR decoding spectate token: #{error?.message}".red if not spectateToken or spectateToken.b?.length == 0 Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A specate token #{spectateToken} is not valid".red @emit "spectate_game_response", error:"Your spectate token is invalid, so we can't join you to the game." return Logger.module("IO").debug "[G:#{gameId}]", "spectate_game -> token contents: ", spectateToken.b Logger.module("IO").debug "[G:#{gameId}]", "spectate_game -> playerId: ", playerId if not _.contains(spectateToken.b,playerId) Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: You do not have permission to specate this game".red @emit "spectate_game_response", error:"You do not have permission to specate this game." return # must have a spectatorId if not spectatorId Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A spectator #{spectatorId.blue} is not valid".red @emit "spectate_game_response", error:"Your login ID is blank (expired?), so we can't join you to the game." return # must have a playerId if not playerId Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A player #{playerId.blue} is not valid".red @emit "spectate_game_response", error:"Invalid player ID." return # must have a gameId if not gameId Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A gameId #{gameId.blue} is not valid".red @emit "spectate_game_response", error:"Invalid Game ID." return # if someone is trying to join a game they don't belong to as a player they are not authenticated as if @.decoded_token.d.id != spectatorId Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A player #{@.decoded_token.d.id.blue} is attempting to join a game as #{playerId.blue}".red @emit "spectate_game_response", error:"Your login ID does not match the one you requested to spectate the game with." return Logger.module("IO").debug "[G:#{gameId}]", "spectate_game -> spectator:#{spectatorId} is joining game:#{gameId}".cyan # if a client is already in another game, leave it spectatorLeaveGameIfNeeded(@) if games[gameId]?.connectedSpectators.length >= 10 # max out at 10 spectators @emit "spectate_game_response", error:"Maximum number of spectators already watching." return # initialize a server-side game session and join it initSpectatorGameSession(gameId) .bind @ .then (spectatorGameSession) -> # for spectators, use the delayed in-memory game session gameSession = spectatorGameSession Logger.module("IO").debug "[G:#{gameId}]", "spectate_game -> Got #{gameId} GameSession data.".cyan player = _.find(gameSession.players, (p) -> return p.playerId == playerId) opponent = _.find(gameSession.players, (p) -> return p.playerId != playerId) if not player # let the socket know we had an error @emit "spectate_game_response", error:"could not join game because the player id you requested could not be found" # destroy the game data loaded so far if the opponent can't be defined and no one else is connected Logger.module("IO").error "[G:#{gameId}]", "onGameSpectatorJoin -> DESTROYING local game cache due to join error".red destroyGameSessionIfNoConnectionsLeft(gameId) # stop any further processing return else # set some parameters for the socket @gameId = gameId @spectatorId = spectatorId @spectateToken = spectateToken @playerId = playerId # join game room @join("spectate-#{gameId}") # update user count for game room games[gameId].connectedSpectators.push(spectatorId) # prepare and scrub game session data for this player # if a followup is active and it isn't this player's followup, send them the rollback snapshot if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() != playerId gameSessionData = JSON.parse(gameSession.getRollbackSnapshotData()) else gameSessionData = JSON.parse(gameSession.serializeToJSON(gameSession)) UtilsGameSession.scrubGameSessionData(gameSession, gameSessionData, playerId, true) ### # if the spectator does not have the opponent in their buddy list if not _.contains(spectateToken.b,opponent.playerId) # scrub deck data and opponent hand data by passing in opponent ID scrubGameSessionDataForSpectators(gameSession, gameSessionData, opponent.playerId) else # otherwise just scrub deck data in a way you can see both decks # scrubGameSessionDataForSpectators(gameSession, gameSessionData) # NOTE: above line is disabled for now since it does some UI jankiness since when a cardId is present the tile layer updates when the spectated opponent starts to select cards # NOTE: besides, actions will be scrubbed so this idea of watching both players only sort of works right now scrubGameSessionDataForSpectators(gameSession, gameSessionData, opponent.playerId, true) ### # respond to client with success and a scrubbed copy of the game session @emit "spectate_game_response", message: "successfully joined game" gameSessionData: gameSessionData # broadcast to the game room that a spectator has joined @broadcast.to(gameId).emit("spectator_joined",{ id: spectatorId, playerId: playerId, username: spectateToken.u }) .catch (e) -> # if we didn't join a game, broadcast a failure @emit "spectate_game_response", error:"could not join game: #{e.message}" ### # socket handler for leaving a game. # @public # @param {Object} requestData Plain JS object with socket event data. ### onGameLeave = (requestData) -> if @.spectatorId Logger.module("IO").debug "[G:#{@.gameId}]", "leave_game -> spectator #{@.spectatorId} leaving #{@.gameId}" spectatorLeaveGameIfNeeded(@) else Logger.module("IO").debug "[G:#{@.gameId}]", "leave_game -> player #{@.playerId} leaving #{@.gameId}" playerLeaveGameIfNeeded(@) ###* # This method is called every time a socket handler recieves a game event and is executed within the context of the socket (this == sending socket). # @public # @param {Object} eventData Plain JS object with event data that contains one "event". ### onGameEvent = (eventData) -> # if for some reason spectator sockets start broadcasting game events if @.spectatorId Logger.module("IO").error "[G:#{@.gameId}]", "onGameEvent :: ERROR: spectator sockets can't submit game events. (type: #{eventData.type})".red return # Logger.module("IO").log "onGameEvent -> #{JSON.stringify(eventData)}".blue if not @gameId or not games[@gameId] @emit EVENTS.network_game_error, code:500 message:"could not broadcast game event because you are not currently in a game" return # gameSession = games[@gameId].session if eventData.type == EVENTS.step #Logger.module("IO").log "[G:#{@.gameId}]", "game_step -> #{JSON.stringify(eventData.step)}".green #Logger.module("IO").log "[G:#{@.gameId}]", "game_step -> #{eventData.step?.playerId} #{eventData.step?.action?.type}".green player = _.find(gameSession.players,(p)-> p.playerId == eventData.step?.playerId) player?.setLastActionTakenAt(Date.now()) try step = gameSession.deserializeStepFromFirebase(eventData.step) action = step.action if action? # clear out any implicit actions sent over the network and re-execute this as a fresh explicit action on the server # the reason is that we want to re-generate and re-validate all the game logic that happens as a result of this FIRST explicit action in the step action.resetForAuthoritativeExecution() # execute the action gameSession.executeAction(action) catch error Logger.module("IO").error "[G:#{@.gameId}]", "onGameStep:: error: #{JSON.stringify(error.message)}".red Logger.module("IO").error "[G:#{@.gameId}]", "onGameStep:: error stack: #{error.stack}".red # Report error to exceptionReporter with gameId + eventData exceptionReporter.notify(error, { errorName: "onGameStep Error", game: { gameId: @gameId eventData: eventData } }) # delete but don't destroy game destroyGameSessionIfNoConnectionsLeft(@gameId,true) # send error to client, forcing reconnect on client side io.to(@gameId).emit EVENTS.network_game_error, JSON.stringify(error.message) return else # transmit the non-step game events to players # step events are emitted automatically after executed on game session emitGameEvent(@, @gameId, eventData) ### # Socket Disconnect Event Handler. Handles rollback if in the middle of followup etc. # @public ### onGameDisconnect = () -> if @.spectatorId # make spectator leave game room spectatorLeaveGameIfNeeded(@) # remove the socket from the error domain, this = socket d.remove(@) else try clients_in_the_room = io.sockets.adapter.rooms[@.gameId] for clientId,socket of clients_in_the_room if socket.playerId == @.playerId Logger.module("IO").error "onGameDisconnect:: looks like the player #{@.playerId} we are trying to disconnect is still in the game #{@.gameId} room. ABORTING".red return for clientId,socket of io.sockets.connected if socket.playerId == @.playerId and not socket.spectatorId Logger.module("IO").error "onGameDisconnect:: looks like the player #{@.playerId} that allegedly disconnected is still alive and well.".red return catch error Logger.module("IO").error "onGameDisconnect:: Error #{error?.message}.".red # if we are in a buffering state # and the disconnecting player is in the middle of a followup gs = games[@gameId]?.session if gs? and gs.getIsBufferingEvents() and gs.getCurrentPlayerId() == @playerId # execute a rollback to reset server state # but do not send this action to the still connected player # because they do not care about rollbacks for the other player rollBackAction = gs.actionRollbackSnapshot() gs.executeAction(rollBackAction) # remove the socket from the error domain, this = socket d.remove(@) savePlayerCount(--playerCount) Logger.module("IO").debug "[G:#{@.gameId}]", "disconnect -> #{@.playerId}".red # if a client is already in another game, leave it playerLeaveGameIfNeeded(@) ###* * Leaves a game for a player socket if the socket is connected to a game * @public * @param {Socket} socket The socket which wants to leave a game. * @param {Boolean} [silent=false] whether to disconnect silently, as in the case of duplicate connections for same player ### playerLeaveGameIfNeeded = (socket, silent=false) -> if socket? gameId = socket.gameId playerId = socket.playerId # if a player is in a game if gameId? and playerId? Logger.module("...").debug "[G:#{gameId}]", "playerLeaveGame -> #{playerId} has left game #{gameId}".red if !silent # broadcast that player left socket.broadcast.to(gameId).emit("player_left",playerId) # leave that game room socket.leave(gameId) # update user count for game room game = games[gameId] if game? index = game.connectedPlayers.indexOf(playerId) game.connectedPlayers.splice(index,1) if !silent # start disconnected player timeout for game startDisconnectedPlayerTimeout(gameId,playerId) # destroy game if no one is connected anymore destroyGameSessionIfNoConnectionsLeft(gameId,true) # finally clear the existing gameId socket.gameId = null ### # This function leaves a game for a spectator socket if the socket is connected to a game # @public # @param {Socket} socket The socket which wants to leave a game. ### spectatorLeaveGameIfNeeded = (socket) -> # if a client is already in another game if socket.gameId Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} leaving game #{socket.gameId}." # broadcast that you left socket.broadcast.to(socket.gameId).emit("spectator_left",{ id:socket.spectatorId, playerId:socket.playerId, username:socket.spectateToken?.u }) # leave specator game room socket.leave("spectate-#{socket.gameId}") Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} left room for game #{socket.gameId}." # update spectator count for game room if games[socket.gameId] games[socket.gameId].connectedSpectators = _.without(games[socket.gameId].connectedSpectators,socket.spectatorId) Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} removed from list of spectators #{socket.gameId}." # if no spectators left, stop the delayed game interval and destroy spectator delayed game session tearDownSpectateSystemsIfNoSpectatorsLeft(socket.gameId) # destroy game if no one is connected anymore destroyGameSessionIfNoConnectionsLeft(socket.gameId,true) remainingSpectators = games[socket.gameId]?.connectedSpectators?.length || 0 Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} has left game #{socket.gameId}. remaining spectators #{remainingSpectators}" # finally clear the existing gameId socket.gameId = null ### # This function destroys in-memory game session of there is no one left connected # @public # @param {String} gameId The ID of the game to destroy. # @param {Boolean} persist Do we need to save/archive this game? ### destroyGameSessionIfNoConnectionsLeft = (gameId,persist=false)-> if games[gameId].connectedPlayers.length == 0 and games[gameId].connectedSpectators.length == 0 clearDisconnectedPlayerTimeout(gameId) stopTurnTimer(gameId) tearDownSpectateSystemsIfNoSpectatorsLeft(gameId) Logger.module("...").debug "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft() -> no players left DESTROYING local game cache".red unsubscribeFromGameSessionEvents(gameId) # TEMP: a way to upload unfinished game data to AWS S3 Archive. For example: errored out games. if persist and games?[gameId]?.session?.status != SDK.GameStatus.over data = games[gameId].session.serializeToJSON(games[gameId].session) mouseAndUIEventsData = JSON.stringify(games[gameId].mouseAndUIEvents) Promise.all([ GameManager.saveGameSession(gameId,data), GameManager.saveGameMouseUIData(gameId,mouseAndUIEventsData), ]) .then (results) -> Logger.module("...").debug "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft -> unfinished Game Archived to S3: #{results[1]}".green .catch (error)-> Logger.module("...").error "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft -> ERROR: failed to archive unfinished game to S3 due to error #{error.message}".red delete games[gameId] saveGameCount(--gameCount) else Logger.module("...").debug "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft() -> players left: #{games[gameId].connectedPlayers.length} spectators left: #{games[gameId].connectedSpectators.length}" ### # This function stops all spectate systems if 0 spectators left. # @public # @param {String} gameId The ID of the game to tear down spectate systems. ### tearDownSpectateSystemsIfNoSpectatorsLeft = (gameId)-> # if no spectators left, stop the delayed game interval and destroy spectator delayed game session if games[gameId]?.connectedSpectators.length == 0 Logger.module("IO").debug "[G:#{gameId}]", "tearDownSpectateSystemsIfNoSpectatorsLeft() -> no spectators left, stopping spectate systems" stopSpectatorDelayedGameInterval(gameId) games[gameId].spectatorDelayedGameSession = null games[gameId].spectateIsRunning = false games[gameId].spectatorOpponentEventDataBuffer.length = 0 games[gameId].spectatorGameEventBuffer.length = 0 ### # Clears timeout for disconnected players # @public # @param {String} gameId The ID of the game to clear disconnected timeout for. ### clearDisconnectedPlayerTimeout = (gameId) -> Logger.module("IO").debug "[G:#{gameId}]", "clearDisconnectedPlayerTimeout:: for game: #{gameId}".yellow clearTimeout(games[gameId]?.disconnectedPlayerTimeout) games[gameId]?.disconnectedPlayerTimeout = null ### # Starts timeout for disconnected players # @public # @param {String} gameId The ID of the game. # @param {String} playerId The player ID for who to start the timeout. ### startDisconnectedPlayerTimeout = (gameId,playerId) -> if games[gameId]?.disconnectedPlayerTimeout? clearDisconnectedPlayerTimeout(gameId) Logger.module("IO").debug "[G:#{gameId}]", "startDisconnectedPlayerTimeout:: for #{playerId} in game: #{gameId}".yellow games[gameId]?.disconnectedPlayerTimeout = setTimeout(()-> onDisconnectedPlayerTimeout(gameId,playerId) ,60000) ### # Resigns game for disconnected player. # @public # @param {String} gameId The ID of the game. # @param {String} playerId The player ID who is resigning. ### onDisconnectedPlayerTimeout = (gameId,playerId) -> Logger.module("IO").debug "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} for game: #{gameId}" clients_in_the_room = io.sockets.adapter.rooms[gameId] for clientId,socket of clients_in_the_room if socket.playerId == playerId Logger.module("IO").error "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: looks like the player #{playerId} we are trying to dis-connect is still in the game #{gameId} room. ABORTING".red return for clientId,socket of io.sockets.connected if socket.playerId == playerId and not socket.spectatorId Logger.module("IO").error "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: looks like the player #{playerId} we are trying to disconnect is still connected but not in the game #{gameId} room.".red return # grab the relevant game session gs = games[gameId]?.session # looks like we timed out for a game that's since ended if !gs or gs?.status == SDK.GameStatus.over Logger.module("IO").error "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} timed out for FINISHED or NULL game: #{gameId}".yellow return else Logger.module("IO").debug "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} auto-resigning game: #{gameId}".yellow # resign the player player = gs.getPlayerById(playerId) resignAction = player.actionResign() gs.executeAction(resignAction) ###* # Start/Restart server side game timer for a game # @public # @param {Object} gameId The game ID. ### restartTurnTimer = (gameId) -> stopTurnTimer(gameId) game = games[gameId] if game.session? game.turnTimerStartedAt = game.turnTimeTickAt = Date.now() game.turnTimer = setInterval((()-> onGameTimeTick(gameId)),1000) ###* # Stop server side game timer for a game # @public # @param {Object} gameId The game ID. ### stopTurnTimer = (gameId) -> game = games[gameId] if game? and game.turnTimer? clearInterval(game.turnTimer) game.turnTimer = null ###* # Server side game timer. After 90 seconds it will end the turn for the current player. # @public # @param {Object} gameId The game for which to iterate the time. ### onGameTimeTick = (gameId) -> game = games[gameId] gameSession = game?.session if gameSession? # allowed turn time is 90 seconds + slop buffer that clients don't see allowed_turn_time = MAX_TURN_TIME # grab the current player player = gameSession.getCurrentPlayer() # if we're past the 2nd turn, we can start checking backwards to see how long the PREVIOUS turn for this player took if player and gameSession.getTurns().length > 2 # find the current player's previous turn allTurns = gameSession.getTurns() playersPreviousTurn = null for i in [allTurns.length-1..0] by -1 if allTurns[i].playerId == player.playerId playersPreviousTurn = allTurns[i] # gameSession.getTurns()[gameSession.getTurns().length - 3] break #Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: last action at #{player.getLastActionTakenAt()} / last turn delta #{playersPreviousTurn?.createdAt - player.getLastActionTakenAt()}".red # if this player's previous action was on a turn older than the last one if playersPreviousTurn && (playersPreviousTurn.createdAt - player.getLastActionTakenAt() > 0) # you're only allowed 15 seconds + 3 second buffer that clients don't see allowed_turn_time = MAX_TURN_TIME_INACTIVE lastTurnTimeTickAt = game.turnTimeTickAt game.turnTimeTickAt = Date.now() delta_turn_time_tick = game.turnTimeTickAt - lastTurnTimeTickAt delta_since_timer_began = game.turnTimeTickAt - game.turnTimerStartedAt game.turnTimeRemaining = Math.max(0.0, allowed_turn_time - delta_since_timer_began + game.turnTimeBonus) game.turnTimeBonus = Math.max(0.0, game.turnTimeBonus - delta_turn_time_tick) #Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: delta #{delta_turn_time_tick/1000}, #{game.turnTimeRemaining/1000} time remaining, #{game.turnTimeBonus/1000} bonus remaining" turnTimeRemainingInSeconds = Math.ceil(game.turnTimeRemaining/1000) gameSession.setTurnTimeRemaining(turnTimeRemainingInSeconds) if game.turnTimeRemaining <= 0 # turn time has expired stopTurnTimer(gameId) if gameSession.status == SDK.GameStatus.new # force draw starting hand with current cards for player in gameSession.players if not player.getHasStartingHand() Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: mulligan timer up, submitting player #{player.playerId.blue} mulligan".red drawStartingHandAction = player.actionDrawStartingHand([]) gameSession.executeAction(drawStartingHandAction) else if gameSession.status == SDK.GameStatus.active # force end turn Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: turn timer up, submitting player #{gameSession.getCurrentPlayerId().blue} turn".red endTurnAction = gameSession.actionEndTurn() gameSession.executeAction(endTurnAction) else # if the turn timer has not expired, just send the time tick over to all clients totalStepCount = gameSession.getStepCount() - games[gameId].opponentEventDataBuffer.length emitGameEvent(null,gameId,{type: EVENTS.turn_time, time: turnTimeRemainingInSeconds, timestamp: Date.now(), stepCount: totalStepCount}) ###* # ... # @public # @param {Object} gameId The game ID. ### restartSpectatorDelayedGameInterval = (gameId) -> stopSpectatorDelayedGameInterval(gameId) Logger.module("IO").debug "[G:#{gameId}]", "restartSpectatorDelayedGameInterval" if games[gameId].spectateIsDelayed games[gameId].spectatorDelayTimer = setInterval((()-> onSpectatorDelayedGameTick(gameId)), 500) ###* # ... # @public # @param {Object} gameId The game ID. ### stopSpectatorDelayedGameInterval = (gameId) -> Logger.module("IO").debug "[G:#{gameId}]", "stopSpectatorDelayedGameInterval" clearInterval(games[gameId].spectatorDelayTimer) ###* # Ticks the spectator delayed game and usually flushes the buffer by calling `flushSpectatorNetworkEventBuffer`. # @public # @param {Object} gameId The game for which to iterate the time. ### onSpectatorDelayedGameTick = (gameId) -> if not games[gameId] Logger.module("Game").debug "onSpectatorDelayedGameTick() -> game [G:#{gameId}] seems to be destroyed. Stopping ticks." stopSpectatorDelayedGameInterval(gameId) return _logSpectatorTickInfo(gameId) # flush anything in the spectator buffer flushSpectatorNetworkEventBuffer(gameId) ###* # Runs actions delayed in the spectator buffer. # @public # @param {Object} gameId The game for which to iterate the time. ### flushSpectatorNetworkEventBuffer = (gameId) -> # if there is anything in the buffer if games[gameId].spectatorGameEventBuffer.length > 0 # Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer()" # remove all the NULLED out actions games[gameId].spectatorGameEventBuffer = _.compact(games[gameId].spectatorGameEventBuffer) # loop through the actions in order for eventData,i in games[gameId].spectatorGameEventBuffer timestamp = eventData.timestamp || eventData.step?.timestamp # if we are not delaying events or if the event time exceeds the delay show it to spectators if not games[gameId].spectateIsDelayed || timestamp and moment().utc().valueOf() - timestamp > games[gameId].spectateDelay # null out the event that is about to be broadcast so it can be compacted later games[gameId].spectatorGameEventBuffer[i] = null if (eventData.step) Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> broadcasting spectator step #{eventData.type} - #{eventData.step?.action?.type}" if games[gameId].spectateIsDelayed step = games[gameId].spectatorDelayedGameSession.deserializeStepFromFirebase(eventData.step) games[gameId].spectatorDelayedGameSession.executeAuthoritativeStep(step) # NOTE: we should be OK to contiue to use the eventData here since indices of all actions are the same becuase the delayed game sessions is running as non-authoriative # send events over to spectators of current player for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"] Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.name} to player's spectators" socket = io.sockets.connected[socketId] if socket? and socket.playerId == eventData.step.playerId # scrub the action data. this should not be skipped since some actions include entire deck that needs to be scrubbed because we don't want spectators deck sniping eventDataCopy = JSON.parse(JSON.stringify(eventData)) # TODO: we use session to scrub here but might need to use the delayed session UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId, true) socket.emit EVENTS.network_game_event, eventDataCopy # skip processing anything for the opponent if this is a RollbackToSnapshotAction since only the sender cares about that one if eventData.step.action.type == SDK.RollbackToSnapshotAction.type return # start buffering events until a followup is complete for the opponent since players can cancel out of a followup games[gameId].spectatorOpponentEventDataBuffer.push(eventData) # if we are delayed then check the delayed game session for if we are buffering, otherwise use the primary isSpectatorGameSessionBufferingFollowups = (games[gameId].spectateIsDelayed and games[gameId].spectatorDelayedGameSession?.getIsBufferingEvents()) || games[gameId].session.getIsBufferingEvents() Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> opponentEventDataBuffer at #{games[gameId].spectatorOpponentEventDataBuffer.length} ... buffering: #{isSpectatorGameSessionBufferingFollowups}" # if we have anything in the buffer and we are currently not buffering, flush the buffer over to your opponent's spectators if games[gameId].spectatorOpponentEventDataBuffer.length > 0 and !isSpectatorGameSessionBufferingFollowups # copy buffer and reset opponentEventDataBuffer = games[gameId].spectatorOpponentEventDataBuffer.slice(0) games[gameId].spectatorOpponentEventDataBuffer.length = 0 # broadcast whatever's in the buffer to the opponent _.each(opponentEventDataBuffer, (eventData) -> Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.name} to opponent's spectators" for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"] socket = io.sockets.connected[socketId] if socket? and socket.playerId != eventData.step.playerId eventDataCopy = JSON.parse(JSON.stringify(eventData)) # always scrub steps for sensitive data from opponent's spectator perspective UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId, true) socket.emit EVENTS.network_game_event, eventDataCopy ) else io.to("spectate-#{gameId}").emit EVENTS.network_game_event, eventData _logSpectatorTickInfo = _.debounce((gameId)-> Logger.module("Game").debug "onSpectatorDelayedGameTick() ... #{games[gameId]?.spectatorGameEventBuffer?.length} buffered" if games[gameId]?.spectatorGameEventBuffer for eventData,i in games[gameId]?.spectatorGameEventBuffer Logger.module("Game").debug "onSpectatorDelayedGameTick() eventData: ",eventData , 1000) ###* # Emit/Broadcast game event to appropriate destination. # @public # @param {Socket} event Originating socket. # @param {String} gameId The game id for which to broadcast. # @param {Object} eventData Data to broadcast. ### emitGameEvent = (fromSocket,gameId,eventData)-> if games[gameId]? if eventData.type == EVENTS.step Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> step #{eventData.step?.index?.toString().yellow} with timestamp #{eventData.step?.timestamp} and action #{eventData.step?.action?.type}" # only broadcast valid steps if eventData.step? and eventData.step.timestamp? and eventData.step.action? # send the step to the owner for socketId,connected of io.sockets.adapter.rooms[gameId] socket = io.sockets.connected[socketId] if socket? and socket.playerId == eventData.step.playerId eventDataCopy = JSON.parse(JSON.stringify(eventData)) # always scrub steps for sensitive data from player perspective UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId) Logger.module("IO").debug "[G:#{gameId}]", "emitGameEvent -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.type} to origin" socket.emit EVENTS.network_game_event, eventDataCopy # NOTE: don't BREAK here because there is a potential case that during reconnection 3 sockets are connected: # 2 for this current reconnecting player and 1 for the opponent # breaking here would essentially result in only the DEAD socket in process of disconnecting receiving the event # break # buffer actions for the opponent other than a rollback action since that should clear the buffer during followups and there's no need to be sent to the opponent # essentially: skip processing anything for the opponent if this is a RollbackToSnapshotAction since only the sender cares about that one if eventData.step.action.type != SDK.RollbackToSnapshotAction.type # start buffering events until a followup is complete for the opponent since players can cancel out of a followup games[gameId].opponentEventDataBuffer.push(eventData) # if we have anything in the buffer and we are currently not buffering, flush the buffer over to your opponent if games[gameId].opponentEventDataBuffer.length > 0 and !games[gameId].session.getIsBufferingEvents() # copy buffer and reset opponentEventDataBuffer = games[gameId].opponentEventDataBuffer.slice(0) games[gameId].opponentEventDataBuffer.length = 0 # broadcast whatever's in the buffer to the opponent _.each(opponentEventDataBuffer, (eventData) -> for socketId,connected of io.sockets.adapter.rooms[gameId] socket = io.sockets.connected[socketId] if socket? and socket.playerId != eventData.step.playerId eventDataCopy = JSON.parse(JSON.stringify(eventData)) # always scrub steps for sensitive data from player perspective UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId) Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.type} to opponent" socket.emit EVENTS.network_game_event, eventDataCopy ) else if eventData.type == EVENTS.invalid_action # send the invalid action notification to the owner for socketId,connected of io.sockets.adapter.rooms[gameId] socket = io.sockets.connected[socketId] if socket? and socket.playerId == eventData.playerId eventDataCopy = JSON.parse(JSON.stringify(eventData)) socket.emit EVENTS.network_game_event, eventDataCopy # NOTE: don't BREAK here because there is a potential case that during reconnection 3 sockets are connected: # 2 for this current reconnecting player and 1 for the opponent # breaking here would essentially result in only the DEAD socket in process of disconnecting receiving the event else if eventData.type == EVENTS.network_game_hover or eventData.type == EVENTS.network_game_select or eventData.type == EVENTS.network_game_mouse_clear or eventData.type == EVENTS.show_emote # save the player id of this event eventData.playerId ?= fromSocket?.playerId eventData.timestamp = moment().utc().valueOf() # mouse events, emotes, etc should be saved and persisted to S3 for replays games[gameId].mouseAndUIEvents ?= [] games[gameId].mouseAndUIEvents.push(eventData) if fromSocket? # send it along to other connected sockets in the game room fromSocket.broadcast.to(gameId).emit EVENTS.network_game_event, eventData else # send to all sockets connected to the game room io.to(gameId).emit EVENTS.network_game_event, eventData # push a deep clone of the event data to the spectator buffer if games[gameId]?.spectateIsRunning spectatorEventDataCopy = JSON.parse(JSON.stringify(eventData)) games[gameId].spectatorGameEventBuffer.push(spectatorEventDataCopy) # if we're not running a timed delay, just flush everything now if not games[gameId]?.spectateIsDelayed flushSpectatorNetworkEventBuffer(gameId) ### # start a game session if one doesn't exist and call a completion handler when done # @public # @param {Object} gameId The game ID to load. # @param {Function} onComplete Callback when done. ### initGameSession = (gameId,onComplete) -> if games[gameId]?.loadingPromise return games[gameId].loadingPromise # setup local cache reference if none already there if not games[gameId] games[gameId] = opponentEventDataBuffer:[] connectedPlayers:[] session:null connectedSpectators:[] spectateIsRunning:false spectateIsDelayed:false spectateDelay:30000 spectatorGameEventBuffer:[] spectatorOpponentEventDataBuffer:[] spectatorDelayedGameSession:null turnTimerStartedAt: 0 turnTimeTickAt: 0 turnTimeRemaining: 0 turnTimeBonus: 0 # return game session from redis games[gameId].loadingPromise = Promise.all([ GameManager.loadGameSession(gameId) GameManager.loadGameMouseUIData(gameId) ]) .spread (gameData,mouseData)-> return [ JSON.parse(gameData) JSON.parse(mouseData) ] .spread (gameDataIn,mouseData) -> Logger.module("IO").log "[G:#{gameId}]", "initGameSession -> loaded game data for game:#{gameId}" # deserialize game session gameSession = SDK.GameSession.create() gameSession.setIsRunningAsAuthoritative(true) gameSession.deserializeSessionFromFirebase(gameDataIn) if gameSession.isOver() throw new Error("Game is already over!") # store session games[gameId].session = gameSession # store mouse and ui event data games[gameId].mouseAndUIEvents = mouseData saveGameCount(++gameCount) # in case the server restarted or loading data for first time, set the last action at timestamp for both players to now # this timestamp is used to shorten turn timer if player has not made any moves for a long time _.each(gameSession.players,(player)-> player.setLastActionTakenAt(Date.now()) ) # this is ugly but a simple way to subscribe to turn change events to save the game session subscribeToGameSessionEvents(gameId) # start the turn timer restartTurnTimer(gameId) return Promise.resolve([ games[gameId].session ]) .catch (error) -> Logger.module("IO").log "[G:#{gameId}]", "initGameSession:: error: #{JSON.stringify(error.message)}".red Logger.module("IO").log "[G:#{gameId}]", "initGameSession:: error stack: #{error.stack}".red # Report error to exceptionReporter with gameId exceptionReporter.notify(error, { errorName: "initGameSession Error", severity: "error", game: { id: gameId } }) throw error ### # start a spectator game session if one doesn't exist and call a completion handler when done # @public # @param {Object} gameId The game ID to load. # @param {Function} onComplete Callback when done. ### initSpectatorGameSession = (gameId)-> if not games[gameId] return Promise.reject(new Error("This game is no longer in progress")) return Promise.resolve() .then ()-> # if we're not already running spectate systems if not games[gameId].spectateIsRunning # mark that we are running spectate systems games[gameId].spectateIsRunning = true # if we're in the middle of a followup and we have some buffered events, we need to copy them over to the spectate buffer if games[gameId].session.getIsBufferingEvents() and games[gameId].opponentEventDataBuffer.length > 0 games[gameId].spectatorOpponentEventDataBuffer.length = 0 for eventData in games[gameId].opponentEventDataBuffer eventDataCopy = JSON.parse(JSON.stringify(eventData)) games[gameId].spectatorOpponentEventDataBuffer.push(eventDataCopy) if games[gameId].spectateIsDelayed and not games[gameId].spectatorDelayedGameSession Logger.module("...").log "[G:#{gameId}]", "initSpectatorDelayedGameSession() -> creating delayed game session" # create delayedGameDataIn = games[gameId].session.serializeToJSON(games[gameId].session) delayedGameSession = SDK.GameSession.create() delayedGameSession.setIsRunningAsAuthoritative(false) delayedGameSession.deserializeSessionFromFirebase(JSON.parse(delayedGameDataIn)) delayedGameSession.gameId = "SPECTATE:#{delayedGameSession.gameId}" games[gameId].spectatorDelayedGameSession = delayedGameSession # start timer to execute delayed / buffered spectator game events restartSpectatorDelayedGameInterval(gameId) return Promise.resolve(games[gameId].spectatorDelayedGameSession) else return Promise.resolve(games[gameId].session) ###* * Handler for before a game session rolls back to a snapshot. ### onBeforeRollbackToSnapshot = (event) -> # clear the buffer just before rolling back gameSession = event.gameSession gameId = gameSession.gameId game = games[gameId] if game? game.opponentEventDataBuffer.length = 0 # TODO: this will break delayed game session, needs a recode game.spectatorOpponentEventDataBuffer.length = 0 ###* * Handler for a game session step. ### onStep = (event) -> gameSession = event.gameSession gameId = gameSession.gameId game = games[gameId] if game? step = event.step if step? and step.timestamp? and step.action? # send out step events stepEventData = {type: EVENTS.step, step: JSON.parse(game.session.serializeToJSON(step))} emitGameEvent(null, gameId, stepEventData) # special action cases action = step.action if action instanceof SDK.EndTurnAction # save game on end turn # delay so that we don't block sending the step back to the players _.delay((()-> if games[gameId]? and games[gameId].session? GameManager.saveGameSession(gameId, games[gameId].session.serializeToJSON(games[gameId].session)) ), 500) else if action instanceof SDK.StartTurnAction # restart the turn timer whenever a turn starts restartTurnTimer(gameId) else if action instanceof SDK.DrawStartingHandAction # restart turn timer if both players have a starting hand and this step is for a DrawStartingHandAction bothPlayersHaveStartingHand = _.reduce(game.session.players,((memo,player)-> memo && player.getHasStartingHand()),true) if bothPlayersHaveStartingHand restartTurnTimer(gameId) if action.getIsAutomatic() and !game.session.getIsFollowupActive() # add bonus to turn time for every automatic step # unless followup is active, to prevent rollbacks for infinite turn time # bonus as a separate parameter accounts for cases such as: # - battle pet automatic actions eating up your own time # - queuing up many actions and ending turn quickly to eat into opponent's time game.turnTimeBonus += 2000 # when game is over and we have the final step # we cannot archive game until final step event # because otherwise step won't be finished/signed correctly # so we must do this on step event and not on game_over event if game.session.status == SDK.GameStatus.over # stop any turn timers stopTurnTimer(gameId) if !game.isArchived? game.isArchived = true afterGameOver(gameId, game.session, game.mouseAndUIEvents) ###* * Handler for an invalid action. ### onInvalidAction = (event) -> # safety fallback: if player attempts to make an invalid explicit action, notify that player only gameSession = event.gameSession gameId = gameSession.gameId game = games[gameId] if game? action = event.action if !action.getIsImplicit() #Logger.module("...").log "[G:#{gameId}]", "onInvalidAction -> INVALID ACTION: #{action.getLogName()} / VALIDATED BY: #{action.getValidatorType()} / MESSAGE: #{action.getValidationMessage()}" invalidActionEventData = { type: EVENTS.invalid_action, playerId: action.getOwnerId(), action: JSON.parse(game.session.serializeToJSON(action)), validatorType: event.validatorType, validationMessage: event.validationMessage, validationMessagePosition: event.validationMessagePosition, desync: gameSession.isActive() and gameSession.getCurrentPlayerId() == action.getOwnerId() and gameSession.getTurnTimeRemaining() > CONFIG.TURN_DURATION_LATENCY_BUFFER } emitGameEvent(null, gameId, invalidActionEventData) ### # Subscribes to the gamesession's event bus. # Can be called multiple times in order to re-subscribe. # @public # @param {Object} gameId The game ID to subscribe for. ### subscribeToGameSessionEvents = (gameId)-> Logger.module("...").debug "[G:#{gameId}]", "subscribeToGameSessionEvents -> subscribing to GameSession events" game = games[gameId] if game? # unsubscribe from previous unsubscribeFromGameSessionEvents(gameId) # listen for game events game.session.getEventBus().on(EVENTS.before_rollback_to_snapshot, onBeforeRollbackToSnapshot) game.session.getEventBus().on(EVENTS.step, onStep) game.session.getEventBus().on(EVENTS.invalid_action, onInvalidAction) ### # Unsubscribe from event listeners on the game session for this game ID. # @public # @param {String} gameId The game ID that needs to be unsubscribed. ### unsubscribeFromGameSessionEvents = (gameId)-> Logger.module("...").debug "[G:#{gameId}]", "unsubscribeFromGameSessionEvents -> un-subscribing from GameSession events" game = games[gameId] if game? game.session.getEventBus().off(EVENTS.before_rollback_to_snapshot, onBeforeRollbackToSnapshot) game.session.getEventBus().off(EVENTS.step, onStep) game.session.getEventBus().off(EVENTS.invalid_action, onInvalidAction) ### # must be called after game is over # processes a game, saves to redis, and kicks-off post-game processing jobs # @public # @param {String} gameId The game ID that is over. # @param {Object} gameSession The game session data. # @param {Array} mouseAndUIEvents The mouse and UI events for this game. ### afterGameOver = (gameId, gameSession, mouseAndUIEvents) -> Logger.module("GAME-OVER").log "[G:#{gameId}]", "---------- ======= GAME #{gameId} OVER ======= ---------".green # Update User Ranking, Progression, Quests, Stats updateUser = (userId, opponentId, gameId, factionId, generalId, isWinner, isDraw, ticketId) -> Logger.module("GAME-OVER").log "[G:#{gameId}]", "UPDATING user #{userId}. (winner:#{isWinner})" player = gameSession.getPlayerById(userId) isFriendly = gameSession.isFriendly() # get game type for user gameType = gameSession.getGameType() if gameType == SDK.GameType.Casual and player.getIsRanked() # casual games should be processed as ranked for ranked players gameType = SDK.GameType.Ranked # check for isUnscored isUnscored = false # calculate based on number of resign status and number of actions # if the game didn't have a single turn, mark the game as unscored if gameSession.getPlayerById(userId).hasResigned and gameSession.getTurns().length == 0 Logger.module("GAME-OVER").debug "[G:#{gameId}]", "User: #{userId} CONCEDED a game with 0 turns. Marking as UNSCORED".yellow isUnscored = true else if not isWinner and not isDraw # otherwise check how many actions the player took playerActionCount = 0 meaningfulActionCount = 0 moveActionCount = 0 for a in gameSession.getActions() # explicit actions if a.getOwnerId() == userId && a.getIsImplicit() == false playerActionCount++ # meaningful actions if a instanceof SDK.AttackAction if a.getTarget().getIsGeneral() meaningfulActionCount += 2 else meaningfulActionCount += 1 if a instanceof SDK.PlayCardFromHandAction or a instanceof SDK.PlaySignatureCardAction meaningfulActionCount += 1 if a instanceof SDK.BonusManaAction meaningfulActionCount += 2 # move actions if a instanceof SDK.MoveAction moveActionCount += 1 # more than 9 explicit actions # more than 1 move action # more than 5 meaningful actions if playerActionCount > 9 and moveActionCount > 1 and meaningfulActionCount > 4 break ### what we're looking for: * more than 9 explicit actions * more than 1 move action * more than 5 meaningful actions ... otherwise mark the game as unscored ### # Logger.module("GAME-OVER").log "[G:#{gameId}]", "User: #{userId} #{playerActionCount}, #{moveActionCount}, #{meaningfulActionCount}".cyan if playerActionCount <= 9 or moveActionCount <= 1 or meaningfulActionCount <= 4 Logger.module("GAME-OVER").debug "[G:#{gameId}]", "User: #{userId} CONCEDED a game with too few meaningful actions. Marking as UNSCORED".yellow isUnscored = true # start the job to process the game for a user return Jobs.create("update-user-post-game", name: "Update User Ranking" title: util.format("User %s :: Game %s", userId, gameId) userId: userId opponentId: opponentId gameId: gameId gameType: gameType factionId: factionId generalId: generalId isWinner: isWinner isDraw: isDraw isUnscored: isUnscored ticketId: ticketId ).removeOnComplete(true) # wait to save job until ready to process updateUsersRatings = (player1UserId, player2UserId, gameId, player1IsWinner, isDraw) -> # Detect if one player is casual playing in a ranked game player1IsRanked = gameSession.getPlayerById(player1UserId).getIsRanked() player2IsRanked = gameSession.getPlayerById(player2UserId).getIsRanked() gameType = gameSession.getGameType() if gameType == SDK.GameType.Casual and (player1IsRanked || player2IsRanked) # casual games should be processed as ranked for ranked players gameType = SDK.GameType.Ranked isRanked = gameType == SDK.GameType.Ranked Logger.module("GAME-OVER").debug "[G:#{gameId}]", "UPDATING users [#{player1UserId},#{player2UserId}] ratings." # Ratings only process in NON-FRIENDLY matches where at least 1 player is rank 0 if isRanked # start the job to process the ratings for the players return Jobs.create("update-users-ratings", name: "Update User Rating" title: util.format("Users [%s,%s] :: Game %s", player1UserId,player2UserId, gameId) player1UserId: player1UserId player1IsRanked: player1IsRanked player2UserId: player2UserId player2IsRanked: player2IsRanked gameId: gameId player1IsWinner: player1IsWinner isDraw: isDraw ).removeOnComplete(true).save() else return Promise.resolve() # Save then archive game session archiveGame = (gameId, gameSession, mouseAndUIEvents) -> return Promise.all([ GameManager.saveGameMouseUIData(gameId, JSON.stringify(mouseAndUIEvents)), GameManager.saveGameSession(gameId, gameSession.serializeToJSON(gameSession)) ]).then () -> # Job: Archive Game Jobs.create("archive-game", name: "Archive Game" title: util.format("Archiving Game %s", gameId) gameId: gameId gameType: gameSession.getGameType() ).removeOnComplete(true).save() # Builds a promise for executing the user update ratings job after player update jobs have completed updateUserRatingsPromise = (updatePlayer1Job,updatePlayer2Job,player1Id,player2Id,gameId,player1IsWinner,isDraw) -> # Wait until both players update jobs have completed before updating ratings return Promise.all([ new Promise (resolve,reject) -> updatePlayer1Job.on("complete",resolve); updatePlayer1Job.on("error",reject), new Promise (resolve,reject) -> updatePlayer2Job.on("complete",resolve); updatePlayer2Job.on("error",reject) ]).then () -> updateUsersRatings(player1Id,player2Id,gameId,player1IsWinner,isDraw) .catch (error) -> Logger.module("GAME-OVER").error "[G:#{gameId}]", "ERROR: afterGameOver update player job failed #{error}".red # issue a warning to our exceptionReporter error tracker exceptionReporter.notify(error, { errorName: "afterGameOver update player job failed", severity: "error" game: id: gameId gameType: gameSession.gameType player1Id: player1Id player2Id: player2Id winnerId: winnerId loserId: loserId }) # gamesession player data player1Id = gameSession.getPlayer1Id() player2Id = gameSession.getPlayer2Id() player1FactionId = gameSession.getPlayer1SetupData()?.factionId player2FactionId = gameSession.getPlayer2SetupData()?.factionId player1GeneralId = gameSession.getPlayer1SetupData()?.generalId player2GeneralId = gameSession.getPlayer2SetupData()?.generalId player1TicketId = gameSession.getPlayer1SetupData()?.ticketId player2TicketId = gameSession.getPlayer2SetupData()?.ticketId winnerId = gameSession.getWinnerId() loserId = gameSession.getWinnerId() player1IsWinner = (player1Id == winnerId) isDraw = if !winnerId? then true else false # update promises promises = [] # update users updatePlayer1Job = updateUser(player1Id,player2Id,gameId,player1FactionId,player1GeneralId,(player1Id == winnerId),isDraw,player1TicketId) updatePlayer2Job = updateUser(player2Id,player1Id,gameId,player2FactionId,player2GeneralId,(player2Id == winnerId),isDraw,player2TicketId) # wait until both players update jobs have completed before updating ratings promises.push(updateUserRatingsPromise(updatePlayer1Job,updatePlayer2Job,player1Id,player2Id,gameId,player1IsWinner,isDraw)) updatePlayer1Job.save() updatePlayer2Job.save() # archive game promises.push(archiveGame(gameId, gameSession, mouseAndUIEvents)) # execute promises Promise.all(promises) .then () -> Logger.module("GAME-OVER").debug "[G:#{gameId}]", "afterGameOver done, game is being archived".green .catch (error) -> Logger.module("GAME-OVER").error "[G:#{gameId}]", "ERROR: afterGameOver failed #{error}".red # issue a warning to exceptionReporter exceptionReporter.notify(error, { errorName: "afterGameOver failed", severity: "error" game: id: gameId gameType: gameSession.getGameType() player1Id: player1Id player2Id: player2Id winnerId: winnerId loserId: loserId }) ### Shutdown Handler ### shutdown = () -> Logger.module("SERVER").log "Shutting down game server." Logger.module("SERVER").log "Active Players: #{playerCount}." Logger.module("SERVER").log "Active Games: #{gameCount}." if !config.get('consul.enabled') process.exit(0) return Consul.getReassignmentStatus() .then (reassign) -> if reassign == false Logger.module("SERVER").log "Reassignment disabled - exiting." process.exit(0) # Build an array of game IDs ids = [] _.each games, (game, id) -> ids.push(id) # Map to save each game to Redis before shutdown return Promise.map ids, (id) -> serializedData = games[id].session.serializeToJSON(games[id].session) return GameManager.saveGameSession(id, serializedData) .then () -> return Consul.getHealthyServers() .then (servers) -> # Filter 'yourself' from list of nodes filtered = _.reject servers, (server)-> return server["Node"]?["Node"] == os.hostname() if filtered.length == 0 Logger.module("SERVER").log "No servers available - exiting without re-assignment." process.exit(1) random_node = _.sample(filtered) node_name = random_node["Node"]?["Node"] return Consul.kv.get("nodes/#{node_name}/public_ip") .then (newServerIp) -> # Development override for testing, bounces between port 9000 & 9001 if config.isDevelopment() port = 9001 if config.get('port') is 9000 port = 9000 if config.get('port') is 9001 newServerIp = "127.0.0.1:#{port}" msg = "Server is shutting down. You will be reconnected automatically." io.emit "game_server_shutdown", {msg:msg,ip:newServerIp} Logger.module("SERVER").log "Players reconnecting to: #{newServerIp}" Logger.module("SERVER").log "Re-assignment complete. Exiting." process.exit(0) .catch (err) -> Logger.module("SERVER").log "Re-assignment failed: #{err.message}. Exiting." process.exit(1) process.on "SIGTERM", shutdown process.on "SIGINT", shutdown process.on "SIGHUP", shutdown process.on "SIGQUIT", shutdown
true
### Game Server Pieces ### fs = require 'fs' os = require 'os' util = require 'util' _ = require 'underscore' colors = require 'colors' # used for console message coloring jwt = require 'jsonwebtoken' io = require 'socket.io' ioJwt = require 'socketio-jwt' Promise = require 'bluebird' kue = require 'kue' moment = require 'moment' request = require 'superagent' # Our modules shutdown = require './shutdown' SDK = require '../app/sdk.coffee' Logger = require '../app/common/logger.coffee' EVENTS = require '../app/common/event_types' UtilsGameSession = require '../app/common/utils/utils_game_session.coffee' exceptionReporter = require '@counterplay/exception-reporter' # lib Modules Consul = require './lib/consul' # Configuration object config = require '../config/config.js' env = config.get('env') firebaseToken = config.get('firebaseToken') # Boots up a basic HTTP server on port 8080 # Responds to /health endpoint with status 200 # Otherwise responds with status 404 Logger = require '../app/common/logger.coffee' CONFIG = require '../app/common/config' http = require 'http' url = require 'url' Promise = require 'bluebird' # perform DNS health check dnsHealthCheck = () -> if config.isDevelopment() return Promise.resolve({healthy: true}) nodename = "#{config.get('env')}-#{os.hostname().split('.')[0]}" return Consul.kv.get("nodes/#{nodename}/dns_name") .then (dnsName) -> return new Promise (resolve, reject) -> request.get("https://#{dnsName}/health") .end (err, res) -> if err return resolve({dnsName: dnsName, healthy: false}) if res? && res.status == 200 return resolve({dnsName: dnsName, healthy: true}) return ({dnsName: dnsName, healthy: false}) .catch (e) -> return {healthy: false} # create http server and respond to /health requests server = http.createServer (req, res) -> pathname = url.parse(req.url).pathname if pathname == '/health' Logger.module("GAME SERVER").debug "HTTP Health Ping" res.statusCode = 200 res.write JSON.stringify({players: playerCount, games: gameCount}) res.end() else res.statusCode = 404 res.end() # io server setup, binds to http server io = require('socket.io')().listen(server, { cors: { origin: "*" } }) io.use( ioJwt.authorize( secret:firebaseToken timeout: 15000 ) ) module.exports = io server.listen config.get('game_port'), () -> Logger.module("GAME SERVER").log "GAME Server <b>#{os.hostname()}</b> started." # redis {Redis, Jobs, GameManager} = require './redis/' # server id for this game server serverId = os.hostname() # the 'games' hash maps game IDs to References for those games games = {} # save some basic stats about this server into redis playerCount = 0 gameCount = 0 # turn times MAX_TURN_TIME = (CONFIG.TURN_DURATION + CONFIG.TURN_DURATION_LATENCY_BUFFER) * 1000.0 MAX_TURN_TIME_INACTIVE = (CONFIG.TURN_DURATION_INACTIVE + CONFIG.TURN_DURATION_LATENCY_BUFFER) * 1000.0 savePlayerCount = (playerCount) -> Redis.hsetAsync("servers:#{serverId}", "players", playerCount) saveGameCount = (gameCount) -> Redis.hsetAsync("servers:#{serverId}", "games", gameCount) # error 'domain' to deal with io.sockets uncaught errors d = require('domain').create() d.on 'error', shutdown.errorShutdown d.add(io.sockets) # health ping on socket namespace /health healthPing = io .of '/health' .on 'connection', (socket) -> socket.on 'ping', () -> Logger.module("GAME SERVER").debug "socket.io Health Ping" socket.emit 'pong' # run main io.sockets inside of the domain d.run () -> io.sockets.on "authenticated", (socket) -> # add the socket to the error domain d.add(socket) # Socket is now autheticated, continue to bind other handlers Logger.module("IO").debug "DECODED TOKEN ID: #{socket.decoded_token.d.id.blue}" savePlayerCount(++playerCount) # Send message to user that connection is succesful socket.emit "connected", message: "Successfully connected to server" # Bind socket event handlers socket.on EVENTS.join_game, onGamePlayerJoin socket.on EVENTS.spectate_game, onGameSpectatorJoin socket.on EVENTS.leave_game, onGameLeave socket.on EVENTS.network_game_event, onGameEvent socket.on "disconnect", onGameDisconnect getConnectedSpectatorsDataForGamePlayer = (gameId,playerId)-> spectators = [] for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"] socket = io.sockets.connected[socketId] if socket.playerId == playerId spectators.push({ id:socket.spectatorId, playerId:socket.playerId, username:socket.spectateToken?.u }) return spectators ### # socket handler for players joining game # @public # @param {Object} requestData Plain JS object with socket event data. ### onGamePlayerJoin = (requestData) -> # request parameters gameId = requestData.gameId playerId = requestData.playerId Logger.module("IO").debug "[G:#{gameId}]", "join_game -> player:#{requestData.playerId} is joining game:#{requestData.gameId}".cyan # you must have a playerId if not playerId Logger.module("IO").error "[G:#{gameId}]", "join_game -> REFUSING JOIN: A player #{playerId.blue} is not valid".red @emit "join_game_response", error:"Your player id seems to be blank (has your login expired?), so we can't join you to the game." return # must have a gameId if not gameId Logger.module("IO").error "[G:#{gameId}]", "join_game -> REFUSING JOIN: A gameId #{gameId.blue} is not valid".red @emit "join_game_response", error:"Invalid Game ID." return # if someone is trying to join a game they don't belong to as a player they are not authenticated as if @.decoded_token.d.id != playerId Logger.module("IO").error "[G:#{gameId}]", "join_game -> REFUSING JOIN: A player #{@.decoded_token.PI:EMAIL:<EMAIL>END_PI.blue} is attempting to join a game as #{playerId.blue}".red @emit "join_game_response", error:"Your player id does not match the one you requested to join a game with. Are you sure you're joining the right game?" return # if a client is already in another game, leave it playerLeaveGameIfNeeded(this) # if this client already exists in this game, disconnect duplicate client for socketId,connected of io.sockets.adapter.rooms[gameId] socket = io.sockets.connected[socketId] if socket? and socket.playerId == playerId Logger.module("IO").error "[G:#{gameId}]", "join_game -> detected duplicate connection to #{gameId} GameSession for #{playerId.blue}. Disconnecting duplicate...".cyan playerLeaveGameIfNeeded(socket, silent=true) # initialize a server-side game session and join it initGameSession(gameId) .bind @ .spread (gameSession) -> #Logger.module("IO").debug "[G:#{gameId}]", "join_game -> players in data: ", gameSession.players # player player = _.find(gameSession.players, (p) -> return p.playerId == playerId) # get the opponent based on the game session data opponent = _.find(gameSession.players, (p) -> return p.playerId != playerId) Logger.module("IO").debug "[G:#{gameId}]", "join_game -> Got #{gameId} GameSession data #{playerId.blue}.".cyan if not player # oops looks like this player does not exist in the requested game # let the socket know we had an error @emit "join_game_response", error:"could not join game because your player id could not be found" # destroy the game data loaded so far if the opponent can't be defined and no one else is connected Logger.module("IO").error "[G:#{gameId}]", "onGameJoin -> DESTROYING local game cache due to join error".red destroyGameSessionIfNoConnectionsLeft(gameId) # stop any further processing return else if not opponent? # oops, looks like we can'f find an opponent in the game session? Logger.module("IO").error "[G:#{gameId}]", "join_game -> game #{gameId} ERROR: could not find opponent for #{playerId.blue}.".red # let the socket know we had an error @emit "join_game_response", error:"could not join game because the opponent could not be found" # issue a warning to our exceptionReporter error tracker exceptionReporter.notify(new Error("Error joining game: could not find opponent"), { severity: "warning" user: id: playerId game: id: gameId player1Id: gameSession?.players[0].playerId player2Id: gameSession?.players[1].playerId }) # destroy the game data loaded so far if the opponent can't be defined and no one else is connected Logger.module("IO").error "[G:#{gameId}]", "onGameJoin -> DESTROYING local game cache due to join error".red destroyGameSessionIfNoConnectionsLeft(gameId) # stop any further processing return else # rollback if it is this player's followup # this can happen if a player reconnects without properly disconnecting if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() == playerId gameSession.executeAction(gameSession.actionRollbackSnapshot()) # set some parameters for the socket @gameId = gameId @playerId = playerId # join game room @join(gameId) # update user count for game room games[gameId].connectedPlayers.push(playerId) Logger.module("IO").debug "[G:#{gameId}]", "join_game -> Game #{gameId} connected players so far: #{games[gameId].connectedPlayers.length}." # if only one player is in so far, start the disconnection timer if games[gameId].connectedPlayers.length == 1 # start disconnected player timeout for game startDisconnectedPlayerTimeout(gameId,opponent.playerId) else if games[gameId].connectedPlayers.length == 2 # clear timeout when we get two players clearDisconnectedPlayerTimeout(gameId) # prepare and scrub game session data for this player # if a followup is active and it isn't this player's followup, send them the rollback snapshot if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() != playerId gameSessionData = JSON.parse(gameSession.getRollbackSnapshotData()) else gameSessionData = JSON.parse(gameSession.serializeToJSON(gameSession)) UtilsGameSession.scrubGameSessionData(gameSession, gameSessionData, playerId) # respond to client with success and a scrubbed copy of the game session @emit "join_game_response", message: "successfully joined game" gameSessionData: gameSessionData connectedPlayers:games[gameId].connectedPlayers connectedSpectators: getConnectedSpectatorsDataForGamePlayer(gameId,playerId) # broadcast join to any other connected players @broadcast.to(gameId).emit("player_joined",playerId) .catch (e) -> Logger.module("IO").error "[G:#{gameId}]", "join_game -> player:#{playerId} failed to join game, error: #{e.message}".red Logger.module("IO").error "[G:#{gameId}]", "join_game -> player:#{playerId} failed to join game, error stack: #{e.stack}".red # if we didn't join a game, broadcast a failure @emit "join_game_response", error:"Could not join game: " + e?.message ### # socket handler for spectators joining game # @public # @param {Object} requestData Plain JS object with socket event data. ### onGameSpectatorJoin = (requestData) -> # request parameters # TODO : Sanitize these parameters to prevent crash if gameId = null gameId = requestData.gameId spectatorId = requestData.spectatorId playerId = requestData.playerId spectateToken = null # verify - synchronous try spectateToken = jwt.verify(requestData.spectateToken, firebaseToken) catch error Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> ERROR decoding spectate token: #{error?.message}".red if not spectateToken or spectateToken.b?.length == 0 Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A specate token #{spectateToken} is not valid".red @emit "spectate_game_response", error:"Your spectate token is invalid, so we can't join you to the game." return Logger.module("IO").debug "[G:#{gameId}]", "spectate_game -> token contents: ", spectateToken.b Logger.module("IO").debug "[G:#{gameId}]", "spectate_game -> playerId: ", playerId if not _.contains(spectateToken.b,playerId) Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: You do not have permission to specate this game".red @emit "spectate_game_response", error:"You do not have permission to specate this game." return # must have a spectatorId if not spectatorId Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A spectator #{spectatorId.blue} is not valid".red @emit "spectate_game_response", error:"Your login ID is blank (expired?), so we can't join you to the game." return # must have a playerId if not playerId Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A player #{playerId.blue} is not valid".red @emit "spectate_game_response", error:"Invalid player ID." return # must have a gameId if not gameId Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A gameId #{gameId.blue} is not valid".red @emit "spectate_game_response", error:"Invalid Game ID." return # if someone is trying to join a game they don't belong to as a player they are not authenticated as if @.decoded_token.d.id != spectatorId Logger.module("IO").error "[G:#{gameId}]", "spectate_game -> REFUSING JOIN: A player #{@.decoded_token.d.id.blue} is attempting to join a game as #{playerId.blue}".red @emit "spectate_game_response", error:"Your login ID does not match the one you requested to spectate the game with." return Logger.module("IO").debug "[G:#{gameId}]", "spectate_game -> spectator:#{spectatorId} is joining game:#{gameId}".cyan # if a client is already in another game, leave it spectatorLeaveGameIfNeeded(@) if games[gameId]?.connectedSpectators.length >= 10 # max out at 10 spectators @emit "spectate_game_response", error:"Maximum number of spectators already watching." return # initialize a server-side game session and join it initSpectatorGameSession(gameId) .bind @ .then (spectatorGameSession) -> # for spectators, use the delayed in-memory game session gameSession = spectatorGameSession Logger.module("IO").debug "[G:#{gameId}]", "spectate_game -> Got #{gameId} GameSession data.".cyan player = _.find(gameSession.players, (p) -> return p.playerId == playerId) opponent = _.find(gameSession.players, (p) -> return p.playerId != playerId) if not player # let the socket know we had an error @emit "spectate_game_response", error:"could not join game because the player id you requested could not be found" # destroy the game data loaded so far if the opponent can't be defined and no one else is connected Logger.module("IO").error "[G:#{gameId}]", "onGameSpectatorJoin -> DESTROYING local game cache due to join error".red destroyGameSessionIfNoConnectionsLeft(gameId) # stop any further processing return else # set some parameters for the socket @gameId = gameId @spectatorId = spectatorId @spectateToken = spectateToken @playerId = playerId # join game room @join("spectate-#{gameId}") # update user count for game room games[gameId].connectedSpectators.push(spectatorId) # prepare and scrub game session data for this player # if a followup is active and it isn't this player's followup, send them the rollback snapshot if gameSession.getIsFollowupActive() and gameSession.getCurrentPlayerId() != playerId gameSessionData = JSON.parse(gameSession.getRollbackSnapshotData()) else gameSessionData = JSON.parse(gameSession.serializeToJSON(gameSession)) UtilsGameSession.scrubGameSessionData(gameSession, gameSessionData, playerId, true) ### # if the spectator does not have the opponent in their buddy list if not _.contains(spectateToken.b,opponent.playerId) # scrub deck data and opponent hand data by passing in opponent ID scrubGameSessionDataForSpectators(gameSession, gameSessionData, opponent.playerId) else # otherwise just scrub deck data in a way you can see both decks # scrubGameSessionDataForSpectators(gameSession, gameSessionData) # NOTE: above line is disabled for now since it does some UI jankiness since when a cardId is present the tile layer updates when the spectated opponent starts to select cards # NOTE: besides, actions will be scrubbed so this idea of watching both players only sort of works right now scrubGameSessionDataForSpectators(gameSession, gameSessionData, opponent.playerId, true) ### # respond to client with success and a scrubbed copy of the game session @emit "spectate_game_response", message: "successfully joined game" gameSessionData: gameSessionData # broadcast to the game room that a spectator has joined @broadcast.to(gameId).emit("spectator_joined",{ id: spectatorId, playerId: playerId, username: spectateToken.u }) .catch (e) -> # if we didn't join a game, broadcast a failure @emit "spectate_game_response", error:"could not join game: #{e.message}" ### # socket handler for leaving a game. # @public # @param {Object} requestData Plain JS object with socket event data. ### onGameLeave = (requestData) -> if @.spectatorId Logger.module("IO").debug "[G:#{@.gameId}]", "leave_game -> spectator #{@.spectatorId} leaving #{@.gameId}" spectatorLeaveGameIfNeeded(@) else Logger.module("IO").debug "[G:#{@.gameId}]", "leave_game -> player #{@.playerId} leaving #{@.gameId}" playerLeaveGameIfNeeded(@) ###* # This method is called every time a socket handler recieves a game event and is executed within the context of the socket (this == sending socket). # @public # @param {Object} eventData Plain JS object with event data that contains one "event". ### onGameEvent = (eventData) -> # if for some reason spectator sockets start broadcasting game events if @.spectatorId Logger.module("IO").error "[G:#{@.gameId}]", "onGameEvent :: ERROR: spectator sockets can't submit game events. (type: #{eventData.type})".red return # Logger.module("IO").log "onGameEvent -> #{JSON.stringify(eventData)}".blue if not @gameId or not games[@gameId] @emit EVENTS.network_game_error, code:500 message:"could not broadcast game event because you are not currently in a game" return # gameSession = games[@gameId].session if eventData.type == EVENTS.step #Logger.module("IO").log "[G:#{@.gameId}]", "game_step -> #{JSON.stringify(eventData.step)}".green #Logger.module("IO").log "[G:#{@.gameId}]", "game_step -> #{eventData.step?.playerId} #{eventData.step?.action?.type}".green player = _.find(gameSession.players,(p)-> p.playerId == eventData.step?.playerId) player?.setLastActionTakenAt(Date.now()) try step = gameSession.deserializeStepFromFirebase(eventData.step) action = step.action if action? # clear out any implicit actions sent over the network and re-execute this as a fresh explicit action on the server # the reason is that we want to re-generate and re-validate all the game logic that happens as a result of this FIRST explicit action in the step action.resetForAuthoritativeExecution() # execute the action gameSession.executeAction(action) catch error Logger.module("IO").error "[G:#{@.gameId}]", "onGameStep:: error: #{JSON.stringify(error.message)}".red Logger.module("IO").error "[G:#{@.gameId}]", "onGameStep:: error stack: #{error.stack}".red # Report error to exceptionReporter with gameId + eventData exceptionReporter.notify(error, { errorName: "onGameStep Error", game: { gameId: @gameId eventData: eventData } }) # delete but don't destroy game destroyGameSessionIfNoConnectionsLeft(@gameId,true) # send error to client, forcing reconnect on client side io.to(@gameId).emit EVENTS.network_game_error, JSON.stringify(error.message) return else # transmit the non-step game events to players # step events are emitted automatically after executed on game session emitGameEvent(@, @gameId, eventData) ### # Socket Disconnect Event Handler. Handles rollback if in the middle of followup etc. # @public ### onGameDisconnect = () -> if @.spectatorId # make spectator leave game room spectatorLeaveGameIfNeeded(@) # remove the socket from the error domain, this = socket d.remove(@) else try clients_in_the_room = io.sockets.adapter.rooms[@.gameId] for clientId,socket of clients_in_the_room if socket.playerId == @.playerId Logger.module("IO").error "onGameDisconnect:: looks like the player #{@.playerId} we are trying to disconnect is still in the game #{@.gameId} room. ABORTING".red return for clientId,socket of io.sockets.connected if socket.playerId == @.playerId and not socket.spectatorId Logger.module("IO").error "onGameDisconnect:: looks like the player #{@.playerId} that allegedly disconnected is still alive and well.".red return catch error Logger.module("IO").error "onGameDisconnect:: Error #{error?.message}.".red # if we are in a buffering state # and the disconnecting player is in the middle of a followup gs = games[@gameId]?.session if gs? and gs.getIsBufferingEvents() and gs.getCurrentPlayerId() == @playerId # execute a rollback to reset server state # but do not send this action to the still connected player # because they do not care about rollbacks for the other player rollBackAction = gs.actionRollbackSnapshot() gs.executeAction(rollBackAction) # remove the socket from the error domain, this = socket d.remove(@) savePlayerCount(--playerCount) Logger.module("IO").debug "[G:#{@.gameId}]", "disconnect -> #{@.playerId}".red # if a client is already in another game, leave it playerLeaveGameIfNeeded(@) ###* * Leaves a game for a player socket if the socket is connected to a game * @public * @param {Socket} socket The socket which wants to leave a game. * @param {Boolean} [silent=false] whether to disconnect silently, as in the case of duplicate connections for same player ### playerLeaveGameIfNeeded = (socket, silent=false) -> if socket? gameId = socket.gameId playerId = socket.playerId # if a player is in a game if gameId? and playerId? Logger.module("...").debug "[G:#{gameId}]", "playerLeaveGame -> #{playerId} has left game #{gameId}".red if !silent # broadcast that player left socket.broadcast.to(gameId).emit("player_left",playerId) # leave that game room socket.leave(gameId) # update user count for game room game = games[gameId] if game? index = game.connectedPlayers.indexOf(playerId) game.connectedPlayers.splice(index,1) if !silent # start disconnected player timeout for game startDisconnectedPlayerTimeout(gameId,playerId) # destroy game if no one is connected anymore destroyGameSessionIfNoConnectionsLeft(gameId,true) # finally clear the existing gameId socket.gameId = null ### # This function leaves a game for a spectator socket if the socket is connected to a game # @public # @param {Socket} socket The socket which wants to leave a game. ### spectatorLeaveGameIfNeeded = (socket) -> # if a client is already in another game if socket.gameId Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} leaving game #{socket.gameId}." # broadcast that you left socket.broadcast.to(socket.gameId).emit("spectator_left",{ id:socket.spectatorId, playerId:socket.playerId, username:socket.spectateToken?.u }) # leave specator game room socket.leave("spectate-#{socket.gameId}") Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} left room for game #{socket.gameId}." # update spectator count for game room if games[socket.gameId] games[socket.gameId].connectedSpectators = _.without(games[socket.gameId].connectedSpectators,socket.spectatorId) Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} removed from list of spectators #{socket.gameId}." # if no spectators left, stop the delayed game interval and destroy spectator delayed game session tearDownSpectateSystemsIfNoSpectatorsLeft(socket.gameId) # destroy game if no one is connected anymore destroyGameSessionIfNoConnectionsLeft(socket.gameId,true) remainingSpectators = games[socket.gameId]?.connectedSpectators?.length || 0 Logger.module("...").debug "[G:#{socket.gameId}]", "spectatorLeaveGameIfNeeded -> #{socket.spectatorId} has left game #{socket.gameId}. remaining spectators #{remainingSpectators}" # finally clear the existing gameId socket.gameId = null ### # This function destroys in-memory game session of there is no one left connected # @public # @param {String} gameId The ID of the game to destroy. # @param {Boolean} persist Do we need to save/archive this game? ### destroyGameSessionIfNoConnectionsLeft = (gameId,persist=false)-> if games[gameId].connectedPlayers.length == 0 and games[gameId].connectedSpectators.length == 0 clearDisconnectedPlayerTimeout(gameId) stopTurnTimer(gameId) tearDownSpectateSystemsIfNoSpectatorsLeft(gameId) Logger.module("...").debug "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft() -> no players left DESTROYING local game cache".red unsubscribeFromGameSessionEvents(gameId) # TEMP: a way to upload unfinished game data to AWS S3 Archive. For example: errored out games. if persist and games?[gameId]?.session?.status != SDK.GameStatus.over data = games[gameId].session.serializeToJSON(games[gameId].session) mouseAndUIEventsData = JSON.stringify(games[gameId].mouseAndUIEvents) Promise.all([ GameManager.saveGameSession(gameId,data), GameManager.saveGameMouseUIData(gameId,mouseAndUIEventsData), ]) .then (results) -> Logger.module("...").debug "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft -> unfinished Game Archived to S3: #{results[1]}".green .catch (error)-> Logger.module("...").error "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft -> ERROR: failed to archive unfinished game to S3 due to error #{error.message}".red delete games[gameId] saveGameCount(--gameCount) else Logger.module("...").debug "[G:#{gameId}]", "destroyGameSessionIfNoConnectionsLeft() -> players left: #{games[gameId].connectedPlayers.length} spectators left: #{games[gameId].connectedSpectators.length}" ### # This function stops all spectate systems if 0 spectators left. # @public # @param {String} gameId The ID of the game to tear down spectate systems. ### tearDownSpectateSystemsIfNoSpectatorsLeft = (gameId)-> # if no spectators left, stop the delayed game interval and destroy spectator delayed game session if games[gameId]?.connectedSpectators.length == 0 Logger.module("IO").debug "[G:#{gameId}]", "tearDownSpectateSystemsIfNoSpectatorsLeft() -> no spectators left, stopping spectate systems" stopSpectatorDelayedGameInterval(gameId) games[gameId].spectatorDelayedGameSession = null games[gameId].spectateIsRunning = false games[gameId].spectatorOpponentEventDataBuffer.length = 0 games[gameId].spectatorGameEventBuffer.length = 0 ### # Clears timeout for disconnected players # @public # @param {String} gameId The ID of the game to clear disconnected timeout for. ### clearDisconnectedPlayerTimeout = (gameId) -> Logger.module("IO").debug "[G:#{gameId}]", "clearDisconnectedPlayerTimeout:: for game: #{gameId}".yellow clearTimeout(games[gameId]?.disconnectedPlayerTimeout) games[gameId]?.disconnectedPlayerTimeout = null ### # Starts timeout for disconnected players # @public # @param {String} gameId The ID of the game. # @param {String} playerId The player ID for who to start the timeout. ### startDisconnectedPlayerTimeout = (gameId,playerId) -> if games[gameId]?.disconnectedPlayerTimeout? clearDisconnectedPlayerTimeout(gameId) Logger.module("IO").debug "[G:#{gameId}]", "startDisconnectedPlayerTimeout:: for #{playerId} in game: #{gameId}".yellow games[gameId]?.disconnectedPlayerTimeout = setTimeout(()-> onDisconnectedPlayerTimeout(gameId,playerId) ,60000) ### # Resigns game for disconnected player. # @public # @param {String} gameId The ID of the game. # @param {String} playerId The player ID who is resigning. ### onDisconnectedPlayerTimeout = (gameId,playerId) -> Logger.module("IO").debug "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} for game: #{gameId}" clients_in_the_room = io.sockets.adapter.rooms[gameId] for clientId,socket of clients_in_the_room if socket.playerId == playerId Logger.module("IO").error "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: looks like the player #{playerId} we are trying to dis-connect is still in the game #{gameId} room. ABORTING".red return for clientId,socket of io.sockets.connected if socket.playerId == playerId and not socket.spectatorId Logger.module("IO").error "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: looks like the player #{playerId} we are trying to disconnect is still connected but not in the game #{gameId} room.".red return # grab the relevant game session gs = games[gameId]?.session # looks like we timed out for a game that's since ended if !gs or gs?.status == SDK.GameStatus.over Logger.module("IO").error "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} timed out for FINISHED or NULL game: #{gameId}".yellow return else Logger.module("IO").debug "[G:#{gameId}]", "onDisconnectedPlayerTimeout:: #{playerId} auto-resigning game: #{gameId}".yellow # resign the player player = gs.getPlayerById(playerId) resignAction = player.actionResign() gs.executeAction(resignAction) ###* # Start/Restart server side game timer for a game # @public # @param {Object} gameId The game ID. ### restartTurnTimer = (gameId) -> stopTurnTimer(gameId) game = games[gameId] if game.session? game.turnTimerStartedAt = game.turnTimeTickAt = Date.now() game.turnTimer = setInterval((()-> onGameTimeTick(gameId)),1000) ###* # Stop server side game timer for a game # @public # @param {Object} gameId The game ID. ### stopTurnTimer = (gameId) -> game = games[gameId] if game? and game.turnTimer? clearInterval(game.turnTimer) game.turnTimer = null ###* # Server side game timer. After 90 seconds it will end the turn for the current player. # @public # @param {Object} gameId The game for which to iterate the time. ### onGameTimeTick = (gameId) -> game = games[gameId] gameSession = game?.session if gameSession? # allowed turn time is 90 seconds + slop buffer that clients don't see allowed_turn_time = MAX_TURN_TIME # grab the current player player = gameSession.getCurrentPlayer() # if we're past the 2nd turn, we can start checking backwards to see how long the PREVIOUS turn for this player took if player and gameSession.getTurns().length > 2 # find the current player's previous turn allTurns = gameSession.getTurns() playersPreviousTurn = null for i in [allTurns.length-1..0] by -1 if allTurns[i].playerId == player.playerId playersPreviousTurn = allTurns[i] # gameSession.getTurns()[gameSession.getTurns().length - 3] break #Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: last action at #{player.getLastActionTakenAt()} / last turn delta #{playersPreviousTurn?.createdAt - player.getLastActionTakenAt()}".red # if this player's previous action was on a turn older than the last one if playersPreviousTurn && (playersPreviousTurn.createdAt - player.getLastActionTakenAt() > 0) # you're only allowed 15 seconds + 3 second buffer that clients don't see allowed_turn_time = MAX_TURN_TIME_INACTIVE lastTurnTimeTickAt = game.turnTimeTickAt game.turnTimeTickAt = Date.now() delta_turn_time_tick = game.turnTimeTickAt - lastTurnTimeTickAt delta_since_timer_began = game.turnTimeTickAt - game.turnTimerStartedAt game.turnTimeRemaining = Math.max(0.0, allowed_turn_time - delta_since_timer_began + game.turnTimeBonus) game.turnTimeBonus = Math.max(0.0, game.turnTimeBonus - delta_turn_time_tick) #Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: delta #{delta_turn_time_tick/1000}, #{game.turnTimeRemaining/1000} time remaining, #{game.turnTimeBonus/1000} bonus remaining" turnTimeRemainingInSeconds = Math.ceil(game.turnTimeRemaining/1000) gameSession.setTurnTimeRemaining(turnTimeRemainingInSeconds) if game.turnTimeRemaining <= 0 # turn time has expired stopTurnTimer(gameId) if gameSession.status == SDK.GameStatus.new # force draw starting hand with current cards for player in gameSession.players if not player.getHasStartingHand() Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: mulligan timer up, submitting player #{player.playerId.blue} mulligan".red drawStartingHandAction = player.actionDrawStartingHand([]) gameSession.executeAction(drawStartingHandAction) else if gameSession.status == SDK.GameStatus.active # force end turn Logger.module("IO").log "[G:#{gameId}]", "onGameTimeTick:: turn timer up, submitting player #{gameSession.getCurrentPlayerId().blue} turn".red endTurnAction = gameSession.actionEndTurn() gameSession.executeAction(endTurnAction) else # if the turn timer has not expired, just send the time tick over to all clients totalStepCount = gameSession.getStepCount() - games[gameId].opponentEventDataBuffer.length emitGameEvent(null,gameId,{type: EVENTS.turn_time, time: turnTimeRemainingInSeconds, timestamp: Date.now(), stepCount: totalStepCount}) ###* # ... # @public # @param {Object} gameId The game ID. ### restartSpectatorDelayedGameInterval = (gameId) -> stopSpectatorDelayedGameInterval(gameId) Logger.module("IO").debug "[G:#{gameId}]", "restartSpectatorDelayedGameInterval" if games[gameId].spectateIsDelayed games[gameId].spectatorDelayTimer = setInterval((()-> onSpectatorDelayedGameTick(gameId)), 500) ###* # ... # @public # @param {Object} gameId The game ID. ### stopSpectatorDelayedGameInterval = (gameId) -> Logger.module("IO").debug "[G:#{gameId}]", "stopSpectatorDelayedGameInterval" clearInterval(games[gameId].spectatorDelayTimer) ###* # Ticks the spectator delayed game and usually flushes the buffer by calling `flushSpectatorNetworkEventBuffer`. # @public # @param {Object} gameId The game for which to iterate the time. ### onSpectatorDelayedGameTick = (gameId) -> if not games[gameId] Logger.module("Game").debug "onSpectatorDelayedGameTick() -> game [G:#{gameId}] seems to be destroyed. Stopping ticks." stopSpectatorDelayedGameInterval(gameId) return _logSpectatorTickInfo(gameId) # flush anything in the spectator buffer flushSpectatorNetworkEventBuffer(gameId) ###* # Runs actions delayed in the spectator buffer. # @public # @param {Object} gameId The game for which to iterate the time. ### flushSpectatorNetworkEventBuffer = (gameId) -> # if there is anything in the buffer if games[gameId].spectatorGameEventBuffer.length > 0 # Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer()" # remove all the NULLED out actions games[gameId].spectatorGameEventBuffer = _.compact(games[gameId].spectatorGameEventBuffer) # loop through the actions in order for eventData,i in games[gameId].spectatorGameEventBuffer timestamp = eventData.timestamp || eventData.step?.timestamp # if we are not delaying events or if the event time exceeds the delay show it to spectators if not games[gameId].spectateIsDelayed || timestamp and moment().utc().valueOf() - timestamp > games[gameId].spectateDelay # null out the event that is about to be broadcast so it can be compacted later games[gameId].spectatorGameEventBuffer[i] = null if (eventData.step) Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> broadcasting spectator step #{eventData.type} - #{eventData.step?.action?.type}" if games[gameId].spectateIsDelayed step = games[gameId].spectatorDelayedGameSession.deserializeStepFromFirebase(eventData.step) games[gameId].spectatorDelayedGameSession.executeAuthoritativeStep(step) # NOTE: we should be OK to contiue to use the eventData here since indices of all actions are the same becuase the delayed game sessions is running as non-authoriative # send events over to spectators of current player for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"] Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.name} to player's spectators" socket = io.sockets.connected[socketId] if socket? and socket.playerId == eventData.step.playerId # scrub the action data. this should not be skipped since some actions include entire deck that needs to be scrubbed because we don't want spectators deck sniping eventDataCopy = JSON.parse(JSON.stringify(eventData)) # TODO: we use session to scrub here but might need to use the delayed session UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId, true) socket.emit EVENTS.network_game_event, eventDataCopy # skip processing anything for the opponent if this is a RollbackToSnapshotAction since only the sender cares about that one if eventData.step.action.type == SDK.RollbackToSnapshotAction.type return # start buffering events until a followup is complete for the opponent since players can cancel out of a followup games[gameId].spectatorOpponentEventDataBuffer.push(eventData) # if we are delayed then check the delayed game session for if we are buffering, otherwise use the primary isSpectatorGameSessionBufferingFollowups = (games[gameId].spectateIsDelayed and games[gameId].spectatorDelayedGameSession?.getIsBufferingEvents()) || games[gameId].session.getIsBufferingEvents() Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> opponentEventDataBuffer at #{games[gameId].spectatorOpponentEventDataBuffer.length} ... buffering: #{isSpectatorGameSessionBufferingFollowups}" # if we have anything in the buffer and we are currently not buffering, flush the buffer over to your opponent's spectators if games[gameId].spectatorOpponentEventDataBuffer.length > 0 and !isSpectatorGameSessionBufferingFollowups # copy buffer and reset opponentEventDataBuffer = games[gameId].spectatorOpponentEventDataBuffer.slice(0) games[gameId].spectatorOpponentEventDataBuffer.length = 0 # broadcast whatever's in the buffer to the opponent _.each(opponentEventDataBuffer, (eventData) -> Logger.module("IO").debug "[G:#{gameId}]", "flushSpectatorNetworkEventBuffer() -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.name} to opponent's spectators" for socketId,connected of io.sockets.adapter.rooms["spectate-#{gameId}"] socket = io.sockets.connected[socketId] if socket? and socket.playerId != eventData.step.playerId eventDataCopy = JSON.parse(JSON.stringify(eventData)) # always scrub steps for sensitive data from opponent's spectator perspective UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId, true) socket.emit EVENTS.network_game_event, eventDataCopy ) else io.to("spectate-#{gameId}").emit EVENTS.network_game_event, eventData _logSpectatorTickInfo = _.debounce((gameId)-> Logger.module("Game").debug "onSpectatorDelayedGameTick() ... #{games[gameId]?.spectatorGameEventBuffer?.length} buffered" if games[gameId]?.spectatorGameEventBuffer for eventData,i in games[gameId]?.spectatorGameEventBuffer Logger.module("Game").debug "onSpectatorDelayedGameTick() eventData: ",eventData , 1000) ###* # Emit/Broadcast game event to appropriate destination. # @public # @param {Socket} event Originating socket. # @param {String} gameId The game id for which to broadcast. # @param {Object} eventData Data to broadcast. ### emitGameEvent = (fromSocket,gameId,eventData)-> if games[gameId]? if eventData.type == EVENTS.step Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> step #{eventData.step?.index?.toString().yellow} with timestamp #{eventData.step?.timestamp} and action #{eventData.step?.action?.type}" # only broadcast valid steps if eventData.step? and eventData.step.timestamp? and eventData.step.action? # send the step to the owner for socketId,connected of io.sockets.adapter.rooms[gameId] socket = io.sockets.connected[socketId] if socket? and socket.playerId == eventData.step.playerId eventDataCopy = JSON.parse(JSON.stringify(eventData)) # always scrub steps for sensitive data from player perspective UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId) Logger.module("IO").debug "[G:#{gameId}]", "emitGameEvent -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.type} to origin" socket.emit EVENTS.network_game_event, eventDataCopy # NOTE: don't BREAK here because there is a potential case that during reconnection 3 sockets are connected: # 2 for this current reconnecting player and 1 for the opponent # breaking here would essentially result in only the DEAD socket in process of disconnecting receiving the event # break # buffer actions for the opponent other than a rollback action since that should clear the buffer during followups and there's no need to be sent to the opponent # essentially: skip processing anything for the opponent if this is a RollbackToSnapshotAction since only the sender cares about that one if eventData.step.action.type != SDK.RollbackToSnapshotAction.type # start buffering events until a followup is complete for the opponent since players can cancel out of a followup games[gameId].opponentEventDataBuffer.push(eventData) # if we have anything in the buffer and we are currently not buffering, flush the buffer over to your opponent if games[gameId].opponentEventDataBuffer.length > 0 and !games[gameId].session.getIsBufferingEvents() # copy buffer and reset opponentEventDataBuffer = games[gameId].opponentEventDataBuffer.slice(0) games[gameId].opponentEventDataBuffer.length = 0 # broadcast whatever's in the buffer to the opponent _.each(opponentEventDataBuffer, (eventData) -> for socketId,connected of io.sockets.adapter.rooms[gameId] socket = io.sockets.connected[socketId] if socket? and socket.playerId != eventData.step.playerId eventDataCopy = JSON.parse(JSON.stringify(eventData)) # always scrub steps for sensitive data from player perspective UtilsGameSession.scrubSensitiveActionData(games[gameId].session, eventDataCopy.step.action, socket.playerId) Logger.module("IO").log "[G:#{gameId}]", "emitGameEvent -> transmitting step #{eventData.step?.index?.toString().yellow} with action #{eventData.step.action?.type} to opponent" socket.emit EVENTS.network_game_event, eventDataCopy ) else if eventData.type == EVENTS.invalid_action # send the invalid action notification to the owner for socketId,connected of io.sockets.adapter.rooms[gameId] socket = io.sockets.connected[socketId] if socket? and socket.playerId == eventData.playerId eventDataCopy = JSON.parse(JSON.stringify(eventData)) socket.emit EVENTS.network_game_event, eventDataCopy # NOTE: don't BREAK here because there is a potential case that during reconnection 3 sockets are connected: # 2 for this current reconnecting player and 1 for the opponent # breaking here would essentially result in only the DEAD socket in process of disconnecting receiving the event else if eventData.type == EVENTS.network_game_hover or eventData.type == EVENTS.network_game_select or eventData.type == EVENTS.network_game_mouse_clear or eventData.type == EVENTS.show_emote # save the player id of this event eventData.playerId ?= fromSocket?.playerId eventData.timestamp = moment().utc().valueOf() # mouse events, emotes, etc should be saved and persisted to S3 for replays games[gameId].mouseAndUIEvents ?= [] games[gameId].mouseAndUIEvents.push(eventData) if fromSocket? # send it along to other connected sockets in the game room fromSocket.broadcast.to(gameId).emit EVENTS.network_game_event, eventData else # send to all sockets connected to the game room io.to(gameId).emit EVENTS.network_game_event, eventData # push a deep clone of the event data to the spectator buffer if games[gameId]?.spectateIsRunning spectatorEventDataCopy = JSON.parse(JSON.stringify(eventData)) games[gameId].spectatorGameEventBuffer.push(spectatorEventDataCopy) # if we're not running a timed delay, just flush everything now if not games[gameId]?.spectateIsDelayed flushSpectatorNetworkEventBuffer(gameId) ### # start a game session if one doesn't exist and call a completion handler when done # @public # @param {Object} gameId The game ID to load. # @param {Function} onComplete Callback when done. ### initGameSession = (gameId,onComplete) -> if games[gameId]?.loadingPromise return games[gameId].loadingPromise # setup local cache reference if none already there if not games[gameId] games[gameId] = opponentEventDataBuffer:[] connectedPlayers:[] session:null connectedSpectators:[] spectateIsRunning:false spectateIsDelayed:false spectateDelay:30000 spectatorGameEventBuffer:[] spectatorOpponentEventDataBuffer:[] spectatorDelayedGameSession:null turnTimerStartedAt: 0 turnTimeTickAt: 0 turnTimeRemaining: 0 turnTimeBonus: 0 # return game session from redis games[gameId].loadingPromise = Promise.all([ GameManager.loadGameSession(gameId) GameManager.loadGameMouseUIData(gameId) ]) .spread (gameData,mouseData)-> return [ JSON.parse(gameData) JSON.parse(mouseData) ] .spread (gameDataIn,mouseData) -> Logger.module("IO").log "[G:#{gameId}]", "initGameSession -> loaded game data for game:#{gameId}" # deserialize game session gameSession = SDK.GameSession.create() gameSession.setIsRunningAsAuthoritative(true) gameSession.deserializeSessionFromFirebase(gameDataIn) if gameSession.isOver() throw new Error("Game is already over!") # store session games[gameId].session = gameSession # store mouse and ui event data games[gameId].mouseAndUIEvents = mouseData saveGameCount(++gameCount) # in case the server restarted or loading data for first time, set the last action at timestamp for both players to now # this timestamp is used to shorten turn timer if player has not made any moves for a long time _.each(gameSession.players,(player)-> player.setLastActionTakenAt(Date.now()) ) # this is ugly but a simple way to subscribe to turn change events to save the game session subscribeToGameSessionEvents(gameId) # start the turn timer restartTurnTimer(gameId) return Promise.resolve([ games[gameId].session ]) .catch (error) -> Logger.module("IO").log "[G:#{gameId}]", "initGameSession:: error: #{JSON.stringify(error.message)}".red Logger.module("IO").log "[G:#{gameId}]", "initGameSession:: error stack: #{error.stack}".red # Report error to exceptionReporter with gameId exceptionReporter.notify(error, { errorName: "initGameSession Error", severity: "error", game: { id: gameId } }) throw error ### # start a spectator game session if one doesn't exist and call a completion handler when done # @public # @param {Object} gameId The game ID to load. # @param {Function} onComplete Callback when done. ### initSpectatorGameSession = (gameId)-> if not games[gameId] return Promise.reject(new Error("This game is no longer in progress")) return Promise.resolve() .then ()-> # if we're not already running spectate systems if not games[gameId].spectateIsRunning # mark that we are running spectate systems games[gameId].spectateIsRunning = true # if we're in the middle of a followup and we have some buffered events, we need to copy them over to the spectate buffer if games[gameId].session.getIsBufferingEvents() and games[gameId].opponentEventDataBuffer.length > 0 games[gameId].spectatorOpponentEventDataBuffer.length = 0 for eventData in games[gameId].opponentEventDataBuffer eventDataCopy = JSON.parse(JSON.stringify(eventData)) games[gameId].spectatorOpponentEventDataBuffer.push(eventDataCopy) if games[gameId].spectateIsDelayed and not games[gameId].spectatorDelayedGameSession Logger.module("...").log "[G:#{gameId}]", "initSpectatorDelayedGameSession() -> creating delayed game session" # create delayedGameDataIn = games[gameId].session.serializeToJSON(games[gameId].session) delayedGameSession = SDK.GameSession.create() delayedGameSession.setIsRunningAsAuthoritative(false) delayedGameSession.deserializeSessionFromFirebase(JSON.parse(delayedGameDataIn)) delayedGameSession.gameId = "SPECTATE:#{delayedGameSession.gameId}" games[gameId].spectatorDelayedGameSession = delayedGameSession # start timer to execute delayed / buffered spectator game events restartSpectatorDelayedGameInterval(gameId) return Promise.resolve(games[gameId].spectatorDelayedGameSession) else return Promise.resolve(games[gameId].session) ###* * Handler for before a game session rolls back to a snapshot. ### onBeforeRollbackToSnapshot = (event) -> # clear the buffer just before rolling back gameSession = event.gameSession gameId = gameSession.gameId game = games[gameId] if game? game.opponentEventDataBuffer.length = 0 # TODO: this will break delayed game session, needs a recode game.spectatorOpponentEventDataBuffer.length = 0 ###* * Handler for a game session step. ### onStep = (event) -> gameSession = event.gameSession gameId = gameSession.gameId game = games[gameId] if game? step = event.step if step? and step.timestamp? and step.action? # send out step events stepEventData = {type: EVENTS.step, step: JSON.parse(game.session.serializeToJSON(step))} emitGameEvent(null, gameId, stepEventData) # special action cases action = step.action if action instanceof SDK.EndTurnAction # save game on end turn # delay so that we don't block sending the step back to the players _.delay((()-> if games[gameId]? and games[gameId].session? GameManager.saveGameSession(gameId, games[gameId].session.serializeToJSON(games[gameId].session)) ), 500) else if action instanceof SDK.StartTurnAction # restart the turn timer whenever a turn starts restartTurnTimer(gameId) else if action instanceof SDK.DrawStartingHandAction # restart turn timer if both players have a starting hand and this step is for a DrawStartingHandAction bothPlayersHaveStartingHand = _.reduce(game.session.players,((memo,player)-> memo && player.getHasStartingHand()),true) if bothPlayersHaveStartingHand restartTurnTimer(gameId) if action.getIsAutomatic() and !game.session.getIsFollowupActive() # add bonus to turn time for every automatic step # unless followup is active, to prevent rollbacks for infinite turn time # bonus as a separate parameter accounts for cases such as: # - battle pet automatic actions eating up your own time # - queuing up many actions and ending turn quickly to eat into opponent's time game.turnTimeBonus += 2000 # when game is over and we have the final step # we cannot archive game until final step event # because otherwise step won't be finished/signed correctly # so we must do this on step event and not on game_over event if game.session.status == SDK.GameStatus.over # stop any turn timers stopTurnTimer(gameId) if !game.isArchived? game.isArchived = true afterGameOver(gameId, game.session, game.mouseAndUIEvents) ###* * Handler for an invalid action. ### onInvalidAction = (event) -> # safety fallback: if player attempts to make an invalid explicit action, notify that player only gameSession = event.gameSession gameId = gameSession.gameId game = games[gameId] if game? action = event.action if !action.getIsImplicit() #Logger.module("...").log "[G:#{gameId}]", "onInvalidAction -> INVALID ACTION: #{action.getLogName()} / VALIDATED BY: #{action.getValidatorType()} / MESSAGE: #{action.getValidationMessage()}" invalidActionEventData = { type: EVENTS.invalid_action, playerId: action.getOwnerId(), action: JSON.parse(game.session.serializeToJSON(action)), validatorType: event.validatorType, validationMessage: event.validationMessage, validationMessagePosition: event.validationMessagePosition, desync: gameSession.isActive() and gameSession.getCurrentPlayerId() == action.getOwnerId() and gameSession.getTurnTimeRemaining() > CONFIG.TURN_DURATION_LATENCY_BUFFER } emitGameEvent(null, gameId, invalidActionEventData) ### # Subscribes to the gamesession's event bus. # Can be called multiple times in order to re-subscribe. # @public # @param {Object} gameId The game ID to subscribe for. ### subscribeToGameSessionEvents = (gameId)-> Logger.module("...").debug "[G:#{gameId}]", "subscribeToGameSessionEvents -> subscribing to GameSession events" game = games[gameId] if game? # unsubscribe from previous unsubscribeFromGameSessionEvents(gameId) # listen for game events game.session.getEventBus().on(EVENTS.before_rollback_to_snapshot, onBeforeRollbackToSnapshot) game.session.getEventBus().on(EVENTS.step, onStep) game.session.getEventBus().on(EVENTS.invalid_action, onInvalidAction) ### # Unsubscribe from event listeners on the game session for this game ID. # @public # @param {String} gameId The game ID that needs to be unsubscribed. ### unsubscribeFromGameSessionEvents = (gameId)-> Logger.module("...").debug "[G:#{gameId}]", "unsubscribeFromGameSessionEvents -> un-subscribing from GameSession events" game = games[gameId] if game? game.session.getEventBus().off(EVENTS.before_rollback_to_snapshot, onBeforeRollbackToSnapshot) game.session.getEventBus().off(EVENTS.step, onStep) game.session.getEventBus().off(EVENTS.invalid_action, onInvalidAction) ### # must be called after game is over # processes a game, saves to redis, and kicks-off post-game processing jobs # @public # @param {String} gameId The game ID that is over. # @param {Object} gameSession The game session data. # @param {Array} mouseAndUIEvents The mouse and UI events for this game. ### afterGameOver = (gameId, gameSession, mouseAndUIEvents) -> Logger.module("GAME-OVER").log "[G:#{gameId}]", "---------- ======= GAME #{gameId} OVER ======= ---------".green # Update User Ranking, Progression, Quests, Stats updateUser = (userId, opponentId, gameId, factionId, generalId, isWinner, isDraw, ticketId) -> Logger.module("GAME-OVER").log "[G:#{gameId}]", "UPDATING user #{userId}. (winner:#{isWinner})" player = gameSession.getPlayerById(userId) isFriendly = gameSession.isFriendly() # get game type for user gameType = gameSession.getGameType() if gameType == SDK.GameType.Casual and player.getIsRanked() # casual games should be processed as ranked for ranked players gameType = SDK.GameType.Ranked # check for isUnscored isUnscored = false # calculate based on number of resign status and number of actions # if the game didn't have a single turn, mark the game as unscored if gameSession.getPlayerById(userId).hasResigned and gameSession.getTurns().length == 0 Logger.module("GAME-OVER").debug "[G:#{gameId}]", "User: #{userId} CONCEDED a game with 0 turns. Marking as UNSCORED".yellow isUnscored = true else if not isWinner and not isDraw # otherwise check how many actions the player took playerActionCount = 0 meaningfulActionCount = 0 moveActionCount = 0 for a in gameSession.getActions() # explicit actions if a.getOwnerId() == userId && a.getIsImplicit() == false playerActionCount++ # meaningful actions if a instanceof SDK.AttackAction if a.getTarget().getIsGeneral() meaningfulActionCount += 2 else meaningfulActionCount += 1 if a instanceof SDK.PlayCardFromHandAction or a instanceof SDK.PlaySignatureCardAction meaningfulActionCount += 1 if a instanceof SDK.BonusManaAction meaningfulActionCount += 2 # move actions if a instanceof SDK.MoveAction moveActionCount += 1 # more than 9 explicit actions # more than 1 move action # more than 5 meaningful actions if playerActionCount > 9 and moveActionCount > 1 and meaningfulActionCount > 4 break ### what we're looking for: * more than 9 explicit actions * more than 1 move action * more than 5 meaningful actions ... otherwise mark the game as unscored ### # Logger.module("GAME-OVER").log "[G:#{gameId}]", "User: #{userId} #{playerActionCount}, #{moveActionCount}, #{meaningfulActionCount}".cyan if playerActionCount <= 9 or moveActionCount <= 1 or meaningfulActionCount <= 4 Logger.module("GAME-OVER").debug "[G:#{gameId}]", "User: #{userId} CONCEDED a game with too few meaningful actions. Marking as UNSCORED".yellow isUnscored = true # start the job to process the game for a user return Jobs.create("update-user-post-game", name: "Update User Ranking" title: util.format("User %s :: Game %s", userId, gameId) userId: userId opponentId: opponentId gameId: gameId gameType: gameType factionId: factionId generalId: generalId isWinner: isWinner isDraw: isDraw isUnscored: isUnscored ticketId: ticketId ).removeOnComplete(true) # wait to save job until ready to process updateUsersRatings = (player1UserId, player2UserId, gameId, player1IsWinner, isDraw) -> # Detect if one player is casual playing in a ranked game player1IsRanked = gameSession.getPlayerById(player1UserId).getIsRanked() player2IsRanked = gameSession.getPlayerById(player2UserId).getIsRanked() gameType = gameSession.getGameType() if gameType == SDK.GameType.Casual and (player1IsRanked || player2IsRanked) # casual games should be processed as ranked for ranked players gameType = SDK.GameType.Ranked isRanked = gameType == SDK.GameType.Ranked Logger.module("GAME-OVER").debug "[G:#{gameId}]", "UPDATING users [#{player1UserId},#{player2UserId}] ratings." # Ratings only process in NON-FRIENDLY matches where at least 1 player is rank 0 if isRanked # start the job to process the ratings for the players return Jobs.create("update-users-ratings", name: "Update User Rating" title: util.format("Users [%s,%s] :: Game %s", player1UserId,player2UserId, gameId) player1UserId: player1UserId player1IsRanked: player1IsRanked player2UserId: player2UserId player2IsRanked: player2IsRanked gameId: gameId player1IsWinner: player1IsWinner isDraw: isDraw ).removeOnComplete(true).save() else return Promise.resolve() # Save then archive game session archiveGame = (gameId, gameSession, mouseAndUIEvents) -> return Promise.all([ GameManager.saveGameMouseUIData(gameId, JSON.stringify(mouseAndUIEvents)), GameManager.saveGameSession(gameId, gameSession.serializeToJSON(gameSession)) ]).then () -> # Job: Archive Game Jobs.create("archive-game", name: "Archive Game" title: util.format("Archiving Game %s", gameId) gameId: gameId gameType: gameSession.getGameType() ).removeOnComplete(true).save() # Builds a promise for executing the user update ratings job after player update jobs have completed updateUserRatingsPromise = (updatePlayer1Job,updatePlayer2Job,player1Id,player2Id,gameId,player1IsWinner,isDraw) -> # Wait until both players update jobs have completed before updating ratings return Promise.all([ new Promise (resolve,reject) -> updatePlayer1Job.on("complete",resolve); updatePlayer1Job.on("error",reject), new Promise (resolve,reject) -> updatePlayer2Job.on("complete",resolve); updatePlayer2Job.on("error",reject) ]).then () -> updateUsersRatings(player1Id,player2Id,gameId,player1IsWinner,isDraw) .catch (error) -> Logger.module("GAME-OVER").error "[G:#{gameId}]", "ERROR: afterGameOver update player job failed #{error}".red # issue a warning to our exceptionReporter error tracker exceptionReporter.notify(error, { errorName: "afterGameOver update player job failed", severity: "error" game: id: gameId gameType: gameSession.gameType player1Id: player1Id player2Id: player2Id winnerId: winnerId loserId: loserId }) # gamesession player data player1Id = gameSession.getPlayer1Id() player2Id = gameSession.getPlayer2Id() player1FactionId = gameSession.getPlayer1SetupData()?.factionId player2FactionId = gameSession.getPlayer2SetupData()?.factionId player1GeneralId = gameSession.getPlayer1SetupData()?.generalId player2GeneralId = gameSession.getPlayer2SetupData()?.generalId player1TicketId = gameSession.getPlayer1SetupData()?.ticketId player2TicketId = gameSession.getPlayer2SetupData()?.ticketId winnerId = gameSession.getWinnerId() loserId = gameSession.getWinnerId() player1IsWinner = (player1Id == winnerId) isDraw = if !winnerId? then true else false # update promises promises = [] # update users updatePlayer1Job = updateUser(player1Id,player2Id,gameId,player1FactionId,player1GeneralId,(player1Id == winnerId),isDraw,player1TicketId) updatePlayer2Job = updateUser(player2Id,player1Id,gameId,player2FactionId,player2GeneralId,(player2Id == winnerId),isDraw,player2TicketId) # wait until both players update jobs have completed before updating ratings promises.push(updateUserRatingsPromise(updatePlayer1Job,updatePlayer2Job,player1Id,player2Id,gameId,player1IsWinner,isDraw)) updatePlayer1Job.save() updatePlayer2Job.save() # archive game promises.push(archiveGame(gameId, gameSession, mouseAndUIEvents)) # execute promises Promise.all(promises) .then () -> Logger.module("GAME-OVER").debug "[G:#{gameId}]", "afterGameOver done, game is being archived".green .catch (error) -> Logger.module("GAME-OVER").error "[G:#{gameId}]", "ERROR: afterGameOver failed #{error}".red # issue a warning to exceptionReporter exceptionReporter.notify(error, { errorName: "afterGameOver failed", severity: "error" game: id: gameId gameType: gameSession.getGameType() player1Id: player1Id player2Id: player2Id winnerId: winnerId loserId: loserId }) ### Shutdown Handler ### shutdown = () -> Logger.module("SERVER").log "Shutting down game server." Logger.module("SERVER").log "Active Players: #{playerCount}." Logger.module("SERVER").log "Active Games: #{gameCount}." if !config.get('consul.enabled') process.exit(0) return Consul.getReassignmentStatus() .then (reassign) -> if reassign == false Logger.module("SERVER").log "Reassignment disabled - exiting." process.exit(0) # Build an array of game IDs ids = [] _.each games, (game, id) -> ids.push(id) # Map to save each game to Redis before shutdown return Promise.map ids, (id) -> serializedData = games[id].session.serializeToJSON(games[id].session) return GameManager.saveGameSession(id, serializedData) .then () -> return Consul.getHealthyServers() .then (servers) -> # Filter 'yourself' from list of nodes filtered = _.reject servers, (server)-> return server["Node"]?["Node"] == os.hostname() if filtered.length == 0 Logger.module("SERVER").log "No servers available - exiting without re-assignment." process.exit(1) random_node = _.sample(filtered) node_name = random_node["Node"]?["Node"] return Consul.kv.get("nodes/#{node_name}/public_ip") .then (newServerIp) -> # Development override for testing, bounces between port 9000 & 9001 if config.isDevelopment() port = 9001 if config.get('port') is 9000 port = 9000 if config.get('port') is 9001 newServerIp = "127.0.0.1:#{port}" msg = "Server is shutting down. You will be reconnected automatically." io.emit "game_server_shutdown", {msg:msg,ip:newServerIp} Logger.module("SERVER").log "Players reconnecting to: #{newServerIp}" Logger.module("SERVER").log "Re-assignment complete. Exiting." process.exit(0) .catch (err) -> Logger.module("SERVER").log "Re-assignment failed: #{err.message}. Exiting." process.exit(1) process.on "SIGTERM", shutdown process.on "SIGINT", shutdown process.on "SIGHUP", shutdown process.on "SIGQUIT", shutdown
[ { "context": "e: 'Place'\n\n Author = createModel\n name: 'Author'\n connection: createClient()\n\n Book = cre", "end": 304, "score": 0.814221978187561, "start": 298, "tag": "NAME", "value": "Author" }, { "context": " minItems: 0\n\n fitzgerald = Author.create 'f-scott', born:1896\n fitzgerald.put().then fitzgeral", "end": 750, "score": 0.9996996521949768, "start": 743, "tag": "NAME", "value": "f-scott" }, { "context": "reate 'oak-park'\n hemingway = Author.create 'ernest', born:1899\n\n hemingway.put().catch ->\n ", "end": 1072, "score": 0.9996156692504883, "start": 1066, "tag": "NAME", "value": "ernest" }, { "context": " maxItems: 2\n\n faulkner = Author.create 'will', born:1897\n faulkner.link 'advanced-payment", "end": 1436, "score": 0.9973498582839966, "start": 1432, "tag": "NAME", "value": "will" }, { "context": "et'\n tag: 'ship'\n\n a = Author.create 'heinlein'\n a.link 'ship', {}\n a.put().catch (err", "end": 2016, "score": 0.9721070528030396, "start": 2008, "tag": "NAME", "value": "heinlein" } ]
ExampleZukaiRestApi/node_modules/zukai/test/default-plugins.coffee
radjivC/interaction-node-riak
0
assert = require 'assert' {createClient} = require 'riakpbc' {createModel, plugins} = require '../src' Place = Author = Book = Cover = null connection = null describe 'Default Plugins', -> beforeEach (done)-> Place = createModel name: 'Place' Author = createModel name: 'Author' connection: createClient() Book = createModel name: 'Book' connection: createClient() Cover = createModel name: 'Cover' connection: createClient() done() describe 'relation', -> it 'should allow missing relationship when minItems=0', (done)-> Author.plugin plugins.relation, type: 'Place' tag: 'birth-place' minItems: 0 fitzgerald = Author.create 'f-scott', born:1896 fitzgerald.put().then fitzgerald.del done it 'should not allow missing relationship when minItems=1', (done)-> Author.plugin plugins.relation, type: 'Place' tag: 'birth-place' minItems: 1 oakpark = Place.create 'oak-park' hemingway = Author.create 'ernest', born:1899 hemingway.put().catch -> hemingway.link 'birth-place', oakpark hemingway.put().then hemingway.del done it 'should not allow more than given maxItems relationships', (done)-> Author.plugin plugins.relation, type: 'Book' tag: 'advanced-payment' maxItems: 2 faulkner = Author.create 'will', born:1897 faulkner.link 'advanced-payment', Book.create 'mosquitoes' faulkner.link 'advanced-payment', Book.create 'sanctuary' faulkner.link 'advanced-payment', Book.create 'pylon' faulkner.put().catch (err)-> assert err.message+'' == 'Error: Too many relations for Book:advanced-payment' faulkner.links.pop() faulkner.put().then faulkner.del done it 'should not allow relations to missing models', (done)-> Author.plugin plugins.relation, type: 'Rocket' tag: 'ship' a = Author.create 'heinlein' a.link 'ship', {} a.put().catch (err)-> assert "#{err.message}" == 'Error: No model Rocket' done() it 'should not allow relations to undefined models', (done)-> try Author.plugin plugins.relation, tag:'nope' catch err assert "#{err.message}" == 'Missing type' done()
75788
assert = require 'assert' {createClient} = require 'riakpbc' {createModel, plugins} = require '../src' Place = Author = Book = Cover = null connection = null describe 'Default Plugins', -> beforeEach (done)-> Place = createModel name: 'Place' Author = createModel name: '<NAME>' connection: createClient() Book = createModel name: 'Book' connection: createClient() Cover = createModel name: 'Cover' connection: createClient() done() describe 'relation', -> it 'should allow missing relationship when minItems=0', (done)-> Author.plugin plugins.relation, type: 'Place' tag: 'birth-place' minItems: 0 fitzgerald = Author.create '<NAME>', born:1896 fitzgerald.put().then fitzgerald.del done it 'should not allow missing relationship when minItems=1', (done)-> Author.plugin plugins.relation, type: 'Place' tag: 'birth-place' minItems: 1 oakpark = Place.create 'oak-park' hemingway = Author.create '<NAME>', born:1899 hemingway.put().catch -> hemingway.link 'birth-place', oakpark hemingway.put().then hemingway.del done it 'should not allow more than given maxItems relationships', (done)-> Author.plugin plugins.relation, type: 'Book' tag: 'advanced-payment' maxItems: 2 faulkner = Author.create '<NAME>', born:1897 faulkner.link 'advanced-payment', Book.create 'mosquitoes' faulkner.link 'advanced-payment', Book.create 'sanctuary' faulkner.link 'advanced-payment', Book.create 'pylon' faulkner.put().catch (err)-> assert err.message+'' == 'Error: Too many relations for Book:advanced-payment' faulkner.links.pop() faulkner.put().then faulkner.del done it 'should not allow relations to missing models', (done)-> Author.plugin plugins.relation, type: 'Rocket' tag: 'ship' a = Author.create '<NAME>' a.link 'ship', {} a.put().catch (err)-> assert "#{err.message}" == 'Error: No model Rocket' done() it 'should not allow relations to undefined models', (done)-> try Author.plugin plugins.relation, tag:'nope' catch err assert "#{err.message}" == 'Missing type' done()
true
assert = require 'assert' {createClient} = require 'riakpbc' {createModel, plugins} = require '../src' Place = Author = Book = Cover = null connection = null describe 'Default Plugins', -> beforeEach (done)-> Place = createModel name: 'Place' Author = createModel name: 'PI:NAME:<NAME>END_PI' connection: createClient() Book = createModel name: 'Book' connection: createClient() Cover = createModel name: 'Cover' connection: createClient() done() describe 'relation', -> it 'should allow missing relationship when minItems=0', (done)-> Author.plugin plugins.relation, type: 'Place' tag: 'birth-place' minItems: 0 fitzgerald = Author.create 'PI:NAME:<NAME>END_PI', born:1896 fitzgerald.put().then fitzgerald.del done it 'should not allow missing relationship when minItems=1', (done)-> Author.plugin plugins.relation, type: 'Place' tag: 'birth-place' minItems: 1 oakpark = Place.create 'oak-park' hemingway = Author.create 'PI:NAME:<NAME>END_PI', born:1899 hemingway.put().catch -> hemingway.link 'birth-place', oakpark hemingway.put().then hemingway.del done it 'should not allow more than given maxItems relationships', (done)-> Author.plugin plugins.relation, type: 'Book' tag: 'advanced-payment' maxItems: 2 faulkner = Author.create 'PI:NAME:<NAME>END_PI', born:1897 faulkner.link 'advanced-payment', Book.create 'mosquitoes' faulkner.link 'advanced-payment', Book.create 'sanctuary' faulkner.link 'advanced-payment', Book.create 'pylon' faulkner.put().catch (err)-> assert err.message+'' == 'Error: Too many relations for Book:advanced-payment' faulkner.links.pop() faulkner.put().then faulkner.del done it 'should not allow relations to missing models', (done)-> Author.plugin plugins.relation, type: 'Rocket' tag: 'ship' a = Author.create 'PI:NAME:<NAME>END_PI' a.link 'ship', {} a.put().catch (err)-> assert "#{err.message}" == 'Error: No model Rocket' done() it 'should not allow relations to undefined models', (done)-> try Author.plugin plugins.relation, tag:'nope' catch err assert "#{err.message}" == 'Missing type' done()
[ { "context": "ms\n body :\n password : generateRandomString()\n recoveryToken : ''\n\n request.post re", "end": 1529, "score": 0.8977211117744446, "start": 1509, "tag": "PASSWORD", "value": "generateRandomString" }, { "context": " password : ''\n recoveryToken : generateRandomString()\n\n request.post resetRequestParams, (err, res", "end": 1966, "score": 0.6580500602722168, "start": 1946, "tag": "KEY", "value": "generateRandomString" }, { "context": "ms\n body :\n password : generateRandomString()\n recoveryToken : generateRandomString()\n", "end": 2351, "score": 0.9458763599395752, "start": 2331, "tag": "PASSWORD", "value": "generateRandomString" }, { "context": " : generateRandomString()\n recoveryToken : generateRandomString()\n\n request.post resetRequestParams, (err, res", "end": 2398, "score": 0.5752138495445251, "start": 2378, "tag": "KEY", "value": "generateRandomString" }, { "context": " = generateRandomEmail()\n token = generateRandomString()\n username = generateRandomUsername()\n ", "end": 2741, "score": 0.6812682151794434, "start": 2721, "tag": "KEY", "value": "generateRandomString" }, { "context": " = generateRandomString()\n username = generateRandomUsername()\n certificate = null\n expiryPeriod = defa", "end": 2785, "score": 0.9946079850196838, "start": 2763, "tag": "USERNAME", "value": "generateRandomUsername" }, { "context": "ms\n body :\n password : generateRandomString()\n recoveryToken : token\n\n queue = [\n\n ", "end": 3048, "score": 0.9900093078613281, "start": 3028, "tag": "PASSWORD", "value": "generateRandomString" }, { "context": " status : 'active'\n username : username\n expiryPeriod : expiryPeriod\n\n ce", "end": 3339, "score": 0.999414324760437, "start": 3331, "tag": "USERNAME", "value": "username" }, { "context": " = generateRandomEmail()\n token = generateRandomString()\n username = generateRandomUsername()\n ", "end": 4574, "score": 0.5893391966819763, "start": 4554, "tag": "KEY", "value": "generateRandomString" }, { "context": " = generateRandomString()\n username = generateRandomUsername()\n certificate = null\n expiryPeriod = defaul", "end": 4618, "score": 0.9280045628547668, "start": 4596, "tag": "USERNAME", "value": "generateRandomUsername" }, { "context": "ms\n body :\n password : generateRandomString()\n recoveryToken : token\n\n queue = [\n\n ", "end": 4805, "score": 0.9703192710876465, "start": 4785, "tag": "PASSWORD", "value": "generateRandomString" }, { "context": " status : 'active'\n username : username\n expiryPeriod : expiryPeriod\n\n ce", "end": 5096, "score": 0.9894073605537415, "start": 5088, "tag": "USERNAME", "value": "username" }, { "context": " = generateRandomEmail()\n token = generateRandomString()\n username = generateRandomUsernam", "end": 5765, "score": 0.5936930179595947, "start": 5745, "tag": "KEY", "value": "generateRandomString" }, { "context": "= generateRandomString()\n username = generateRandomUsername()\n certificate = null\n expiryPeriod ", "end": 5816, "score": 0.9233294725418091, "start": 5794, "tag": "USERNAME", "value": "generateRandomUsername" }, { "context": "ms\n body :\n password : generateRandomString()\n recoveryToken : token\n\n registerReques", "end": 6048, "score": 0.9525091648101807, "start": 6028, "tag": "PASSWORD", "value": "generateRandomString" }, { "context": " :\n email : email\n username : username\n\n queue = [\n\n (next) ->\n # generat", "end": 6211, "score": 0.9956890940666199, "start": 6203, "tag": "USERNAME", "value": "username" }, { "context": " status : 'active'\n username : username\n expiryPeriod : expiryPeriod\n\n ce", "end": 6470, "score": 0.9975157380104065, "start": 6462, "tag": "USERNAME", "value": "username" }, { "context": " = generateRandomEmail()\n token1 = generateRandomString()\n token2 = generateRandomString(", "end": 7737, "score": 0.5727312564849854, "start": 7717, "tag": "KEY", "value": "generateRandomString" }, { "context": "= generateRandomString()\n token2 = generateRandomString()\n username = generateRandomUsernam", "end": 7786, "score": 0.6337806582450867, "start": 7766, "tag": "KEY", "value": "generateRandomString" }, { "context": "= generateRandomString()\n username = generateRandomUsername()\n certificate1 = null\n certificate2 ", "end": 7837, "score": 0.9413401484489441, "start": 7815, "tag": "USERNAME", "value": "generateRandomUsername" }, { "context": "ms\n body :\n password : generateRandomString()\n recoveryToken : token1\n\n registerReque", "end": 8069, "score": 0.9485868215560913, "start": 8049, "tag": "PASSWORD", "value": "generateRandomString" }, { "context": " email : email\n username : username\n\n queue = [\n\n (next) ->\n # generat", "end": 8254, "score": 0.9919477105140686, "start": 8246, "tag": "USERNAME", "value": "username" }, { "context": " status : 'active'\n username : username\n expiryPeriod : expiryPeriod\n\n ce", "end": 8515, "score": 0.9934808015823364, "start": 8507, "tag": "USERNAME", "value": "username" }, { "context": " status : 'active'\n username : username\n expiryPeriod : expiryPeriod\n\n ce", "end": 8911, "score": 0.9940440058708191, "start": 8903, "tag": "USERNAME", "value": "username" } ]
servers/lib/server/handlers/reset.test.coffee
ezgikaysi/koding
1
{ async expect request generateRandomEmail generateRandomString generateRandomUsername checkBongoConnectivity } = require '../../../testhelper' { testCsrfToken } = require '../../../testhelper/handler' { defaultExpiryPeriod generateResetRequestParams } = require '../../../testhelper/handler/resethelper' { generateRegisterRequestParams } = require '../../../testhelper/handler/registerhelper' JUser = require '../../../models/user' JPasswordRecovery = require '../../../models/passwordrecovery' beforeTests = before (done) -> checkBongoConnectivity done # here we have actual tests runTests = -> describe 'server.handlers.reset', -> it 'should fail when csrf token is invalid', (done) -> testCsrfToken generateResetRequestParams, 'post', done it 'should send HTTP 404 if request method is not POST', (done) -> resetRequestParams = generateResetRequestParams() queue = [] methods = ['put', 'patch', 'delete'] addRequestToQueue = (queue, method) -> queue.push (next) -> resetRequestParams.method = method request resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 404 next() for method in methods addRequestToQueue queue, method async.series queue, done it 'should send HTTP 400 if token is not set', (done) -> resetRequestParams = generateResetRequestParams body : password : generateRandomString() recoveryToken : '' request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal 'Invalid token!' done() it 'should send HTTP 400 if password is not set', (done) -> resetRequestParams = generateResetRequestParams body : password : '' recoveryToken : generateRandomString() request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal 'Invalid password!' done() it 'should send HTTP 400 if token is not found', (done) -> resetRequestParams = generateResetRequestParams body : password : generateRandomString() recoveryToken : generateRandomString() request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal 'Invalid token.' done() it 'should send HTTP 400 if token is not active', (done) -> email = generateRandomEmail() token = generateRandomString() username = generateRandomUsername() certificate = null expiryPeriod = defaultExpiryPeriod expectedBody = 'This password recovery certificate cannot be redeemed.' resetRequestParams = generateResetRequestParams body : password : generateRandomString() recoveryToken : token queue = [ (next) -> # generating a new certificate and saving it certificate = new JPasswordRecovery email : email token : token status : 'active' username : username expiryPeriod : expiryPeriod certificate.save (err) -> expect(err).to.not.exist next() (next) -> # redeeming certificate without before reset request certificate.redeem (err) -> expect(err).to.not.exist next() (next) -> # expecting failure because certificate status is redeemed request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal expectedBody next() (next) -> # expiring certificate before reset request certificate.expire (err) -> expect(err).to.not.exist next() (next) -> # expecting failure because certificate status is expired request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal expectedBody next() ] async.series queue, done it 'should send HTTP 400 if token is valid but user doesnt exist', (done) -> email = generateRandomEmail() token = generateRandomString() username = generateRandomUsername() certificate = null expiryPeriod = defaultExpiryPeriod resetRequestParams = generateResetRequestParams body : password : generateRandomString() recoveryToken : token queue = [ (next) -> # generating a new certificate and saving it certificate = new JPasswordRecovery email : email token : token status : 'active' username : username expiryPeriod : expiryPeriod certificate.save (err) -> expect(err).to.not.exist next() (next) -> # expecting failure because user doesn't exist expectedBody = 'Unknown user!' request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal expectedBody next() ] async.series queue, done it 'should send HTTP 200 and reset password when token and user are valid', (done) -> email = generateRandomEmail() token = generateRandomString() username = generateRandomUsername() certificate = null expiryPeriod = defaultExpiryPeriod passwordBeforeReset = null resetRequestParams = generateResetRequestParams body : password : generateRandomString() recoveryToken : token registerRequestParams = generateRegisterRequestParams body : email : email username : username queue = [ (next) -> # generating a new certificate and saving it certificate = new JPasswordRecovery email : email token : token status : 'active' username : username expiryPeriod : expiryPeriod certificate.save (err) -> expect(err).to.not.exist next() (next) -> # registering a new user request.post registerRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 next() (next) -> # keeping user's password to compare after reset request JUser.one { username }, (err, user) -> expect(err).to.not.exist passwordBeforeReset = user.password next() (next) -> # expecting reset request to succeed request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 next() (next) -> # expecting user's password not to be changed after reset request JUser.one { username }, (err, user) -> expect(err).to.not.exist expect(user.password).to.not.be.equal passwordBeforeReset next() ] async.series queue, done it 'should send HTTP 200 and invalidate other tokens after resetting', (done) -> email = generateRandomEmail() token1 = generateRandomString() token2 = generateRandomString() username = generateRandomUsername() certificate1 = null certificate2 = null expiryPeriod = defaultExpiryPeriod resetRequestParams = generateResetRequestParams body : password : generateRandomString() recoveryToken : token1 registerRequestParams = generateRegisterRequestParams body : email : email username : username queue = [ (next) -> # generating a new certificate and saving it certificate1 = new JPasswordRecovery email : email token : token1 status : 'active' username : username expiryPeriod : expiryPeriod certificate1.save (err) -> expect(err).to.not.exist next() (next) -> #generating another certificate which will be checked if invalidated certificate2 = new JPasswordRecovery email : email token : token2 status : 'active' username : username expiryPeriod : expiryPeriod certificate2.save (err) -> expect(err).to.not.exist next() (next) -> # registering a new user request.post registerRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 next() (next) -> # expecting reset request to succeed request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 next() (next) -> # expecting other token's status be updated as 'invalidated' JPasswordRecovery.one { token : token2 }, (err, certificate) -> expect(err).to.not.exist expect(certificate?.status).to.be.equal 'invalidated' next() ] async.series queue, done runTests()
26081
{ async expect request generateRandomEmail generateRandomString generateRandomUsername checkBongoConnectivity } = require '../../../testhelper' { testCsrfToken } = require '../../../testhelper/handler' { defaultExpiryPeriod generateResetRequestParams } = require '../../../testhelper/handler/resethelper' { generateRegisterRequestParams } = require '../../../testhelper/handler/registerhelper' JUser = require '../../../models/user' JPasswordRecovery = require '../../../models/passwordrecovery' beforeTests = before (done) -> checkBongoConnectivity done # here we have actual tests runTests = -> describe 'server.handlers.reset', -> it 'should fail when csrf token is invalid', (done) -> testCsrfToken generateResetRequestParams, 'post', done it 'should send HTTP 404 if request method is not POST', (done) -> resetRequestParams = generateResetRequestParams() queue = [] methods = ['put', 'patch', 'delete'] addRequestToQueue = (queue, method) -> queue.push (next) -> resetRequestParams.method = method request resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 404 next() for method in methods addRequestToQueue queue, method async.series queue, done it 'should send HTTP 400 if token is not set', (done) -> resetRequestParams = generateResetRequestParams body : password : <PASSWORD>() recoveryToken : '' request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal 'Invalid token!' done() it 'should send HTTP 400 if password is not set', (done) -> resetRequestParams = generateResetRequestParams body : password : '' recoveryToken : <PASSWORD>() request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal 'Invalid password!' done() it 'should send HTTP 400 if token is not found', (done) -> resetRequestParams = generateResetRequestParams body : password : <PASSWORD>() recoveryToken : <PASSWORD>() request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal 'Invalid token.' done() it 'should send HTTP 400 if token is not active', (done) -> email = generateRandomEmail() token = <PASSWORD>() username = generateRandomUsername() certificate = null expiryPeriod = defaultExpiryPeriod expectedBody = 'This password recovery certificate cannot be redeemed.' resetRequestParams = generateResetRequestParams body : password : <PASSWORD>() recoveryToken : token queue = [ (next) -> # generating a new certificate and saving it certificate = new JPasswordRecovery email : email token : token status : 'active' username : username expiryPeriod : expiryPeriod certificate.save (err) -> expect(err).to.not.exist next() (next) -> # redeeming certificate without before reset request certificate.redeem (err) -> expect(err).to.not.exist next() (next) -> # expecting failure because certificate status is redeemed request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal expectedBody next() (next) -> # expiring certificate before reset request certificate.expire (err) -> expect(err).to.not.exist next() (next) -> # expecting failure because certificate status is expired request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal expectedBody next() ] async.series queue, done it 'should send HTTP 400 if token is valid but user doesnt exist', (done) -> email = generateRandomEmail() token = <PASSWORD>() username = generateRandomUsername() certificate = null expiryPeriod = defaultExpiryPeriod resetRequestParams = generateResetRequestParams body : password : <PASSWORD>() recoveryToken : token queue = [ (next) -> # generating a new certificate and saving it certificate = new JPasswordRecovery email : email token : token status : 'active' username : username expiryPeriod : expiryPeriod certificate.save (err) -> expect(err).to.not.exist next() (next) -> # expecting failure because user doesn't exist expectedBody = 'Unknown user!' request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal expectedBody next() ] async.series queue, done it 'should send HTTP 200 and reset password when token and user are valid', (done) -> email = generateRandomEmail() token = <PASSWORD>() username = generateRandomUsername() certificate = null expiryPeriod = defaultExpiryPeriod passwordBeforeReset = null resetRequestParams = generateResetRequestParams body : password : <PASSWORD>() recoveryToken : token registerRequestParams = generateRegisterRequestParams body : email : email username : username queue = [ (next) -> # generating a new certificate and saving it certificate = new JPasswordRecovery email : email token : token status : 'active' username : username expiryPeriod : expiryPeriod certificate.save (err) -> expect(err).to.not.exist next() (next) -> # registering a new user request.post registerRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 next() (next) -> # keeping user's password to compare after reset request JUser.one { username }, (err, user) -> expect(err).to.not.exist passwordBeforeReset = user.password next() (next) -> # expecting reset request to succeed request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 next() (next) -> # expecting user's password not to be changed after reset request JUser.one { username }, (err, user) -> expect(err).to.not.exist expect(user.password).to.not.be.equal passwordBeforeReset next() ] async.series queue, done it 'should send HTTP 200 and invalidate other tokens after resetting', (done) -> email = generateRandomEmail() token1 = <PASSWORD>() token2 = <PASSWORD>() username = generateRandomUsername() certificate1 = null certificate2 = null expiryPeriod = defaultExpiryPeriod resetRequestParams = generateResetRequestParams body : password : <PASSWORD>() recoveryToken : token1 registerRequestParams = generateRegisterRequestParams body : email : email username : username queue = [ (next) -> # generating a new certificate and saving it certificate1 = new JPasswordRecovery email : email token : token1 status : 'active' username : username expiryPeriod : expiryPeriod certificate1.save (err) -> expect(err).to.not.exist next() (next) -> #generating another certificate which will be checked if invalidated certificate2 = new JPasswordRecovery email : email token : token2 status : 'active' username : username expiryPeriod : expiryPeriod certificate2.save (err) -> expect(err).to.not.exist next() (next) -> # registering a new user request.post registerRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 next() (next) -> # expecting reset request to succeed request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 next() (next) -> # expecting other token's status be updated as 'invalidated' JPasswordRecovery.one { token : token2 }, (err, certificate) -> expect(err).to.not.exist expect(certificate?.status).to.be.equal 'invalidated' next() ] async.series queue, done runTests()
true
{ async expect request generateRandomEmail generateRandomString generateRandomUsername checkBongoConnectivity } = require '../../../testhelper' { testCsrfToken } = require '../../../testhelper/handler' { defaultExpiryPeriod generateResetRequestParams } = require '../../../testhelper/handler/resethelper' { generateRegisterRequestParams } = require '../../../testhelper/handler/registerhelper' JUser = require '../../../models/user' JPasswordRecovery = require '../../../models/passwordrecovery' beforeTests = before (done) -> checkBongoConnectivity done # here we have actual tests runTests = -> describe 'server.handlers.reset', -> it 'should fail when csrf token is invalid', (done) -> testCsrfToken generateResetRequestParams, 'post', done it 'should send HTTP 404 if request method is not POST', (done) -> resetRequestParams = generateResetRequestParams() queue = [] methods = ['put', 'patch', 'delete'] addRequestToQueue = (queue, method) -> queue.push (next) -> resetRequestParams.method = method request resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 404 next() for method in methods addRequestToQueue queue, method async.series queue, done it 'should send HTTP 400 if token is not set', (done) -> resetRequestParams = generateResetRequestParams body : password : PI:PASSWORD:<PASSWORD>END_PI() recoveryToken : '' request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal 'Invalid token!' done() it 'should send HTTP 400 if password is not set', (done) -> resetRequestParams = generateResetRequestParams body : password : '' recoveryToken : PI:KEY:<PASSWORD>END_PI() request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal 'Invalid password!' done() it 'should send HTTP 400 if token is not found', (done) -> resetRequestParams = generateResetRequestParams body : password : PI:PASSWORD:<PASSWORD>END_PI() recoveryToken : PI:KEY:<PASSWORD>END_PI() request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal 'Invalid token.' done() it 'should send HTTP 400 if token is not active', (done) -> email = generateRandomEmail() token = PI:KEY:<PASSWORD>END_PI() username = generateRandomUsername() certificate = null expiryPeriod = defaultExpiryPeriod expectedBody = 'This password recovery certificate cannot be redeemed.' resetRequestParams = generateResetRequestParams body : password : PI:PASSWORD:<PASSWORD>END_PI() recoveryToken : token queue = [ (next) -> # generating a new certificate and saving it certificate = new JPasswordRecovery email : email token : token status : 'active' username : username expiryPeriod : expiryPeriod certificate.save (err) -> expect(err).to.not.exist next() (next) -> # redeeming certificate without before reset request certificate.redeem (err) -> expect(err).to.not.exist next() (next) -> # expecting failure because certificate status is redeemed request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal expectedBody next() (next) -> # expiring certificate before reset request certificate.expire (err) -> expect(err).to.not.exist next() (next) -> # expecting failure because certificate status is expired request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal expectedBody next() ] async.series queue, done it 'should send HTTP 400 if token is valid but user doesnt exist', (done) -> email = generateRandomEmail() token = PI:KEY:<PASSWORD>END_PI() username = generateRandomUsername() certificate = null expiryPeriod = defaultExpiryPeriod resetRequestParams = generateResetRequestParams body : password : PI:PASSWORD:<PASSWORD>END_PI() recoveryToken : token queue = [ (next) -> # generating a new certificate and saving it certificate = new JPasswordRecovery email : email token : token status : 'active' username : username expiryPeriod : expiryPeriod certificate.save (err) -> expect(err).to.not.exist next() (next) -> # expecting failure because user doesn't exist expectedBody = 'Unknown user!' request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 400 expect(body).to.be.equal expectedBody next() ] async.series queue, done it 'should send HTTP 200 and reset password when token and user are valid', (done) -> email = generateRandomEmail() token = PI:KEY:<PASSWORD>END_PI() username = generateRandomUsername() certificate = null expiryPeriod = defaultExpiryPeriod passwordBeforeReset = null resetRequestParams = generateResetRequestParams body : password : PI:PASSWORD:<PASSWORD>END_PI() recoveryToken : token registerRequestParams = generateRegisterRequestParams body : email : email username : username queue = [ (next) -> # generating a new certificate and saving it certificate = new JPasswordRecovery email : email token : token status : 'active' username : username expiryPeriod : expiryPeriod certificate.save (err) -> expect(err).to.not.exist next() (next) -> # registering a new user request.post registerRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 next() (next) -> # keeping user's password to compare after reset request JUser.one { username }, (err, user) -> expect(err).to.not.exist passwordBeforeReset = user.password next() (next) -> # expecting reset request to succeed request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 next() (next) -> # expecting user's password not to be changed after reset request JUser.one { username }, (err, user) -> expect(err).to.not.exist expect(user.password).to.not.be.equal passwordBeforeReset next() ] async.series queue, done it 'should send HTTP 200 and invalidate other tokens after resetting', (done) -> email = generateRandomEmail() token1 = PI:KEY:<PASSWORD>END_PI() token2 = PI:KEY:<PASSWORD>END_PI() username = generateRandomUsername() certificate1 = null certificate2 = null expiryPeriod = defaultExpiryPeriod resetRequestParams = generateResetRequestParams body : password : PI:PASSWORD:<PASSWORD>END_PI() recoveryToken : token1 registerRequestParams = generateRegisterRequestParams body : email : email username : username queue = [ (next) -> # generating a new certificate and saving it certificate1 = new JPasswordRecovery email : email token : token1 status : 'active' username : username expiryPeriod : expiryPeriod certificate1.save (err) -> expect(err).to.not.exist next() (next) -> #generating another certificate which will be checked if invalidated certificate2 = new JPasswordRecovery email : email token : token2 status : 'active' username : username expiryPeriod : expiryPeriod certificate2.save (err) -> expect(err).to.not.exist next() (next) -> # registering a new user request.post registerRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 next() (next) -> # expecting reset request to succeed request.post resetRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 next() (next) -> # expecting other token's status be updated as 'invalidated' JPasswordRecovery.one { token : token2 }, (err, certificate) -> expect(err).to.not.exist expect(certificate?.status).to.be.equal 'invalidated' next() ] async.series queue, done runTests()
[ { "context": "lution timer polyfill with Date fallback\n @author Daniel Lamb <dlamb.open.source@gmail.com>\n###\nperfnow = (glob", "end": 127, "score": 0.9998614192008972, "start": 116, "tag": "NAME", "value": "Daniel Lamb" }, { "context": "olyfill with Date fallback\n @author Daniel Lamb <dlamb.open.source@gmail.com>\n###\nperfnow = (global) ->\n # make sure we have ", "end": 156, "score": 0.9999352693557739, "start": 129, "tag": "EMAIL", "value": "dlamb.open.source@gmail.com" } ]
perfnow.coffee
daniellmb/perfnow.js
41
###* @file perfnow is a 0.1 kb global.performance.now high resolution timer polyfill with Date fallback @author Daniel Lamb <dlamb.open.source@gmail.com> ### perfnow = (global) -> # make sure we have an object to work with global.performance = {} unless "performance" of global perf = global.performance # handle vendor prefixing global.performance.now = perf.now or perf.mozNow or perf.msNow or perf.oNow or perf.webkitNow or Date.now or -> # fallback to Date new Date().getTime() perfnow self
45688
###* @file perfnow is a 0.1 kb global.performance.now high resolution timer polyfill with Date fallback @author <NAME> <<EMAIL>> ### perfnow = (global) -> # make sure we have an object to work with global.performance = {} unless "performance" of global perf = global.performance # handle vendor prefixing global.performance.now = perf.now or perf.mozNow or perf.msNow or perf.oNow or perf.webkitNow or Date.now or -> # fallback to Date new Date().getTime() perfnow self
true
###* @file perfnow is a 0.1 kb global.performance.now high resolution timer polyfill with Date fallback @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### perfnow = (global) -> # make sure we have an object to work with global.performance = {} unless "performance" of global perf = global.performance # handle vendor prefixing global.performance.now = perf.now or perf.mozNow or perf.msNow or perf.oNow or perf.webkitNow or Date.now or -> # fallback to Date new Date().getTime() perfnow self
[ { "context": "d Slow':\n author: 'Daniel Kahneman'\n publisher: 'Farr", "end": 338, "score": 0.9998920559883118, "start": 323, "tag": "NAME", "value": "Daniel Kahneman" }, { "context": "eality':\n author: 'Max Tegmark'\n publisher: 'Knop", "end": 637, "score": 0.9998965263366699, "start": 626, "tag": "NAME", "value": "Max Tegmark" }, { "context": "wabian':\n author: 'A. Douglas Stone'\n publisher: 'Prin", "end": 953, "score": 0.999880850315094, "start": 937, "tag": "NAME", "value": "A. Douglas Stone" }, { "context": "hysics':\n author: 'Leonard Susskind'\n publisher: 'Basi", "end": 1241, "score": 0.9998865723609924, "start": 1225, "tag": "NAME", "value": "Leonard Susskind" }, { "context": "tranger':\n auhtor:'Albert Camus'\n publisher: 'Gall", "end": 1597, "score": 0.9998679161071777, "start": 1585, "tag": "NAME", "value": "Albert Camus" }, { "context": "z Swann':\n author:'Marcel Proust'\n Publisher: 'Gall", "end": 1817, "score": 0.9998847842216492, "start": 1804, "tag": "NAME", "value": "Marcel Proust" }, { "context": "Fashion':\n author:'Anna Reynolds'\n publisher: 'Roya", "end": 2491, "score": 0.9998818039894104, "start": 2478, "tag": "NAME", "value": "Anna Reynolds" }, { "context": " World':\n author: 'Edward Dolnick'\n publisher: 'Harp", "end": 2792, "score": 0.9998518824577332, "start": 2778, "tag": "NAME", "value": "Edward Dolnick" }, { "context": "9-1814':\n auhtor: 'Rory Muir'\n publisher: 'Yale", "end": 3120, "score": 0.999833881855011, "start": 3111, "tag": "NAME", "value": "Rory Muir" }, { "context": "9-1848':\n author: 'Eric Hobsbawm'\n publisher: 'Vint", "end": 3364, "score": 0.9998943209648132, "start": 3351, "tag": "NAME", "value": "Eric Hobsbawm" }, { "context": " Books:\n 'Killing Lincoln: The Shocking Assassination that Changed America ", "end": 3618, "score": 0.9994120597839355, "start": 3603, "tag": "NAME", "value": "Killing Lincoln" }, { "context": "Forever':\n author:'Bill O\\'Reilly'\n publisher: 'Henr", "end": 3732, "score": 0.9998639225959778, "start": 3718, "tag": "NAME", "value": "Bill O\\'Reilly" }, { "context": "vasion':\n auhtor: 'Allen C. Guelzo'\n publisher: 'Knop", "end": 3985, "score": 0.999872088432312, "start": 3970, "tag": "NAME", "value": "Allen C. Guelzo" }, { "context": "l Life':\n author: 'Steven Englund'\n publisher: 'Harv", "end": 4204, "score": 0.9998810887336731, "start": 4190, "tag": "NAME", "value": "Steven Englund" } ]
general/locco/workflow.spec.coffee
DrJekyllandMrHyde/chocolate
41
unless window? Workflow = require '../../general/locco/workflow' librarySpace = Categories: Science: Collections: Mathematics: Books: 'Thinking, Fast and Slow': author: 'Daniel Kahneman' publisher: 'Farrar, Straus and Giroux; Reprint edition' date: 'April 2, 2013' 'Our Mathematical Universe: My Quest for the Ultimate Nature of Reality': author: 'Max Tegmark' publisher: 'Knopf' date: 'January 7, 2014' Physics: Books: 'Einstein and the Quantum: The Quest of the Valiant Swabian': author: 'A. Douglas Stone' publisher: 'Princeton University Press' date: 'October 6, 2013' 'The Theoretical Minimum: What You Need to Know to Start Doing Physics': author: 'Leonard Susskind' publisher: 'Basic Books' date: 'January 29, 2013' Literature: Collections: French: Books: 'L\'étranger': auhtor:'Albert Camus' publisher: 'Gallimard' date: 'December 1, 1971' 'Du Cote de Chez Swann': author:'Marcel Proust' Publisher: 'Gallimard Education' date: 'March 1, 1988' German: Books: 'Das Schloß': auhtor:'Franz Kafka' Publisher: 'CreateSpace Independent Publishing Platform' date: 'February 20, 2013' History: Collections: '17th century': Books: 'In Fine Style: The Art of Tudor and Stuart Fashion': author:'Anna Reynolds' publisher: 'Royal Collection Trust' date: 'June 15, 2013' 'The Clockwork Universe: Isaac Newton, the Royal Society, and the Birth of the Modern World': author: 'Edward Dolnick' publisher: 'Harper Perennial; Reprint edition' date: 'February 7, 2012' '18th century': Books: 'Wellington: The Path to Victory 1769-1814': auhtor: 'Rory Muir' publisher: 'Yale University Press' date: 'December 3, 2013' 'The Age of Revolution: 1789-1848': author: 'Eric Hobsbawm' publisher: 'Vintage; 1st Vintage Books ed edition' date: 'November 26, 1996' '19th century': Books: 'Killing Lincoln: The Shocking Assassination that Changed America Forever': author:'Bill O\'Reilly' publisher: 'Henry Holt and Co.; 1 edition' date: 'September 27, 2011' 'Gettysburg: The Last Invasion': auhtor: 'Allen C. Guelzo' publisher: 'Knopf' date: 'May 14, 2013' 'Napoleon: A Political Life': author: 'Steven Englund' publisher: 'Harvard niversity Press' date: 'May 30, 2005' describe 'Workflow', -> describe 'Action', -> Action = Workflow.Action action = undefined it 'should create a Action', -> expect(action = new Action()).not.toBeUndefined() it 'should get back full libray', -> action.go 'Categories', action.go.Where.Inside expect(action.actions.length).toBe(1)
2779
unless window? Workflow = require '../../general/locco/workflow' librarySpace = Categories: Science: Collections: Mathematics: Books: 'Thinking, Fast and Slow': author: '<NAME>' publisher: 'Farrar, Straus and Giroux; Reprint edition' date: 'April 2, 2013' 'Our Mathematical Universe: My Quest for the Ultimate Nature of Reality': author: '<NAME>' publisher: 'Knopf' date: 'January 7, 2014' Physics: Books: 'Einstein and the Quantum: The Quest of the Valiant Swabian': author: '<NAME>' publisher: 'Princeton University Press' date: 'October 6, 2013' 'The Theoretical Minimum: What You Need to Know to Start Doing Physics': author: '<NAME>' publisher: 'Basic Books' date: 'January 29, 2013' Literature: Collections: French: Books: 'L\'étranger': auhtor:'<NAME>' publisher: 'Gallimard' date: 'December 1, 1971' 'Du Cote de Chez Swann': author:'<NAME>' Publisher: 'Gallimard Education' date: 'March 1, 1988' German: Books: 'Das Schloß': auhtor:'Franz Kafka' Publisher: 'CreateSpace Independent Publishing Platform' date: 'February 20, 2013' History: Collections: '17th century': Books: 'In Fine Style: The Art of Tudor and Stuart Fashion': author:'<NAME>' publisher: 'Royal Collection Trust' date: 'June 15, 2013' 'The Clockwork Universe: Isaac Newton, the Royal Society, and the Birth of the Modern World': author: '<NAME>' publisher: 'Harper Perennial; Reprint edition' date: 'February 7, 2012' '18th century': Books: 'Wellington: The Path to Victory 1769-1814': auhtor: '<NAME>' publisher: 'Yale University Press' date: 'December 3, 2013' 'The Age of Revolution: 1789-1848': author: '<NAME>' publisher: 'Vintage; 1st Vintage Books ed edition' date: 'November 26, 1996' '19th century': Books: '<NAME>: The Shocking Assassination that Changed America Forever': author:'<NAME>' publisher: 'Henry Holt and Co.; 1 edition' date: 'September 27, 2011' 'Gettysburg: The Last Invasion': auhtor: '<NAME>' publisher: 'Knopf' date: 'May 14, 2013' 'Napoleon: A Political Life': author: '<NAME>' publisher: 'Harvard niversity Press' date: 'May 30, 2005' describe 'Workflow', -> describe 'Action', -> Action = Workflow.Action action = undefined it 'should create a Action', -> expect(action = new Action()).not.toBeUndefined() it 'should get back full libray', -> action.go 'Categories', action.go.Where.Inside expect(action.actions.length).toBe(1)
true
unless window? Workflow = require '../../general/locco/workflow' librarySpace = Categories: Science: Collections: Mathematics: Books: 'Thinking, Fast and Slow': author: 'PI:NAME:<NAME>END_PI' publisher: 'Farrar, Straus and Giroux; Reprint edition' date: 'April 2, 2013' 'Our Mathematical Universe: My Quest for the Ultimate Nature of Reality': author: 'PI:NAME:<NAME>END_PI' publisher: 'Knopf' date: 'January 7, 2014' Physics: Books: 'Einstein and the Quantum: The Quest of the Valiant Swabian': author: 'PI:NAME:<NAME>END_PI' publisher: 'Princeton University Press' date: 'October 6, 2013' 'The Theoretical Minimum: What You Need to Know to Start Doing Physics': author: 'PI:NAME:<NAME>END_PI' publisher: 'Basic Books' date: 'January 29, 2013' Literature: Collections: French: Books: 'L\'étranger': auhtor:'PI:NAME:<NAME>END_PI' publisher: 'Gallimard' date: 'December 1, 1971' 'Du Cote de Chez Swann': author:'PI:NAME:<NAME>END_PI' Publisher: 'Gallimard Education' date: 'March 1, 1988' German: Books: 'Das Schloß': auhtor:'Franz Kafka' Publisher: 'CreateSpace Independent Publishing Platform' date: 'February 20, 2013' History: Collections: '17th century': Books: 'In Fine Style: The Art of Tudor and Stuart Fashion': author:'PI:NAME:<NAME>END_PI' publisher: 'Royal Collection Trust' date: 'June 15, 2013' 'The Clockwork Universe: Isaac Newton, the Royal Society, and the Birth of the Modern World': author: 'PI:NAME:<NAME>END_PI' publisher: 'Harper Perennial; Reprint edition' date: 'February 7, 2012' '18th century': Books: 'Wellington: The Path to Victory 1769-1814': auhtor: 'PI:NAME:<NAME>END_PI' publisher: 'Yale University Press' date: 'December 3, 2013' 'The Age of Revolution: 1789-1848': author: 'PI:NAME:<NAME>END_PI' publisher: 'Vintage; 1st Vintage Books ed edition' date: 'November 26, 1996' '19th century': Books: 'PI:NAME:<NAME>END_PI: The Shocking Assassination that Changed America Forever': author:'PI:NAME:<NAME>END_PI' publisher: 'Henry Holt and Co.; 1 edition' date: 'September 27, 2011' 'Gettysburg: The Last Invasion': auhtor: 'PI:NAME:<NAME>END_PI' publisher: 'Knopf' date: 'May 14, 2013' 'Napoleon: A Political Life': author: 'PI:NAME:<NAME>END_PI' publisher: 'Harvard niversity Press' date: 'May 30, 2005' describe 'Workflow', -> describe 'Action', -> Action = Workflow.Action action = undefined it 'should create a Action', -> expect(action = new Action()).not.toBeUndefined() it 'should get back full libray', -> action.go 'Categories', action.go.Where.Inside expect(action.actions.length).toBe(1)
[ { "context": ".test(fieldName)\n key = rowName.replace('▲','') \n {指标名称, 单位} = rowObject\n ", "end": 531, "score": 0.575004518032074, "start": 530, "tag": "KEY", "value": "▲" } ]
analyze/indicator.coffee
Tostig0916/hqcoffee
2
{JSONUtils} = require './jsonUtils' # 仅用于建水县人民医院国考填报数据表测试,通用的class 见 dimension.coffee class SimpleIndicator # 一个指标object仅含一年的一个数值,符合一物一用原则 @fromJSONData: (funcOpts={}) -> jsonizedData = JSONUtils.getJSON(funcOpts) histdata = new HistoricData() # sheetName 是单位名,例如"医院",或"普外科" # rowName 是指标名称,json是指标内容 for sheetName, table of jsonizedData for rowName, rowObject of table for fieldName, value of rowObject when /(?:(?:20|21)\d{2})年/g.test(fieldName) key = rowName.replace('▲','') {指标名称, 单位} = rowObject #console.log key, rowObject 数值 = if /^比值/.test(单位) then eval(value) else value indicator = new this({指标名称,单位,数值}) histdata.updateRecord({year:fieldName,sheetName,key,indicator}) # json 只是用来查看和纠错的, instance objects 则应每次从原始文件生成 {folder, basename, needToRewrite} = funcOpts JSONUtils.write2JSON({folder, basename:"#{basename}Hist", needToRewrite, obj: histdata}) return histdata constructor: (funcOpts={}) -> {@指标名称, @单位, @数值} = funcOpts if indicatorDef? {@计量单位, @指标导向, @指标来源, @指标属性, @二级指标, @一级指标} = indicatorDef class HistoricData constructor: (funcOpts={}) -> @records = {} @years = [] @units = [] # year: e.g. '2020年' # sheetName e.g. '医院','心内科' newRecord: (funcOpts={}) -> {year, sheetName, key, indicator,update=false} = funcOpts @years.push(year) unless year in @years @units.push(sheetName) unless sheetName in @units @records[year] ?= {} @records[year][sheetName] ?= {} if update @records[year][sheetName][key] = indicator else @records[year][sheetName][key] ?= indicator addRecord: (funcOpts={}) -> funcOpts.update = false @newRecord(funcOpts) updateRecord: (funcOpts={}) -> funcOpts.update = true @newRecord(funcOpts) ### year: e.g. '2020年' addTable: (funcOpts={}) -> {year, table} = funcOpts @records[year] ?= table ### description: -> @records yearsSorted: (funcOpts=(a,b)-> a - b) -> @years.sort(funcOpts) # (key for key, value of @records).sort(funcOpts) unitsSorted: (funcOpts=(a,b)-> a - b) -> @units.sort(funcOpts) module.exports = { SimpleIndicator }
147851
{JSONUtils} = require './jsonUtils' # 仅用于建水县人民医院国考填报数据表测试,通用的class 见 dimension.coffee class SimpleIndicator # 一个指标object仅含一年的一个数值,符合一物一用原则 @fromJSONData: (funcOpts={}) -> jsonizedData = JSONUtils.getJSON(funcOpts) histdata = new HistoricData() # sheetName 是单位名,例如"医院",或"普外科" # rowName 是指标名称,json是指标内容 for sheetName, table of jsonizedData for rowName, rowObject of table for fieldName, value of rowObject when /(?:(?:20|21)\d{2})年/g.test(fieldName) key = rowName.replace('<KEY>','') {指标名称, 单位} = rowObject #console.log key, rowObject 数值 = if /^比值/.test(单位) then eval(value) else value indicator = new this({指标名称,单位,数值}) histdata.updateRecord({year:fieldName,sheetName,key,indicator}) # json 只是用来查看和纠错的, instance objects 则应每次从原始文件生成 {folder, basename, needToRewrite} = funcOpts JSONUtils.write2JSON({folder, basename:"#{basename}Hist", needToRewrite, obj: histdata}) return histdata constructor: (funcOpts={}) -> {@指标名称, @单位, @数值} = funcOpts if indicatorDef? {@计量单位, @指标导向, @指标来源, @指标属性, @二级指标, @一级指标} = indicatorDef class HistoricData constructor: (funcOpts={}) -> @records = {} @years = [] @units = [] # year: e.g. '2020年' # sheetName e.g. '医院','心内科' newRecord: (funcOpts={}) -> {year, sheetName, key, indicator,update=false} = funcOpts @years.push(year) unless year in @years @units.push(sheetName) unless sheetName in @units @records[year] ?= {} @records[year][sheetName] ?= {} if update @records[year][sheetName][key] = indicator else @records[year][sheetName][key] ?= indicator addRecord: (funcOpts={}) -> funcOpts.update = false @newRecord(funcOpts) updateRecord: (funcOpts={}) -> funcOpts.update = true @newRecord(funcOpts) ### year: e.g. '2020年' addTable: (funcOpts={}) -> {year, table} = funcOpts @records[year] ?= table ### description: -> @records yearsSorted: (funcOpts=(a,b)-> a - b) -> @years.sort(funcOpts) # (key for key, value of @records).sort(funcOpts) unitsSorted: (funcOpts=(a,b)-> a - b) -> @units.sort(funcOpts) module.exports = { SimpleIndicator }
true
{JSONUtils} = require './jsonUtils' # 仅用于建水县人民医院国考填报数据表测试,通用的class 见 dimension.coffee class SimpleIndicator # 一个指标object仅含一年的一个数值,符合一物一用原则 @fromJSONData: (funcOpts={}) -> jsonizedData = JSONUtils.getJSON(funcOpts) histdata = new HistoricData() # sheetName 是单位名,例如"医院",或"普外科" # rowName 是指标名称,json是指标内容 for sheetName, table of jsonizedData for rowName, rowObject of table for fieldName, value of rowObject when /(?:(?:20|21)\d{2})年/g.test(fieldName) key = rowName.replace('PI:KEY:<KEY>END_PI','') {指标名称, 单位} = rowObject #console.log key, rowObject 数值 = if /^比值/.test(单位) then eval(value) else value indicator = new this({指标名称,单位,数值}) histdata.updateRecord({year:fieldName,sheetName,key,indicator}) # json 只是用来查看和纠错的, instance objects 则应每次从原始文件生成 {folder, basename, needToRewrite} = funcOpts JSONUtils.write2JSON({folder, basename:"#{basename}Hist", needToRewrite, obj: histdata}) return histdata constructor: (funcOpts={}) -> {@指标名称, @单位, @数值} = funcOpts if indicatorDef? {@计量单位, @指标导向, @指标来源, @指标属性, @二级指标, @一级指标} = indicatorDef class HistoricData constructor: (funcOpts={}) -> @records = {} @years = [] @units = [] # year: e.g. '2020年' # sheetName e.g. '医院','心内科' newRecord: (funcOpts={}) -> {year, sheetName, key, indicator,update=false} = funcOpts @years.push(year) unless year in @years @units.push(sheetName) unless sheetName in @units @records[year] ?= {} @records[year][sheetName] ?= {} if update @records[year][sheetName][key] = indicator else @records[year][sheetName][key] ?= indicator addRecord: (funcOpts={}) -> funcOpts.update = false @newRecord(funcOpts) updateRecord: (funcOpts={}) -> funcOpts.update = true @newRecord(funcOpts) ### year: e.g. '2020年' addTable: (funcOpts={}) -> {year, table} = funcOpts @records[year] ?= table ### description: -> @records yearsSorted: (funcOpts=(a,b)-> a - b) -> @years.sort(funcOpts) # (key for key, value of @records).sort(funcOpts) unitsSorted: (funcOpts=(a,b)-> a - b) -> @units.sort(funcOpts) module.exports = { SimpleIndicator }
[ { "context": "ll\n finished = false\n options.server ?= \"http://127.0.0.1:#{PORT}\"\n options.level ?= 'info'\n new Dredd(op", "end": 755, "score": 0.9996839165687561, "start": 746, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " ->\n res.json [type: 'bulldozer', name: 'willy']\n\n server = app.listen PORT, () ->\n ", "end": 2292, "score": 0.560684859752655, "start": 2289, "tag": "NAME", "value": "wil" }, { "context": "'\n custom:\n apiaryApiUrl: \"http://127.0.0.1:#{PORT + 1}\"\n apiaryApiKey: 'the-key'\n ", "end": 3557, "score": 0.9975283741950989, "start": 3548, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "eporterEnv:\n APIARY_API_URL: \"http://127.0.0.1:#{PORT + 1}\"\n\n apiary = express()\n\n ", "end": 7205, "score": 0.9996845722198486, "start": 7196, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "eporterEnv:\n APIARY_API_URL: \"http://127.0.0.1:#{PORT + 1}\"\n\n apiary = express()\n ", "end": 8846, "score": 0.9996633529663086, "start": 8837, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "ound = null\n\n errorCmd =\n server: \"http://127.0.0.1:#{PORT + 1}\"\n options:\n path: [\"http:", "end": 10909, "score": 0.9977591037750244, "start": 10900, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "{PORT + 1}\"\n options:\n path: [\"http://127.0.0.1:#{PORT + 1}/connection-error.apib\"]\n\n wrongCmd", "end": 10970, "score": 0.8439592123031616, "start": 10961, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " wrongCmd =\n options:\n path: [\"http://127.0.0.1:#{PORT}/not-found.apib\"]\n\n goodCmd =\n opt", "end": 11070, "score": 0.9984227418899536, "start": 11061, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " goodCmd =\n options:\n path: [\"http://127.0.0.1:#{PORT}/file.apib\"]\n\n afterEach ->\n conne", "end": 11158, "score": 0.9716441631317139, "start": 11149, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "rue\n res.json [type: 'bulldozer', name: 'willy']\n\n server = app.listen PORT, () ->\n ", "end": 14103, "score": 0.9986514449119568, "start": 14098, "tag": "NAME", "value": "willy" }, { "context": "rue\n res.json [type: 'bulldozer', name: 'willy']\n\n server = app.listen PORT, () ->\n ", "end": 15307, "score": 0.9981997013092041, "start": 15302, "tag": "NAME", "value": "willy" }, { "context": "rue\n res.json [type: 'bulldozer', name: 'willy']\n\n server = app.listen PORT, () ->\n ", "end": 16666, "score": 0.5522585511207581, "start": 16663, "tag": "NAME", "value": "wil" } ]
test/integration/dredd-test.coffee
KissPeter/dredd
1
{assert} = require 'chai' sinon = require 'sinon' express = require 'express' clone = require 'clone' fs = require 'fs' bodyParser = require 'body-parser' proxyquire = require('proxyquire').noCallThru() loggerStub = require '../../src/logger' PORT = 9876 exitStatus = null stderr = '' stdout = '' addHooksStub = proxyquire '../../src/add-hooks', { './logger': loggerStub } transactionRunner = proxyquire '../../src/transaction-runner', { './add-hooks': addHooksStub './logger': loggerStub } Dredd = proxyquire '../../src/dredd', { './transaction-runner': transactionRunner './logger': loggerStub } execCommand = (options = {}, cb) -> stdout = '' stderr = '' exitStatus = null finished = false options.server ?= "http://127.0.0.1:#{PORT}" options.level ?= 'info' new Dredd(options).run (error, stats = {}) -> if not finished finished = true if error?.message stderr += error.message exitStatus = if (error or (1 * stats.failures + 1 * stats.errors) > 0) then 1 else 0 cb null, stdout, stderr, exitStatus return describe 'Dredd class Integration', -> dreddCommand = null custom = {} before -> for method in ['warn', 'error'] then do (method) -> sinon.stub(loggerStub, method).callsFake (chunk) -> stderr += "\n#{method}: #{chunk}" for method in ['log', 'info', 'silly', 'verbose', 'test', 'hook', 'complete', 'pass', 'skip', 'debug', 'fail', 'request', 'expected', 'actual'] then do (method) -> sinon.stub(loggerStub, method).callsFake (chunk) -> stdout += "\n#{method}: #{chunk}" return after -> for method in ['warn', 'error'] loggerStub[method].restore() for method in ['log', 'info', 'silly', 'verbose', 'test', 'hook', 'complete', 'pass', 'skip', 'debug', 'fail', 'request', 'expected', 'actual'] loggerStub[method].restore() return describe "when creating Dredd instance with existing API description document and responding server", () -> describe "when the server is responding as specified in the API description", () -> before (done) -> cmd = options: path: "./test/fixtures/single-get.apib" app = express() app.get '/machines', (req, res) -> res.json [type: 'bulldozer', name: 'willy'] server = app.listen PORT, () -> execCommand cmd, -> server.close() server.on 'close', done it 'exit status should be 0', () -> assert.equal exitStatus, 0 describe "when the server is sending different response", () -> before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib"] app = express() app.get '/machines', (req, res) -> res.status(201).json [kind: 'bulldozer', imatriculation: 'willy'] server = app.listen PORT, () -> execCommand cmd, () -> server.close() server.on 'close', done it 'exit status should be 1', () -> assert.equal exitStatus, 1 describe "when using reporter -r apiary with 'verbose' logging with custom apiaryApiKey and apiaryApiName", () -> server = null server2 = null receivedRequest = null receivedRequestTestRuns = null receivedHeaders = null receivedHeadersRuns = null exitStatus = null before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib"] reporter: ["apiary"] level: 'verbose' custom: apiaryApiUrl: "http://127.0.0.1:#{PORT + 1}" apiaryApiKey: 'the-key' apiaryApiName: 'the-api-name' receivedHeaders = {} receivedHeadersRuns = {} apiary = express() app = express() apiary.use bodyParser.json(size:'5mb') apiary.post '/apis/*', (req, res) -> if req.body and req.url.indexOf('/tests/steps') > -1 receivedRequest ?= clone(req.body) receivedHeaders[key.toLowerCase()] = val for key, val of req.headers if req.body and req.url.indexOf('/tests/runs') > -1 receivedRequestTestRuns ?= clone(req.body) receivedHeadersRuns[key.toLowerCase()] = val for key, val of req.headers res.status(201).json _id: '1234_id' testRunId: '6789_testRunId' reportUrl: 'http://url.me/test/run/1234_id' apiary.all '*', (req, res) -> res.json {} app.get '/machines', (req, res) -> res.json [type: 'bulldozer', name: 'willy'] server = app.listen PORT, () -> server2 = apiary.listen (PORT + 1), -> execCommand cmd, () -> server2.close -> server.close () -> done() it 'should not print warning about missing Apiary API settings', -> assert.notInclude stderr, 'Apiary API Key or API Project Subdomain were not provided.' it 'should contain Authentication header thanks to apiaryApiKey and apiaryApiName configuration', -> assert.propertyVal receivedHeaders, 'authentication', 'Token the-key' assert.propertyVal receivedHeadersRuns, 'authentication', 'Token the-key' it 'should send the test-run as a non-public one', -> assert.isObject receivedRequestTestRuns assert.propertyVal receivedRequestTestRuns, 'public', false it 'should print using the new reporter', -> assert.include stdout, 'http://url.me/test/run/1234_id' it 'should send results from Gavel', -> assert.isObject receivedRequest assert.nestedProperty receivedRequest, 'resultData.request' assert.nestedProperty receivedRequest, 'resultData.realResponse' assert.nestedProperty receivedRequest, 'resultData.expectedResponse' assert.nestedProperty receivedRequest, 'resultData.result.body.validator' assert.nestedProperty receivedRequest, 'resultData.result.headers.validator' assert.nestedProperty receivedRequest, 'resultData.result.statusCode.validator' it 'prints out an error message', -> assert.notEqual exitStatus, 0 describe "when called with arguments", () -> describe '--path argument is a string', -> before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib", './test/fixtures/single-get.apib'] app = express() app.get '/machines', (req, res) -> response = [type: 'bulldozer', name: 'willy'] res.json response server = app.listen PORT, () -> execCommand cmd, (error, stdOut, stdErr, code) -> err = stdErr out = stdOut exitCode = code server.close() server.on 'close', done it 'prints out ok', -> assert.equal exitStatus, 0 describe "when using reporter -r apiary and the server isn't running", () -> server = null server2 = null receivedRequest = null exitStatus = null before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib"] reporter: ['apiary'] level: 'verbose' custom: apiaryReporterEnv: APIARY_API_URL: "http://127.0.0.1:#{PORT + 1}" apiary = express() apiary.use bodyParser.json(size:'5mb') apiary.post '/apis/*', (req, res) -> if req.body and req.url.indexOf('/tests/steps') > -1 receivedRequest ?= clone(req.body) res.status(201).json _id: '1234_id' testRunId: '6789_testRunId' reportUrl: 'http://url.me/test/run/1234_id' apiary.all '*', (req, res) -> res.json {} server2 = apiary.listen (PORT + 1), -> execCommand cmd, () -> server2.close -> server2.on 'close', done it 'should print using the reporter', () -> assert.include stdout, 'http://url.me/test/run/1234_id' it 'should send results from gavel', () -> assert.isObject receivedRequest assert.nestedProperty receivedRequest, 'resultData.request' assert.nestedProperty receivedRequest, 'resultData.expectedResponse' assert.nestedProperty receivedRequest, 'resultData.result.general' it 'report should have message about server being down', () -> message = receivedRequest['resultData']['result']['general'][0]['message'] assert.include message, 'connect' describe "when using reporter -r apiary", () -> server = null server2 = null receivedRequest = null exitStatus = null before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib"] reporter: ['apiary'] level: 'verbose' custom: apiaryReporterEnv: APIARY_API_URL: "http://127.0.0.1:#{PORT + 1}" apiary = express() app = express() apiary.use bodyParser.json(size:'5mb') apiary.post '/apis/*', (req, res) -> if req.body and req.url.indexOf('/tests/steps') > -1 receivedRequest ?= clone(req.body) res.status(201).json _id: '1234_id' testRunId: '6789_testRunId' reportUrl: 'http://url.me/test/run/1234_id' apiary.all '*', (req, res) -> res.json {} app.get '/machines', (req, res) -> res.json [type: 'bulldozer', name: 'willy'] server = app.listen PORT, () -> server2 = apiary.listen (PORT + 1), -> execCommand cmd, () -> server2.close -> server.close -> server.on 'close', done it 'should print warning about missing Apiary API settings', -> assert.include stderr, 'Apiary API Key or API Project Subdomain were not provided.' it 'should print link to documentation', -> assert.include stderr, 'https://dredd.readthedocs.io/en/latest/how-to-guides/#using-apiary-reporter-and-apiary-tests' it 'should print using the new reporter', -> assert.include stdout, 'http://url.me/test/run/1234_id' it 'should send results from Gavel', -> assert.isObject receivedRequest assert.nestedProperty receivedRequest, 'resultData.request' assert.nestedProperty receivedRequest, 'resultData.realResponse' assert.nestedProperty receivedRequest, 'resultData.expectedResponse' assert.nestedProperty receivedRequest, 'resultData.result.body.validator' assert.nestedProperty receivedRequest, 'resultData.result.headers.validator' assert.nestedProperty receivedRequest, 'resultData.result.statusCode.validator' describe "when API description document should be loaded from 'http(s)://...' url", -> server = null loadedFromServer = null connectedToServer = null notFound = null fileFound = null errorCmd = server: "http://127.0.0.1:#{PORT + 1}" options: path: ["http://127.0.0.1:#{PORT + 1}/connection-error.apib"] wrongCmd = options: path: ["http://127.0.0.1:#{PORT}/not-found.apib"] goodCmd = options: path: ["http://127.0.0.1:#{PORT}/file.apib"] afterEach -> connectedToServer = null before (done) -> app = express() app.use (req, res, next) -> connectedToServer = true next() app.get '/', (req, res) -> res.sendStatus 404 app.get '/file.apib', (req, res) -> fileFound = true res.type('text') stream = fs.createReadStream './test/fixtures/single-get.apib' stream.pipe res app.get '/machines', (req, res) -> res.json [type: 'bulldozer', name: 'willy'] app.get '/not-found.apib', (req, res) -> notFound = true res.status(404).end() server = app.listen PORT, -> done() after (done) -> server.close -> app = null server = null done() describe 'and I try to load a file from bad hostname at all', -> before (done) -> execCommand errorCmd, -> done() after -> connectedToServer = null it 'should not send a GET to the server', -> assert.isNull connectedToServer it 'should exit with status 1', -> assert.equal exitStatus, 1 it 'should print error message to stderr', -> assert.include stderr, 'Error when loading file from URL' assert.include stderr, 'Is the provided URL correct?' assert.include stderr, 'connection-error.apib' describe 'and I try to load a file that does not exist from an existing server', -> before (done) -> execCommand wrongCmd, -> done() after -> connectedToServer = null it 'should connect to the right server', -> assert.isTrue connectedToServer it 'should send a GET to server at wrong URL', -> assert.isTrue notFound it 'should exit with status 1', -> assert.equal exitStatus, 1 it 'should print error message to stderr', -> assert.include stderr, 'Unable to load file from URL' assert.include stderr, 'responded with status code 404' assert.include stderr, 'not-found.apib' describe 'and I try to load a file that actually is there', -> before (done) -> execCommand goodCmd, -> done() it 'should send a GET to the right server', -> assert.isTrue connectedToServer it 'should send a GET to server at good URL', -> assert.isTrue fileFound it 'should exit with status 0', -> assert.equal exitStatus, 0 describe 'when i use sandbox and hookfiles option', () -> describe 'and I run a test', () -> requested = null before (done) -> cmd = options: path: "./test/fixtures/single-get.apib" sandbox: true hookfiles: './test/fixtures/sandboxed-hook.js' app = express() app.get '/machines', (req, res) -> requested = true res.json [type: 'bulldozer', name: 'willy'] server = app.listen PORT, () -> execCommand cmd, -> server.close() server.on 'close', done it 'exit status should be 1', () -> assert.equal exitStatus, 1 it 'stdout shoud contain fail message', () -> assert.include stdout, 'failed in sandboxed hook' it 'stdout shoud contain sandbox messagae', () -> assert.include stdout, 'Loading hook files in sandboxed context' it 'should perform the request', () -> assert.isTrue requested describe 'when i use sandbox and hookData option', () -> describe 'and I run a test', () -> requested = null before (done) -> cmd = hooksData: "./test/fixtures/single-get.apib": """ after('Machines > Machines collection > Get Machines', function(transaction){ transaction['fail'] = 'failed in sandboxed hook from string'; }); """ options: path: "./test/fixtures/single-get.apib" sandbox: true app = express() app.get '/machines', (req, res) -> requested = true res.json [type: 'bulldozer', name: 'willy'] server = app.listen PORT, () -> execCommand cmd, -> server.close() server.on 'close', done it 'exit status should be 1', () -> assert.equal exitStatus, 1 it 'stdout shoud contain fail message', () -> assert.include stdout, 'failed in sandboxed hook from string' it 'stdout shoud not sandbox messagae', () -> assert.notInclude stdout, 'Loading hook files in sandboxed context' it 'should perform the request', () -> assert.isTrue requested describe 'when use old buggy (#168) path with leading whitespace in hooks', () -> describe 'and I run a test', () -> requested = null before (done) -> cmd = hooksData: "hooks.js": """ before(' > Machines collection > Get Machines', function(transaction){ throw(new Error('Whitespace transaction name')); }); before('Machines collection > Get Machines', function(transaction){ throw(new Error('Fixed transaction name')); }); """ options: path: "./test/fixtures/single-get-nogroup.apib" sandbox: true app = express() app.get '/machines', (req, res) -> requested = true res.json [type: 'bulldozer', name: 'willy'] server = app.listen PORT, () -> execCommand cmd, -> server.close() server.on 'close', done it 'should execute hook with whitespaced name', () -> assert.include stderr, 'Whitespace transaction name' it 'should execute hook with fuxed name', () -> assert.include stderr, 'Fixed transaction name' describe('when Swagger document has multiple responses', -> reTransaction = /(\w+): (\w+) \/honey/g matches = undefined beforeEach((done) -> execCommand( options: path: './test/fixtures/multiple-responses.yaml' , (err) -> matches = [] matches.push(groups) while groups = reTransaction.exec(stdout) done(err) ) ) it('recognizes all 3 transactions', -> assert.equal(matches.length, 3) ) it('the transaction #1 is skipped', -> assert.equal(matches[0][1], 'skip') ) it('the transaction #2 is skipped', -> assert.equal(matches[1][1], 'skip') ) it('the transaction #3 is not skipped (status 200)', -> assert.notEqual(matches[2][1], 'skip') ) ) describe('when Swagger document has multiple responses and hooks unskip some of them', -> reTransaction = /(\w+): (\w+) \/honey/g matches = undefined beforeEach((done) -> execCommand( options: path: './test/fixtures/multiple-responses.yaml' hookfiles: './test/fixtures/swagger-multiple-responses.js' , (err) -> matches = [] matches.push(groups) while groups = reTransaction.exec(stdout) done(err) ) ) it('recognizes all 3 transactions', -> assert.equal(matches.length, 3) ) it('the transaction #1 is skipped', -> assert.equal(matches[0][1], 'skip') ) it('the transaction #2 is not skipped (unskipped in hooks)', -> assert.notEqual(matches[1][1], 'skip') ) it('the transaction #3 is not skipped (status 200)', -> assert.notEqual(matches[2][1], 'skip') ) ) describe('when using Swagger document with hooks', -> reTransactionName = /hook: (.+)/g matches = undefined beforeEach((done) -> execCommand( options: path: './test/fixtures/multiple-responses.yaml' hookfiles: './test/fixtures/swagger-transaction-names.js' , (err) -> matches = [] matches.push(groups[1]) while groups = reTransactionName.exec(stdout) done(err) ) ) it('transaction names contain status code and content type', -> assert.deepEqual(matches, [ '/honey > GET > 200 > application/json' '/honey > GET > 400 > application/json' '/honey > GET > 500 > application/json' ]) ) )
85845
{assert} = require 'chai' sinon = require 'sinon' express = require 'express' clone = require 'clone' fs = require 'fs' bodyParser = require 'body-parser' proxyquire = require('proxyquire').noCallThru() loggerStub = require '../../src/logger' PORT = 9876 exitStatus = null stderr = '' stdout = '' addHooksStub = proxyquire '../../src/add-hooks', { './logger': loggerStub } transactionRunner = proxyquire '../../src/transaction-runner', { './add-hooks': addHooksStub './logger': loggerStub } Dredd = proxyquire '../../src/dredd', { './transaction-runner': transactionRunner './logger': loggerStub } execCommand = (options = {}, cb) -> stdout = '' stderr = '' exitStatus = null finished = false options.server ?= "http://127.0.0.1:#{PORT}" options.level ?= 'info' new Dredd(options).run (error, stats = {}) -> if not finished finished = true if error?.message stderr += error.message exitStatus = if (error or (1 * stats.failures + 1 * stats.errors) > 0) then 1 else 0 cb null, stdout, stderr, exitStatus return describe 'Dredd class Integration', -> dreddCommand = null custom = {} before -> for method in ['warn', 'error'] then do (method) -> sinon.stub(loggerStub, method).callsFake (chunk) -> stderr += "\n#{method}: #{chunk}" for method in ['log', 'info', 'silly', 'verbose', 'test', 'hook', 'complete', 'pass', 'skip', 'debug', 'fail', 'request', 'expected', 'actual'] then do (method) -> sinon.stub(loggerStub, method).callsFake (chunk) -> stdout += "\n#{method}: #{chunk}" return after -> for method in ['warn', 'error'] loggerStub[method].restore() for method in ['log', 'info', 'silly', 'verbose', 'test', 'hook', 'complete', 'pass', 'skip', 'debug', 'fail', 'request', 'expected', 'actual'] loggerStub[method].restore() return describe "when creating Dredd instance with existing API description document and responding server", () -> describe "when the server is responding as specified in the API description", () -> before (done) -> cmd = options: path: "./test/fixtures/single-get.apib" app = express() app.get '/machines', (req, res) -> res.json [type: 'bulldozer', name: '<NAME>ly'] server = app.listen PORT, () -> execCommand cmd, -> server.close() server.on 'close', done it 'exit status should be 0', () -> assert.equal exitStatus, 0 describe "when the server is sending different response", () -> before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib"] app = express() app.get '/machines', (req, res) -> res.status(201).json [kind: 'bulldozer', imatriculation: 'willy'] server = app.listen PORT, () -> execCommand cmd, () -> server.close() server.on 'close', done it 'exit status should be 1', () -> assert.equal exitStatus, 1 describe "when using reporter -r apiary with 'verbose' logging with custom apiaryApiKey and apiaryApiName", () -> server = null server2 = null receivedRequest = null receivedRequestTestRuns = null receivedHeaders = null receivedHeadersRuns = null exitStatus = null before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib"] reporter: ["apiary"] level: 'verbose' custom: apiaryApiUrl: "http://127.0.0.1:#{PORT + 1}" apiaryApiKey: 'the-key' apiaryApiName: 'the-api-name' receivedHeaders = {} receivedHeadersRuns = {} apiary = express() app = express() apiary.use bodyParser.json(size:'5mb') apiary.post '/apis/*', (req, res) -> if req.body and req.url.indexOf('/tests/steps') > -1 receivedRequest ?= clone(req.body) receivedHeaders[key.toLowerCase()] = val for key, val of req.headers if req.body and req.url.indexOf('/tests/runs') > -1 receivedRequestTestRuns ?= clone(req.body) receivedHeadersRuns[key.toLowerCase()] = val for key, val of req.headers res.status(201).json _id: '1234_id' testRunId: '6789_testRunId' reportUrl: 'http://url.me/test/run/1234_id' apiary.all '*', (req, res) -> res.json {} app.get '/machines', (req, res) -> res.json [type: 'bulldozer', name: 'willy'] server = app.listen PORT, () -> server2 = apiary.listen (PORT + 1), -> execCommand cmd, () -> server2.close -> server.close () -> done() it 'should not print warning about missing Apiary API settings', -> assert.notInclude stderr, 'Apiary API Key or API Project Subdomain were not provided.' it 'should contain Authentication header thanks to apiaryApiKey and apiaryApiName configuration', -> assert.propertyVal receivedHeaders, 'authentication', 'Token the-key' assert.propertyVal receivedHeadersRuns, 'authentication', 'Token the-key' it 'should send the test-run as a non-public one', -> assert.isObject receivedRequestTestRuns assert.propertyVal receivedRequestTestRuns, 'public', false it 'should print using the new reporter', -> assert.include stdout, 'http://url.me/test/run/1234_id' it 'should send results from Gavel', -> assert.isObject receivedRequest assert.nestedProperty receivedRequest, 'resultData.request' assert.nestedProperty receivedRequest, 'resultData.realResponse' assert.nestedProperty receivedRequest, 'resultData.expectedResponse' assert.nestedProperty receivedRequest, 'resultData.result.body.validator' assert.nestedProperty receivedRequest, 'resultData.result.headers.validator' assert.nestedProperty receivedRequest, 'resultData.result.statusCode.validator' it 'prints out an error message', -> assert.notEqual exitStatus, 0 describe "when called with arguments", () -> describe '--path argument is a string', -> before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib", './test/fixtures/single-get.apib'] app = express() app.get '/machines', (req, res) -> response = [type: 'bulldozer', name: 'willy'] res.json response server = app.listen PORT, () -> execCommand cmd, (error, stdOut, stdErr, code) -> err = stdErr out = stdOut exitCode = code server.close() server.on 'close', done it 'prints out ok', -> assert.equal exitStatus, 0 describe "when using reporter -r apiary and the server isn't running", () -> server = null server2 = null receivedRequest = null exitStatus = null before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib"] reporter: ['apiary'] level: 'verbose' custom: apiaryReporterEnv: APIARY_API_URL: "http://127.0.0.1:#{PORT + 1}" apiary = express() apiary.use bodyParser.json(size:'5mb') apiary.post '/apis/*', (req, res) -> if req.body and req.url.indexOf('/tests/steps') > -1 receivedRequest ?= clone(req.body) res.status(201).json _id: '1234_id' testRunId: '6789_testRunId' reportUrl: 'http://url.me/test/run/1234_id' apiary.all '*', (req, res) -> res.json {} server2 = apiary.listen (PORT + 1), -> execCommand cmd, () -> server2.close -> server2.on 'close', done it 'should print using the reporter', () -> assert.include stdout, 'http://url.me/test/run/1234_id' it 'should send results from gavel', () -> assert.isObject receivedRequest assert.nestedProperty receivedRequest, 'resultData.request' assert.nestedProperty receivedRequest, 'resultData.expectedResponse' assert.nestedProperty receivedRequest, 'resultData.result.general' it 'report should have message about server being down', () -> message = receivedRequest['resultData']['result']['general'][0]['message'] assert.include message, 'connect' describe "when using reporter -r apiary", () -> server = null server2 = null receivedRequest = null exitStatus = null before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib"] reporter: ['apiary'] level: 'verbose' custom: apiaryReporterEnv: APIARY_API_URL: "http://127.0.0.1:#{PORT + 1}" apiary = express() app = express() apiary.use bodyParser.json(size:'5mb') apiary.post '/apis/*', (req, res) -> if req.body and req.url.indexOf('/tests/steps') > -1 receivedRequest ?= clone(req.body) res.status(201).json _id: '1234_id' testRunId: '6789_testRunId' reportUrl: 'http://url.me/test/run/1234_id' apiary.all '*', (req, res) -> res.json {} app.get '/machines', (req, res) -> res.json [type: 'bulldozer', name: 'willy'] server = app.listen PORT, () -> server2 = apiary.listen (PORT + 1), -> execCommand cmd, () -> server2.close -> server.close -> server.on 'close', done it 'should print warning about missing Apiary API settings', -> assert.include stderr, 'Apiary API Key or API Project Subdomain were not provided.' it 'should print link to documentation', -> assert.include stderr, 'https://dredd.readthedocs.io/en/latest/how-to-guides/#using-apiary-reporter-and-apiary-tests' it 'should print using the new reporter', -> assert.include stdout, 'http://url.me/test/run/1234_id' it 'should send results from Gavel', -> assert.isObject receivedRequest assert.nestedProperty receivedRequest, 'resultData.request' assert.nestedProperty receivedRequest, 'resultData.realResponse' assert.nestedProperty receivedRequest, 'resultData.expectedResponse' assert.nestedProperty receivedRequest, 'resultData.result.body.validator' assert.nestedProperty receivedRequest, 'resultData.result.headers.validator' assert.nestedProperty receivedRequest, 'resultData.result.statusCode.validator' describe "when API description document should be loaded from 'http(s)://...' url", -> server = null loadedFromServer = null connectedToServer = null notFound = null fileFound = null errorCmd = server: "http://127.0.0.1:#{PORT + 1}" options: path: ["http://127.0.0.1:#{PORT + 1}/connection-error.apib"] wrongCmd = options: path: ["http://127.0.0.1:#{PORT}/not-found.apib"] goodCmd = options: path: ["http://127.0.0.1:#{PORT}/file.apib"] afterEach -> connectedToServer = null before (done) -> app = express() app.use (req, res, next) -> connectedToServer = true next() app.get '/', (req, res) -> res.sendStatus 404 app.get '/file.apib', (req, res) -> fileFound = true res.type('text') stream = fs.createReadStream './test/fixtures/single-get.apib' stream.pipe res app.get '/machines', (req, res) -> res.json [type: 'bulldozer', name: 'willy'] app.get '/not-found.apib', (req, res) -> notFound = true res.status(404).end() server = app.listen PORT, -> done() after (done) -> server.close -> app = null server = null done() describe 'and I try to load a file from bad hostname at all', -> before (done) -> execCommand errorCmd, -> done() after -> connectedToServer = null it 'should not send a GET to the server', -> assert.isNull connectedToServer it 'should exit with status 1', -> assert.equal exitStatus, 1 it 'should print error message to stderr', -> assert.include stderr, 'Error when loading file from URL' assert.include stderr, 'Is the provided URL correct?' assert.include stderr, 'connection-error.apib' describe 'and I try to load a file that does not exist from an existing server', -> before (done) -> execCommand wrongCmd, -> done() after -> connectedToServer = null it 'should connect to the right server', -> assert.isTrue connectedToServer it 'should send a GET to server at wrong URL', -> assert.isTrue notFound it 'should exit with status 1', -> assert.equal exitStatus, 1 it 'should print error message to stderr', -> assert.include stderr, 'Unable to load file from URL' assert.include stderr, 'responded with status code 404' assert.include stderr, 'not-found.apib' describe 'and I try to load a file that actually is there', -> before (done) -> execCommand goodCmd, -> done() it 'should send a GET to the right server', -> assert.isTrue connectedToServer it 'should send a GET to server at good URL', -> assert.isTrue fileFound it 'should exit with status 0', -> assert.equal exitStatus, 0 describe 'when i use sandbox and hookfiles option', () -> describe 'and I run a test', () -> requested = null before (done) -> cmd = options: path: "./test/fixtures/single-get.apib" sandbox: true hookfiles: './test/fixtures/sandboxed-hook.js' app = express() app.get '/machines', (req, res) -> requested = true res.json [type: 'bulldozer', name: '<NAME>'] server = app.listen PORT, () -> execCommand cmd, -> server.close() server.on 'close', done it 'exit status should be 1', () -> assert.equal exitStatus, 1 it 'stdout shoud contain fail message', () -> assert.include stdout, 'failed in sandboxed hook' it 'stdout shoud contain sandbox messagae', () -> assert.include stdout, 'Loading hook files in sandboxed context' it 'should perform the request', () -> assert.isTrue requested describe 'when i use sandbox and hookData option', () -> describe 'and I run a test', () -> requested = null before (done) -> cmd = hooksData: "./test/fixtures/single-get.apib": """ after('Machines > Machines collection > Get Machines', function(transaction){ transaction['fail'] = 'failed in sandboxed hook from string'; }); """ options: path: "./test/fixtures/single-get.apib" sandbox: true app = express() app.get '/machines', (req, res) -> requested = true res.json [type: 'bulldozer', name: '<NAME>'] server = app.listen PORT, () -> execCommand cmd, -> server.close() server.on 'close', done it 'exit status should be 1', () -> assert.equal exitStatus, 1 it 'stdout shoud contain fail message', () -> assert.include stdout, 'failed in sandboxed hook from string' it 'stdout shoud not sandbox messagae', () -> assert.notInclude stdout, 'Loading hook files in sandboxed context' it 'should perform the request', () -> assert.isTrue requested describe 'when use old buggy (#168) path with leading whitespace in hooks', () -> describe 'and I run a test', () -> requested = null before (done) -> cmd = hooksData: "hooks.js": """ before(' > Machines collection > Get Machines', function(transaction){ throw(new Error('Whitespace transaction name')); }); before('Machines collection > Get Machines', function(transaction){ throw(new Error('Fixed transaction name')); }); """ options: path: "./test/fixtures/single-get-nogroup.apib" sandbox: true app = express() app.get '/machines', (req, res) -> requested = true res.json [type: 'bulldozer', name: '<NAME>ly'] server = app.listen PORT, () -> execCommand cmd, -> server.close() server.on 'close', done it 'should execute hook with whitespaced name', () -> assert.include stderr, 'Whitespace transaction name' it 'should execute hook with fuxed name', () -> assert.include stderr, 'Fixed transaction name' describe('when Swagger document has multiple responses', -> reTransaction = /(\w+): (\w+) \/honey/g matches = undefined beforeEach((done) -> execCommand( options: path: './test/fixtures/multiple-responses.yaml' , (err) -> matches = [] matches.push(groups) while groups = reTransaction.exec(stdout) done(err) ) ) it('recognizes all 3 transactions', -> assert.equal(matches.length, 3) ) it('the transaction #1 is skipped', -> assert.equal(matches[0][1], 'skip') ) it('the transaction #2 is skipped', -> assert.equal(matches[1][1], 'skip') ) it('the transaction #3 is not skipped (status 200)', -> assert.notEqual(matches[2][1], 'skip') ) ) describe('when Swagger document has multiple responses and hooks unskip some of them', -> reTransaction = /(\w+): (\w+) \/honey/g matches = undefined beforeEach((done) -> execCommand( options: path: './test/fixtures/multiple-responses.yaml' hookfiles: './test/fixtures/swagger-multiple-responses.js' , (err) -> matches = [] matches.push(groups) while groups = reTransaction.exec(stdout) done(err) ) ) it('recognizes all 3 transactions', -> assert.equal(matches.length, 3) ) it('the transaction #1 is skipped', -> assert.equal(matches[0][1], 'skip') ) it('the transaction #2 is not skipped (unskipped in hooks)', -> assert.notEqual(matches[1][1], 'skip') ) it('the transaction #3 is not skipped (status 200)', -> assert.notEqual(matches[2][1], 'skip') ) ) describe('when using Swagger document with hooks', -> reTransactionName = /hook: (.+)/g matches = undefined beforeEach((done) -> execCommand( options: path: './test/fixtures/multiple-responses.yaml' hookfiles: './test/fixtures/swagger-transaction-names.js' , (err) -> matches = [] matches.push(groups[1]) while groups = reTransactionName.exec(stdout) done(err) ) ) it('transaction names contain status code and content type', -> assert.deepEqual(matches, [ '/honey > GET > 200 > application/json' '/honey > GET > 400 > application/json' '/honey > GET > 500 > application/json' ]) ) )
true
{assert} = require 'chai' sinon = require 'sinon' express = require 'express' clone = require 'clone' fs = require 'fs' bodyParser = require 'body-parser' proxyquire = require('proxyquire').noCallThru() loggerStub = require '../../src/logger' PORT = 9876 exitStatus = null stderr = '' stdout = '' addHooksStub = proxyquire '../../src/add-hooks', { './logger': loggerStub } transactionRunner = proxyquire '../../src/transaction-runner', { './add-hooks': addHooksStub './logger': loggerStub } Dredd = proxyquire '../../src/dredd', { './transaction-runner': transactionRunner './logger': loggerStub } execCommand = (options = {}, cb) -> stdout = '' stderr = '' exitStatus = null finished = false options.server ?= "http://127.0.0.1:#{PORT}" options.level ?= 'info' new Dredd(options).run (error, stats = {}) -> if not finished finished = true if error?.message stderr += error.message exitStatus = if (error or (1 * stats.failures + 1 * stats.errors) > 0) then 1 else 0 cb null, stdout, stderr, exitStatus return describe 'Dredd class Integration', -> dreddCommand = null custom = {} before -> for method in ['warn', 'error'] then do (method) -> sinon.stub(loggerStub, method).callsFake (chunk) -> stderr += "\n#{method}: #{chunk}" for method in ['log', 'info', 'silly', 'verbose', 'test', 'hook', 'complete', 'pass', 'skip', 'debug', 'fail', 'request', 'expected', 'actual'] then do (method) -> sinon.stub(loggerStub, method).callsFake (chunk) -> stdout += "\n#{method}: #{chunk}" return after -> for method in ['warn', 'error'] loggerStub[method].restore() for method in ['log', 'info', 'silly', 'verbose', 'test', 'hook', 'complete', 'pass', 'skip', 'debug', 'fail', 'request', 'expected', 'actual'] loggerStub[method].restore() return describe "when creating Dredd instance with existing API description document and responding server", () -> describe "when the server is responding as specified in the API description", () -> before (done) -> cmd = options: path: "./test/fixtures/single-get.apib" app = express() app.get '/machines', (req, res) -> res.json [type: 'bulldozer', name: 'PI:NAME:<NAME>END_PIly'] server = app.listen PORT, () -> execCommand cmd, -> server.close() server.on 'close', done it 'exit status should be 0', () -> assert.equal exitStatus, 0 describe "when the server is sending different response", () -> before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib"] app = express() app.get '/machines', (req, res) -> res.status(201).json [kind: 'bulldozer', imatriculation: 'willy'] server = app.listen PORT, () -> execCommand cmd, () -> server.close() server.on 'close', done it 'exit status should be 1', () -> assert.equal exitStatus, 1 describe "when using reporter -r apiary with 'verbose' logging with custom apiaryApiKey and apiaryApiName", () -> server = null server2 = null receivedRequest = null receivedRequestTestRuns = null receivedHeaders = null receivedHeadersRuns = null exitStatus = null before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib"] reporter: ["apiary"] level: 'verbose' custom: apiaryApiUrl: "http://127.0.0.1:#{PORT + 1}" apiaryApiKey: 'the-key' apiaryApiName: 'the-api-name' receivedHeaders = {} receivedHeadersRuns = {} apiary = express() app = express() apiary.use bodyParser.json(size:'5mb') apiary.post '/apis/*', (req, res) -> if req.body and req.url.indexOf('/tests/steps') > -1 receivedRequest ?= clone(req.body) receivedHeaders[key.toLowerCase()] = val for key, val of req.headers if req.body and req.url.indexOf('/tests/runs') > -1 receivedRequestTestRuns ?= clone(req.body) receivedHeadersRuns[key.toLowerCase()] = val for key, val of req.headers res.status(201).json _id: '1234_id' testRunId: '6789_testRunId' reportUrl: 'http://url.me/test/run/1234_id' apiary.all '*', (req, res) -> res.json {} app.get '/machines', (req, res) -> res.json [type: 'bulldozer', name: 'willy'] server = app.listen PORT, () -> server2 = apiary.listen (PORT + 1), -> execCommand cmd, () -> server2.close -> server.close () -> done() it 'should not print warning about missing Apiary API settings', -> assert.notInclude stderr, 'Apiary API Key or API Project Subdomain were not provided.' it 'should contain Authentication header thanks to apiaryApiKey and apiaryApiName configuration', -> assert.propertyVal receivedHeaders, 'authentication', 'Token the-key' assert.propertyVal receivedHeadersRuns, 'authentication', 'Token the-key' it 'should send the test-run as a non-public one', -> assert.isObject receivedRequestTestRuns assert.propertyVal receivedRequestTestRuns, 'public', false it 'should print using the new reporter', -> assert.include stdout, 'http://url.me/test/run/1234_id' it 'should send results from Gavel', -> assert.isObject receivedRequest assert.nestedProperty receivedRequest, 'resultData.request' assert.nestedProperty receivedRequest, 'resultData.realResponse' assert.nestedProperty receivedRequest, 'resultData.expectedResponse' assert.nestedProperty receivedRequest, 'resultData.result.body.validator' assert.nestedProperty receivedRequest, 'resultData.result.headers.validator' assert.nestedProperty receivedRequest, 'resultData.result.statusCode.validator' it 'prints out an error message', -> assert.notEqual exitStatus, 0 describe "when called with arguments", () -> describe '--path argument is a string', -> before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib", './test/fixtures/single-get.apib'] app = express() app.get '/machines', (req, res) -> response = [type: 'bulldozer', name: 'willy'] res.json response server = app.listen PORT, () -> execCommand cmd, (error, stdOut, stdErr, code) -> err = stdErr out = stdOut exitCode = code server.close() server.on 'close', done it 'prints out ok', -> assert.equal exitStatus, 0 describe "when using reporter -r apiary and the server isn't running", () -> server = null server2 = null receivedRequest = null exitStatus = null before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib"] reporter: ['apiary'] level: 'verbose' custom: apiaryReporterEnv: APIARY_API_URL: "http://127.0.0.1:#{PORT + 1}" apiary = express() apiary.use bodyParser.json(size:'5mb') apiary.post '/apis/*', (req, res) -> if req.body and req.url.indexOf('/tests/steps') > -1 receivedRequest ?= clone(req.body) res.status(201).json _id: '1234_id' testRunId: '6789_testRunId' reportUrl: 'http://url.me/test/run/1234_id' apiary.all '*', (req, res) -> res.json {} server2 = apiary.listen (PORT + 1), -> execCommand cmd, () -> server2.close -> server2.on 'close', done it 'should print using the reporter', () -> assert.include stdout, 'http://url.me/test/run/1234_id' it 'should send results from gavel', () -> assert.isObject receivedRequest assert.nestedProperty receivedRequest, 'resultData.request' assert.nestedProperty receivedRequest, 'resultData.expectedResponse' assert.nestedProperty receivedRequest, 'resultData.result.general' it 'report should have message about server being down', () -> message = receivedRequest['resultData']['result']['general'][0]['message'] assert.include message, 'connect' describe "when using reporter -r apiary", () -> server = null server2 = null receivedRequest = null exitStatus = null before (done) -> cmd = options: path: ["./test/fixtures/single-get.apib"] reporter: ['apiary'] level: 'verbose' custom: apiaryReporterEnv: APIARY_API_URL: "http://127.0.0.1:#{PORT + 1}" apiary = express() app = express() apiary.use bodyParser.json(size:'5mb') apiary.post '/apis/*', (req, res) -> if req.body and req.url.indexOf('/tests/steps') > -1 receivedRequest ?= clone(req.body) res.status(201).json _id: '1234_id' testRunId: '6789_testRunId' reportUrl: 'http://url.me/test/run/1234_id' apiary.all '*', (req, res) -> res.json {} app.get '/machines', (req, res) -> res.json [type: 'bulldozer', name: 'willy'] server = app.listen PORT, () -> server2 = apiary.listen (PORT + 1), -> execCommand cmd, () -> server2.close -> server.close -> server.on 'close', done it 'should print warning about missing Apiary API settings', -> assert.include stderr, 'Apiary API Key or API Project Subdomain were not provided.' it 'should print link to documentation', -> assert.include stderr, 'https://dredd.readthedocs.io/en/latest/how-to-guides/#using-apiary-reporter-and-apiary-tests' it 'should print using the new reporter', -> assert.include stdout, 'http://url.me/test/run/1234_id' it 'should send results from Gavel', -> assert.isObject receivedRequest assert.nestedProperty receivedRequest, 'resultData.request' assert.nestedProperty receivedRequest, 'resultData.realResponse' assert.nestedProperty receivedRequest, 'resultData.expectedResponse' assert.nestedProperty receivedRequest, 'resultData.result.body.validator' assert.nestedProperty receivedRequest, 'resultData.result.headers.validator' assert.nestedProperty receivedRequest, 'resultData.result.statusCode.validator' describe "when API description document should be loaded from 'http(s)://...' url", -> server = null loadedFromServer = null connectedToServer = null notFound = null fileFound = null errorCmd = server: "http://127.0.0.1:#{PORT + 1}" options: path: ["http://127.0.0.1:#{PORT + 1}/connection-error.apib"] wrongCmd = options: path: ["http://127.0.0.1:#{PORT}/not-found.apib"] goodCmd = options: path: ["http://127.0.0.1:#{PORT}/file.apib"] afterEach -> connectedToServer = null before (done) -> app = express() app.use (req, res, next) -> connectedToServer = true next() app.get '/', (req, res) -> res.sendStatus 404 app.get '/file.apib', (req, res) -> fileFound = true res.type('text') stream = fs.createReadStream './test/fixtures/single-get.apib' stream.pipe res app.get '/machines', (req, res) -> res.json [type: 'bulldozer', name: 'willy'] app.get '/not-found.apib', (req, res) -> notFound = true res.status(404).end() server = app.listen PORT, -> done() after (done) -> server.close -> app = null server = null done() describe 'and I try to load a file from bad hostname at all', -> before (done) -> execCommand errorCmd, -> done() after -> connectedToServer = null it 'should not send a GET to the server', -> assert.isNull connectedToServer it 'should exit with status 1', -> assert.equal exitStatus, 1 it 'should print error message to stderr', -> assert.include stderr, 'Error when loading file from URL' assert.include stderr, 'Is the provided URL correct?' assert.include stderr, 'connection-error.apib' describe 'and I try to load a file that does not exist from an existing server', -> before (done) -> execCommand wrongCmd, -> done() after -> connectedToServer = null it 'should connect to the right server', -> assert.isTrue connectedToServer it 'should send a GET to server at wrong URL', -> assert.isTrue notFound it 'should exit with status 1', -> assert.equal exitStatus, 1 it 'should print error message to stderr', -> assert.include stderr, 'Unable to load file from URL' assert.include stderr, 'responded with status code 404' assert.include stderr, 'not-found.apib' describe 'and I try to load a file that actually is there', -> before (done) -> execCommand goodCmd, -> done() it 'should send a GET to the right server', -> assert.isTrue connectedToServer it 'should send a GET to server at good URL', -> assert.isTrue fileFound it 'should exit with status 0', -> assert.equal exitStatus, 0 describe 'when i use sandbox and hookfiles option', () -> describe 'and I run a test', () -> requested = null before (done) -> cmd = options: path: "./test/fixtures/single-get.apib" sandbox: true hookfiles: './test/fixtures/sandboxed-hook.js' app = express() app.get '/machines', (req, res) -> requested = true res.json [type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'] server = app.listen PORT, () -> execCommand cmd, -> server.close() server.on 'close', done it 'exit status should be 1', () -> assert.equal exitStatus, 1 it 'stdout shoud contain fail message', () -> assert.include stdout, 'failed in sandboxed hook' it 'stdout shoud contain sandbox messagae', () -> assert.include stdout, 'Loading hook files in sandboxed context' it 'should perform the request', () -> assert.isTrue requested describe 'when i use sandbox and hookData option', () -> describe 'and I run a test', () -> requested = null before (done) -> cmd = hooksData: "./test/fixtures/single-get.apib": """ after('Machines > Machines collection > Get Machines', function(transaction){ transaction['fail'] = 'failed in sandboxed hook from string'; }); """ options: path: "./test/fixtures/single-get.apib" sandbox: true app = express() app.get '/machines', (req, res) -> requested = true res.json [type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'] server = app.listen PORT, () -> execCommand cmd, -> server.close() server.on 'close', done it 'exit status should be 1', () -> assert.equal exitStatus, 1 it 'stdout shoud contain fail message', () -> assert.include stdout, 'failed in sandboxed hook from string' it 'stdout shoud not sandbox messagae', () -> assert.notInclude stdout, 'Loading hook files in sandboxed context' it 'should perform the request', () -> assert.isTrue requested describe 'when use old buggy (#168) path with leading whitespace in hooks', () -> describe 'and I run a test', () -> requested = null before (done) -> cmd = hooksData: "hooks.js": """ before(' > Machines collection > Get Machines', function(transaction){ throw(new Error('Whitespace transaction name')); }); before('Machines collection > Get Machines', function(transaction){ throw(new Error('Fixed transaction name')); }); """ options: path: "./test/fixtures/single-get-nogroup.apib" sandbox: true app = express() app.get '/machines', (req, res) -> requested = true res.json [type: 'bulldozer', name: 'PI:NAME:<NAME>END_PIly'] server = app.listen PORT, () -> execCommand cmd, -> server.close() server.on 'close', done it 'should execute hook with whitespaced name', () -> assert.include stderr, 'Whitespace transaction name' it 'should execute hook with fuxed name', () -> assert.include stderr, 'Fixed transaction name' describe('when Swagger document has multiple responses', -> reTransaction = /(\w+): (\w+) \/honey/g matches = undefined beforeEach((done) -> execCommand( options: path: './test/fixtures/multiple-responses.yaml' , (err) -> matches = [] matches.push(groups) while groups = reTransaction.exec(stdout) done(err) ) ) it('recognizes all 3 transactions', -> assert.equal(matches.length, 3) ) it('the transaction #1 is skipped', -> assert.equal(matches[0][1], 'skip') ) it('the transaction #2 is skipped', -> assert.equal(matches[1][1], 'skip') ) it('the transaction #3 is not skipped (status 200)', -> assert.notEqual(matches[2][1], 'skip') ) ) describe('when Swagger document has multiple responses and hooks unskip some of them', -> reTransaction = /(\w+): (\w+) \/honey/g matches = undefined beforeEach((done) -> execCommand( options: path: './test/fixtures/multiple-responses.yaml' hookfiles: './test/fixtures/swagger-multiple-responses.js' , (err) -> matches = [] matches.push(groups) while groups = reTransaction.exec(stdout) done(err) ) ) it('recognizes all 3 transactions', -> assert.equal(matches.length, 3) ) it('the transaction #1 is skipped', -> assert.equal(matches[0][1], 'skip') ) it('the transaction #2 is not skipped (unskipped in hooks)', -> assert.notEqual(matches[1][1], 'skip') ) it('the transaction #3 is not skipped (status 200)', -> assert.notEqual(matches[2][1], 'skip') ) ) describe('when using Swagger document with hooks', -> reTransactionName = /hook: (.+)/g matches = undefined beforeEach((done) -> execCommand( options: path: './test/fixtures/multiple-responses.yaml' hookfiles: './test/fixtures/swagger-transaction-names.js' , (err) -> matches = [] matches.push(groups[1]) while groups = reTransactionName.exec(stdout) done(err) ) ) it('transaction names contain status code and content type', -> assert.deepEqual(matches, [ '/honey > GET > 200 > application/json' '/honey > GET > 400 > application/json' '/honey > GET > 500 > application/json' ]) ) )
[ { "context": "ne-Forms chosen editor 1.0.3\n\n Copyright (c) 2017 Tomasz Jakub Rup\n\n https://github.com/tomi77/backbone-forms-chose", "end": 79, "score": 0.9998682737350464, "start": 63, "tag": "NAME", "value": "Tomasz Jakub Rup" }, { "context": "t (c) 2017 Tomasz Jakub Rup\n\n https://github.com/tomi77/backbone-forms-chosen\n\n Released under the MIT l", "end": 108, "score": 0.9996119737625122, "start": 102, "tag": "USERNAME", "value": "tomi77" } ]
src/bbf-chosen.coffee
tomi77/backbone-forms-chosen
0
### Backbone-Forms chosen editor 1.0.3 Copyright (c) 2017 Tomasz Jakub Rup https://github.com/tomi77/backbone-forms-chosen Released under the MIT license ### ((root, factory) -> ### istanbul ignore next ### switch when typeof define is 'function' and define.amd define ['backbone-forms', 'chosen'], factory when typeof exports is 'object' require('chosen-js') factory require('backbone-forms') else factory root.Backbone.Form return ) @, (Form) -> Select = Form.editors.Select Form.editors['chosen'] = Select.extend events: 'change': (event) -> @trigger('change', @) return 'chosen:showing_dropdown': (event) -> @trigger('focus', @) return 'chosen:hiding_dropdown': (event) -> @trigger('blur', @) return initialize: (options) -> Select::initialize.call @, options @editorOptions = options.schema.editorOptions or {} el = @$el @$el = Backbone.$('<div>') @el = @$el[0] @$el.html(el) return render: () -> Select::render.call @ if @editorOptions.width? @renderChosen() else setTimeout @renderChosen.bind(@), 10 @ renderChosen: () -> @$('select').chosen @editorOptions return renderOptions: (options) -> $select = @$('select') html = @_getOptionsHtml(options) # Insert options $select.html(html) # Select correct option @setValue(@value) return getValue: () -> @$('select').val() setValue: (value) -> @$('select').val(value) return return
132623
### Backbone-Forms chosen editor 1.0.3 Copyright (c) 2017 <NAME> https://github.com/tomi77/backbone-forms-chosen Released under the MIT license ### ((root, factory) -> ### istanbul ignore next ### switch when typeof define is 'function' and define.amd define ['backbone-forms', 'chosen'], factory when typeof exports is 'object' require('chosen-js') factory require('backbone-forms') else factory root.Backbone.Form return ) @, (Form) -> Select = Form.editors.Select Form.editors['chosen'] = Select.extend events: 'change': (event) -> @trigger('change', @) return 'chosen:showing_dropdown': (event) -> @trigger('focus', @) return 'chosen:hiding_dropdown': (event) -> @trigger('blur', @) return initialize: (options) -> Select::initialize.call @, options @editorOptions = options.schema.editorOptions or {} el = @$el @$el = Backbone.$('<div>') @el = @$el[0] @$el.html(el) return render: () -> Select::render.call @ if @editorOptions.width? @renderChosen() else setTimeout @renderChosen.bind(@), 10 @ renderChosen: () -> @$('select').chosen @editorOptions return renderOptions: (options) -> $select = @$('select') html = @_getOptionsHtml(options) # Insert options $select.html(html) # Select correct option @setValue(@value) return getValue: () -> @$('select').val() setValue: (value) -> @$('select').val(value) return return
true
### Backbone-Forms chosen editor 1.0.3 Copyright (c) 2017 PI:NAME:<NAME>END_PI https://github.com/tomi77/backbone-forms-chosen Released under the MIT license ### ((root, factory) -> ### istanbul ignore next ### switch when typeof define is 'function' and define.amd define ['backbone-forms', 'chosen'], factory when typeof exports is 'object' require('chosen-js') factory require('backbone-forms') else factory root.Backbone.Form return ) @, (Form) -> Select = Form.editors.Select Form.editors['chosen'] = Select.extend events: 'change': (event) -> @trigger('change', @) return 'chosen:showing_dropdown': (event) -> @trigger('focus', @) return 'chosen:hiding_dropdown': (event) -> @trigger('blur', @) return initialize: (options) -> Select::initialize.call @, options @editorOptions = options.schema.editorOptions or {} el = @$el @$el = Backbone.$('<div>') @el = @$el[0] @$el.html(el) return render: () -> Select::render.call @ if @editorOptions.width? @renderChosen() else setTimeout @renderChosen.bind(@), 10 @ renderChosen: () -> @$('select').chosen @editorOptions return renderOptions: (options) -> $select = @$('select') html = @_getOptionsHtml(options) # Insert options $select.html(html) # Select correct option @setValue(@value) return getValue: () -> @$('select').val() setValue: (value) -> @$('select').val(value) return return
[ { "context": "----------------\n\tDesenvolvido em CoffeeScript por Fabiane Lima\n\n\tLicença: https://opensource.org/licenses/MIT\n##", "end": 112, "score": 0.9999039173126221, "start": 100, "tag": "NAME", "value": "Fabiane Lima" } ]
assets/js/script.coffee
fabianelima/Manzana
0
### MANZANA v0.4 ---------------------------------------------- Desenvolvido em CoffeeScript por Fabiane Lima Licença: https://opensource.org/licenses/MIT ### # ----- Pré-carregamento das imagens ----- # imgs = [ 'assets/img/help.svg' 'assets/img/audio.svg' 'assets/img/audio-off.svg' ] preload = (imgs) -> counter = 0 $(imgs).each -> $('<img />').attr('src', this).appendTo('body').css { display: 'none' } counter++ if counter is imgs.length $('main').css { opacity: '1' } $('body').css { background: '#e7e7e7' } $(window).on 'load', -> preload(imgs) # ----- Módulos e opções ----- # $ -> sets = audio: false clickarea: false quiz: false trueORfalse: false slideshow: true dragdrop: false quizdrag: false vblocks: false audio = trilha: new Audio('assets/audio/trilha.mp3') clique: new Audio('assets/audio/clique.mp3') start: -> if sets.audio is true audio.trilha.volume = 0.6 audio.trilha.loop = true audio.trilha.play() audio.clique.play() $('.content').append('<button class="ic audio"></button>') audio: -> audio.clique.play() if sets.audio is false sets.audio = true audio.trilha.play() $('.audio').css { background: '#006c7f url(assets/img/audio.svg) no-repeat' } else if sets.audio is true sets.audio = false audio.trilha.pause() $('.audio').css { background: '#006c7f url(assets/img/audio-off.svg) no-repeat' } clickarea = pro: undefined data: [ { txt: '1. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [50, 30] stt: false } { txt: '2. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [20, 20] stt: false } { txt: '3. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [10, 30] stt: false } { txt: '4. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [30, 70] stt: false } { txt: '5. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [50, 50] stt: false }] start: -> if sets.clickarea is true $('.content').append('<div class="clickarea"></div><button class="end">Concluir</button>') for i, j in clickarea.data $('.clickarea').append('<div></div>') $('.clickarea div:nth-child(' + (j + 1) + ')').css top: clickarea.data[j].pos[0] + '%' left: clickarea.data[j].pos[1] + '%' showC: ($el) -> clickarea.data[$el.index()].stt = true $el.css { pointerEvents: 'none', opacity: '0.6' } $('.dimmer').fadeIn() $('.modal').html(clickarea.data[$el.index()].txt + '<button class="dismiss callend">Fechar</button>') callEnd: -> k = 0 for i in clickarea.data if i.stt is true k++ if k is clickarea.data.length $('.end').fadeIn() quiz = alt: undefined pro: undefined ctrl: [] count: 0 score: 0 error: 0 inOrder: 1 data: [ { titl: 'Título da questão' enun: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 0 feed: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { titl: 'Título da questão' enun: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 1 feed: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { titl: 'Título da questão' enun: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 2 feed: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } ] rNumber: -> quiz.randy = Math.floor(Math.random() * quiz.data.length) if quiz.ctrl.length < quiz.data.length if quiz.ctrl.indexOf(quiz.randy) is -1 quiz.ctrl.push quiz.randy $('.quiz').append(' <section id="' + quiz.randy + '" class="q"> <div class="enun"> <h1>' + (quiz.ctrl.indexOf(quiz.randy) + 1) + '. ' + quiz.data[quiz.randy].titl + '</h1> <p>' + quiz.data[quiz.randy].enun + '</p> </div> <div class="alts"><ul></ul></div> <button class="verify">Conferir</button> </section> ') quiz.pro = true else quiz.pro = false quiz.putAlts(quiz.randy) quiz.rNumber() start: -> if sets.quiz is true $('.content').append('<div class="quiz"></div>') quiz.rNumber() selectAlt: ($el) -> quiz.alt = $el.index() $('.verify').css { pointerEvents: 'auto', opacity: '1' } $('.alts li').css { background: 'white', color: 'black' } $el.css { background: '#006c7f', color: 'white' } verify: -> $('.dimmer').delay(500).fadeIn() $('.modal').html('<h1></h1><p>' + quiz.data[quiz.ctrl[quiz.count]].feed + '</p><button class="nxt">Prosseguir</button>') if quiz.alt is quiz.data[quiz.ctrl[quiz.count]].answ quiz.score++ $('.modal h1').html('Resposta certa!') else quiz.error++ $('.modal h1').html('Resposta errada!') nxt: -> quiz.count++ if quiz.count < quiz.data.length func.dismiss() quiz.putAlts() $('.verify').css { pointerEvents: 'none', opacity: '0.6' } $('.quiz section:nth-child(' + quiz.count + ')').fadeOut() $('.quiz section:nth-child(' + (quiz.count + 1) + ')').fadeIn() else setTimeout -> func.end() , 400 putAlts: (randy) -> testPromise = new Promise (resolve, reject) -> if quiz.pro is true then resolve() else reject() .then (fromResolve) -> for i, j in quiz.data[randy].alts $('.quiz section:nth-child(' + quiz.inOrder + ') .alts ul').append('<li>' + i + '</li>') if j is quiz.data[randy].alts.length - 1 then quiz.inOrder++ .catch (fromReject) -> return trueORfalse = count: 0 score: 0 alt: undefined data: [ { titl: 'Título da questão' text: '1. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: true feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } { titl: 'Título da questão' text: '2. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: true feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } { titl: 'Título da questão' text: '3. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: false feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } { titl: 'Título da questão' text: '4. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: false feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } { titl: 'Título da questão' text: '5. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: true feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } ] start: -> if sets.trueORfalse is true $('.content').append('<div class="t-or-f"></div>') j = 0 func.dismiss() for i in trueORfalse.data $('.t-or-f').append(' <section> <div class="txt"> <h1>' + trueORfalse.data[j].titl + '</h1> <p>' + trueORfalse.data[j].text + '</p> </div> <div class="ctrl"> <button class="true">verdadeiro</button> <button class="false">falso</button> </div> </section> ') j++ verify: ($el) -> $('.ctrl').css { pointerEvents: 'none' } if $el.attr('class') is 'true' then trueORfalse.alt = true else if $el.attr('class') is 'false' then trueORfalse.alt = false $('.dimmer').fadeIn() $('.modal').html('<h1></h1><p>' + trueORfalse.data[trueORfalse.count].feed + '</p><button class="nxt">Próxima</button>') if trueORfalse.alt is trueORfalse.data[trueORfalse.count].answ trueORfalse.score++ $('.modal h1').html('Resposta correta!') else $('.modal h1').html('Resposta errada!') nxt: -> trueORfalse.count++ if trueORfalse.count < trueORfalse.data.length func.dismiss() $('.t-or-f .ctrl').css { pointerEvents: 'auto' } $('.t-or-f section:nth-child(' + trueORfalse.count + ')').fadeOut() $('.t-or-f section:nth-child(' + (trueORfalse.count + 1) + ')').fadeIn() else setTimeout -> func.end() , 500 slideshow = count: 0 data: [ { img: 'assets/img/img1.png' txt: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' } { img: 'assets/img/img2.png' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { img: 'assets/img/img3.png' txt: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' } { img: 'assets/img/img4.png' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { img: 'assets/img/img5.png' txt: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' } ] start: -> if sets.slideshow is true $('.content').append(' <div class="slideshow"> <div class="slides"></div> <div class="ctrl"> <button class="next"></button> <button class="prev"></button> </div> </div>') for i, j in slideshow.data $('.slides').append(' <section> <div>' + slideshow.data[j].txt + '</div> <img src="' + slideshow.data[j].img + '"> </section> ') slide: ($el) -> if $el.attr('class') is 'next' slideshow.count++ $('.prev').css { pointerEvents: 'auto', opacity: '1' } if slideshow.count < slideshow.data.length $('.slides section').fadeOut() $('.slides section:nth-child(' + (slideshow.count + 1) + ')').fadeIn() else func.end() if $el.attr('class') is 'prev' slideshow.count-- $('.slides section').fadeOut() $('.slides section:nth-child(' + (slideshow.count + 1) + ')').fadeIn() if slideshow.count is 0 then $('.prev').css { pointerEvents: 'none', opacity: '0.6' } dragdrop = count: 0 ctrl: [] endit: [] data: [ [ 'draggable 1' 'draggable 2' 'draggable 3' 'draggable 4' 'draggable 5' 'draggable 6' ] [ 'draggable 1' 'draggable 2' 'draggable 3' 'draggable 4' 'draggable 5' 'draggable 6' ] ] start: -> if sets.dragdrop is true $('.content').append(' <div class="drag-drop"> <div class="draggie"></div> <div class="droppie"></div> </div>') func.dismiss() dragdrop.rNumber() for i in dragdrop.data[1] $('.droppie').append('<div>' + i + '</div>') dragdrop.draggie() dragdrop.droppie() rNumber: -> randy = Math.floor(Math.random() * dragdrop.data[0].length) if dragdrop.ctrl.length < dragdrop.data[0].length if dragdrop.ctrl.indexOf(randy) is -1 dragdrop.ctrl.push randy $('.draggie').append(' <div>' + dragdrop.data[0][randy] + '</div> ') dragdrop.rNumber() draggie: -> $('.draggie').children().draggable cursor: 'move' revert: (event, ui) -> this.data('uiDraggable').originalPosition = top: 0 left: 0 !event droppie: -> $('.droppie').children().droppable tolerance: 'touch' accept: (e) -> if $(this).html() is e.html() then return true drop: (e, ui) -> dragdrop.endit.push $(this).index() $('.ui-draggable-dragging').fadeOut() $(this).css color: 'black' background: 'white' boxShadow: '0 0 0.5em rgba(0,0,0,0.6)' if dragdrop.endit.length is dragdrop.ctrl.length $('.draggie').fadeOut() setTimeout -> func.end() , 800 quizdrag = alt: undefined pro: undefined num: undefined ctrl: [] count: 0 score: 0 error: 0 inOrder: 1 paused: true starttimer: undefined data: [ { enun: 'Lorem ipsum dolor sit amet' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 0 } { enun: 'Lorem ipsum dolor sit amet' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 1 } { enun: 'Lorem ipsum dolor sit amet' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 2 } { enun: 'Lorem ipsum dolor sit amet' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 3 } ] rNumber: -> quizdrag.randy = Math.floor(Math.random() * quizdrag.data.length) if quizdrag.ctrl.length is quizdrag.data.length then quizdrag.num = true else if quizdrag.ctrl.length < quizdrag.data.length if quizdrag.ctrl.indexOf(quizdrag.randy) is -1 quizdrag.ctrl.push quizdrag.randy $('.quizdrag .quizd').append(' <section id="' + quizdrag.randy + '" class="q"> <div class="enun"> <p>' + quizdrag.data[quizdrag.randy].enun + '</p> </div> <div class="alts"><ul class="draggie"></ul></div> <div class="droppie"></div> </section> ') quizdrag.pro = true quizdrag.putAlts(quizdrag.randy) quizdrag.rNumber() quizdrag.goDrag() goDrag: -> checkPromise = new Promise (resolve, reject) -> if quizdrag.num is true then resolve() else reject() .then (fromResolve) -> $('.droppie').fadeIn() quizdrag.draggie() quizdrag.droppie() quizdrag.timer() .catch (fromReject) -> return draggie: -> $('.draggie').children().draggable cursor: 'move' revert: (event, ui) -> if !event then quizdrag.error++ this.data('uiDraggable').originalPosition = top: 0 left: 0 !event droppie: -> $('.droppie').droppable tolerance: 'touch' accept: (e) -> if quizdrag.data[quizdrag.count] isnt undefined if e.html() is quizdrag.data[quizdrag.count].alts[quizdrag.data[quizdrag.ctrl[quizdrag.count]].answ] then return true drop: (e, ui) -> $('.ui-draggable-dragging, .droppie').fadeOut() quizdrag.alt = $(this).index() quizdrag.score++ quizdrag.count++ if quizdrag.count < quizdrag.data.length func.dismiss() quizdrag.putAlts() $('.quizdrag .quizd').animate { left: '-=100%' }, 1800, -> $('.droppie').fadeIn() else quizdrag.paused = true func.end() start: -> if sets.quizdrag is true $('.content').append(' <div class="quizdrag"> <div class="bar"> <div class="border"></div> <div class="innerbar"></div> </div> <div class="quizd"></div> </div>') quizdrag.rNumber() putAlts: (randy) -> testPromise = new Promise (resolve, reject) -> if quizdrag.pro is true then resolve() else reject() .then (fromResolve) -> for i, j in quizdrag.data[randy].alts $('.quizdrag .quizd section:nth-child(' + quizdrag.inOrder + ') .alts ul').append('<li>' + i + '</li>') if j is quizdrag.data[randy].alts.length - 1 then quizdrag.inOrder++ .catch (fromReject) -> return timer: -> s = 60 starttimer = setInterval -> if s isnt 0 if quizdrag.paused isnt true if s > 0 then s-- if s <= 0 s = 0 clearInterval(quizdrag.starttimer) $('.dimmer').fadeIn() $('.modal').html('<h1>Acabou o tempo!</h1><p>Clique no botão abaixo para tentar mais uma vez.</p><button class="again">Jogar novamente</button>') $('.bar .innerbar').css { height: (100 / 60) * s + '%' } , 1000 vblocks = data: [ { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.' } ] start: -> if sets.vblocks is true $('.content').css { overflowY: 'auto' } $('.content').append('<div class="vblocks"></div>') for i, j in vblocks.data $('.vblocks').append(' <section id="b' + j + '"> <div> <h2>' + vblocks.data[j].tit + '</h2> </div> <div> ' + vblocks.data[j].txt + ' <button class="back"></button> </div> </section> ') showM: ($el) -> $('.vblocks section div:nth-child(1)').fadeIn() $('.vblocks section:nth-child(' + ($el.index() + 1) + ') div:nth-child(1)').fadeOut() backIt: -> $('.vblocks section div:nth-child(1)').fadeIn() func = status: false help: -> if sets.quizdrag is true then quizdrag.paused = true audio.clique.play() $('.dimmer').fadeIn() $('.modal').html('<h1>Ajuda</h1><p></p><button class="dismiss">Fechar</button>') info: -> audio.clique.play() $('.modal').html('<h1>Referência</h1><p></p><button class="end">Voltar</button>') end: -> audio.clique.play() $('.dimmer').delay(1000).fadeIn() $('.modal').html('<h1>Finalizando...</h1><p></p><button class="info">Referência</button>&nbsp;&nbsp;<button class="again">Ver novamente</button>') $('.modal p').html('Texto de feedback.') if sets.quiz is true # melhorar isso if quiz.score > 1 then $('.modal h1').html('Você acertou ' + quiz.score + ' questões!') else if quiz.score < 1 then $('.modal h1').html('Você não acertou nenhuma questão!') else $('.modal h1').html('Você acertou uma questão!') if sets.trueORfalse is true if trueORfalse.score < 1 then $('.modal h1').html('Você não acertou nenhuma questão!') else if trueORfalse.score > 1 then $('.modal h1').html('Você acertou ' + trueORfalse.score + ' questões!') else if trueORfalse.score is 1 then $('.modal h1').html('Você acertou uma questão!') dismiss: -> if sets.quizdrag is true then quizdrag.paused = false audio.clique.play() $('.dimmer').fadeOut() start: -> if func.status is false func.status = true $('.intro').fadeOut() $('.modal').delay(300).fadeIn() else audio.start() clickarea.start() quiz.start() slideshow.start() trueORfalse.start() dragdrop.start() quizdrag.start() vblocks.start() func.dismiss() $('.content').fadeIn() # ----- Eventos ----- # $(document).on 'click', '.audio', -> audio.audio() $(document).on 'click', '.clickarea *', -> if sets.clickarea is true then clickarea.showC $(this) $(document).on 'click', '.dismiss', -> if sets.clickarea is true then clickarea.callEnd() $(document).on 'click', '.alts li', -> if sets.quiz is true then quiz.selectAlt $(this) $(document).on 'click', '.verify', -> if sets.quiz is true then quiz.verify() $(document).on 'click', '.nxt', -> if sets.quiz is true then quiz.nxt() $(document).on 'click', '.ctrl *', -> if sets.slideshow is true then slideshow.slide $(this) $(document).on 'click', '.true, .false', -> if sets.trueORfalse is true then trueORfalse.verify $(this) $(document).on 'click', '.nxt', -> if sets.trueORfalse is true then trueORfalse.nxt() $(document).on 'click', '.vblocks section div:nth-child(1)', -> if sets.vblocks is true then vblocks.showM $(this).parent() $(document).on 'click', '.vblocks .back', -> if sets.vblocks is true then vblocks.backIt() $(document).on 'click', '.start', -> func.start() $(document).on 'click', '.help', -> func.help() $(document).on 'click', '.info', -> func.info() $(document).on 'click', '.end', -> func.end() $(document).on 'click', '.dismiss', -> func.dismiss() $(document).on 'click', '.again', -> location.reload()
161522
### MANZANA v0.4 ---------------------------------------------- Desenvolvido em CoffeeScript por <NAME> Licença: https://opensource.org/licenses/MIT ### # ----- Pré-carregamento das imagens ----- # imgs = [ 'assets/img/help.svg' 'assets/img/audio.svg' 'assets/img/audio-off.svg' ] preload = (imgs) -> counter = 0 $(imgs).each -> $('<img />').attr('src', this).appendTo('body').css { display: 'none' } counter++ if counter is imgs.length $('main').css { opacity: '1' } $('body').css { background: '#e7e7e7' } $(window).on 'load', -> preload(imgs) # ----- Módulos e opções ----- # $ -> sets = audio: false clickarea: false quiz: false trueORfalse: false slideshow: true dragdrop: false quizdrag: false vblocks: false audio = trilha: new Audio('assets/audio/trilha.mp3') clique: new Audio('assets/audio/clique.mp3') start: -> if sets.audio is true audio.trilha.volume = 0.6 audio.trilha.loop = true audio.trilha.play() audio.clique.play() $('.content').append('<button class="ic audio"></button>') audio: -> audio.clique.play() if sets.audio is false sets.audio = true audio.trilha.play() $('.audio').css { background: '#006c7f url(assets/img/audio.svg) no-repeat' } else if sets.audio is true sets.audio = false audio.trilha.pause() $('.audio').css { background: '#006c7f url(assets/img/audio-off.svg) no-repeat' } clickarea = pro: undefined data: [ { txt: '1. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [50, 30] stt: false } { txt: '2. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [20, 20] stt: false } { txt: '3. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [10, 30] stt: false } { txt: '4. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [30, 70] stt: false } { txt: '5. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [50, 50] stt: false }] start: -> if sets.clickarea is true $('.content').append('<div class="clickarea"></div><button class="end">Concluir</button>') for i, j in clickarea.data $('.clickarea').append('<div></div>') $('.clickarea div:nth-child(' + (j + 1) + ')').css top: clickarea.data[j].pos[0] + '%' left: clickarea.data[j].pos[1] + '%' showC: ($el) -> clickarea.data[$el.index()].stt = true $el.css { pointerEvents: 'none', opacity: '0.6' } $('.dimmer').fadeIn() $('.modal').html(clickarea.data[$el.index()].txt + '<button class="dismiss callend">Fechar</button>') callEnd: -> k = 0 for i in clickarea.data if i.stt is true k++ if k is clickarea.data.length $('.end').fadeIn() quiz = alt: undefined pro: undefined ctrl: [] count: 0 score: 0 error: 0 inOrder: 1 data: [ { titl: 'Título da questão' enun: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 0 feed: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { titl: 'Título da questão' enun: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 1 feed: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { titl: 'Título da questão' enun: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 2 feed: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } ] rNumber: -> quiz.randy = Math.floor(Math.random() * quiz.data.length) if quiz.ctrl.length < quiz.data.length if quiz.ctrl.indexOf(quiz.randy) is -1 quiz.ctrl.push quiz.randy $('.quiz').append(' <section id="' + quiz.randy + '" class="q"> <div class="enun"> <h1>' + (quiz.ctrl.indexOf(quiz.randy) + 1) + '. ' + quiz.data[quiz.randy].titl + '</h1> <p>' + quiz.data[quiz.randy].enun + '</p> </div> <div class="alts"><ul></ul></div> <button class="verify">Conferir</button> </section> ') quiz.pro = true else quiz.pro = false quiz.putAlts(quiz.randy) quiz.rNumber() start: -> if sets.quiz is true $('.content').append('<div class="quiz"></div>') quiz.rNumber() selectAlt: ($el) -> quiz.alt = $el.index() $('.verify').css { pointerEvents: 'auto', opacity: '1' } $('.alts li').css { background: 'white', color: 'black' } $el.css { background: '#006c7f', color: 'white' } verify: -> $('.dimmer').delay(500).fadeIn() $('.modal').html('<h1></h1><p>' + quiz.data[quiz.ctrl[quiz.count]].feed + '</p><button class="nxt">Prosseguir</button>') if quiz.alt is quiz.data[quiz.ctrl[quiz.count]].answ quiz.score++ $('.modal h1').html('Resposta certa!') else quiz.error++ $('.modal h1').html('Resposta errada!') nxt: -> quiz.count++ if quiz.count < quiz.data.length func.dismiss() quiz.putAlts() $('.verify').css { pointerEvents: 'none', opacity: '0.6' } $('.quiz section:nth-child(' + quiz.count + ')').fadeOut() $('.quiz section:nth-child(' + (quiz.count + 1) + ')').fadeIn() else setTimeout -> func.end() , 400 putAlts: (randy) -> testPromise = new Promise (resolve, reject) -> if quiz.pro is true then resolve() else reject() .then (fromResolve) -> for i, j in quiz.data[randy].alts $('.quiz section:nth-child(' + quiz.inOrder + ') .alts ul').append('<li>' + i + '</li>') if j is quiz.data[randy].alts.length - 1 then quiz.inOrder++ .catch (fromReject) -> return trueORfalse = count: 0 score: 0 alt: undefined data: [ { titl: 'Título da questão' text: '1. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: true feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } { titl: 'Título da questão' text: '2. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: true feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } { titl: 'Título da questão' text: '3. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: false feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } { titl: 'Título da questão' text: '4. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: false feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } { titl: 'Título da questão' text: '5. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: true feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } ] start: -> if sets.trueORfalse is true $('.content').append('<div class="t-or-f"></div>') j = 0 func.dismiss() for i in trueORfalse.data $('.t-or-f').append(' <section> <div class="txt"> <h1>' + trueORfalse.data[j].titl + '</h1> <p>' + trueORfalse.data[j].text + '</p> </div> <div class="ctrl"> <button class="true">verdadeiro</button> <button class="false">falso</button> </div> </section> ') j++ verify: ($el) -> $('.ctrl').css { pointerEvents: 'none' } if $el.attr('class') is 'true' then trueORfalse.alt = true else if $el.attr('class') is 'false' then trueORfalse.alt = false $('.dimmer').fadeIn() $('.modal').html('<h1></h1><p>' + trueORfalse.data[trueORfalse.count].feed + '</p><button class="nxt">Próxima</button>') if trueORfalse.alt is trueORfalse.data[trueORfalse.count].answ trueORfalse.score++ $('.modal h1').html('Resposta correta!') else $('.modal h1').html('Resposta errada!') nxt: -> trueORfalse.count++ if trueORfalse.count < trueORfalse.data.length func.dismiss() $('.t-or-f .ctrl').css { pointerEvents: 'auto' } $('.t-or-f section:nth-child(' + trueORfalse.count + ')').fadeOut() $('.t-or-f section:nth-child(' + (trueORfalse.count + 1) + ')').fadeIn() else setTimeout -> func.end() , 500 slideshow = count: 0 data: [ { img: 'assets/img/img1.png' txt: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' } { img: 'assets/img/img2.png' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { img: 'assets/img/img3.png' txt: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' } { img: 'assets/img/img4.png' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { img: 'assets/img/img5.png' txt: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' } ] start: -> if sets.slideshow is true $('.content').append(' <div class="slideshow"> <div class="slides"></div> <div class="ctrl"> <button class="next"></button> <button class="prev"></button> </div> </div>') for i, j in slideshow.data $('.slides').append(' <section> <div>' + slideshow.data[j].txt + '</div> <img src="' + slideshow.data[j].img + '"> </section> ') slide: ($el) -> if $el.attr('class') is 'next' slideshow.count++ $('.prev').css { pointerEvents: 'auto', opacity: '1' } if slideshow.count < slideshow.data.length $('.slides section').fadeOut() $('.slides section:nth-child(' + (slideshow.count + 1) + ')').fadeIn() else func.end() if $el.attr('class') is 'prev' slideshow.count-- $('.slides section').fadeOut() $('.slides section:nth-child(' + (slideshow.count + 1) + ')').fadeIn() if slideshow.count is 0 then $('.prev').css { pointerEvents: 'none', opacity: '0.6' } dragdrop = count: 0 ctrl: [] endit: [] data: [ [ 'draggable 1' 'draggable 2' 'draggable 3' 'draggable 4' 'draggable 5' 'draggable 6' ] [ 'draggable 1' 'draggable 2' 'draggable 3' 'draggable 4' 'draggable 5' 'draggable 6' ] ] start: -> if sets.dragdrop is true $('.content').append(' <div class="drag-drop"> <div class="draggie"></div> <div class="droppie"></div> </div>') func.dismiss() dragdrop.rNumber() for i in dragdrop.data[1] $('.droppie').append('<div>' + i + '</div>') dragdrop.draggie() dragdrop.droppie() rNumber: -> randy = Math.floor(Math.random() * dragdrop.data[0].length) if dragdrop.ctrl.length < dragdrop.data[0].length if dragdrop.ctrl.indexOf(randy) is -1 dragdrop.ctrl.push randy $('.draggie').append(' <div>' + dragdrop.data[0][randy] + '</div> ') dragdrop.rNumber() draggie: -> $('.draggie').children().draggable cursor: 'move' revert: (event, ui) -> this.data('uiDraggable').originalPosition = top: 0 left: 0 !event droppie: -> $('.droppie').children().droppable tolerance: 'touch' accept: (e) -> if $(this).html() is e.html() then return true drop: (e, ui) -> dragdrop.endit.push $(this).index() $('.ui-draggable-dragging').fadeOut() $(this).css color: 'black' background: 'white' boxShadow: '0 0 0.5em rgba(0,0,0,0.6)' if dragdrop.endit.length is dragdrop.ctrl.length $('.draggie').fadeOut() setTimeout -> func.end() , 800 quizdrag = alt: undefined pro: undefined num: undefined ctrl: [] count: 0 score: 0 error: 0 inOrder: 1 paused: true starttimer: undefined data: [ { enun: 'Lorem ipsum dolor sit amet' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 0 } { enun: 'Lorem ipsum dolor sit amet' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 1 } { enun: 'Lorem ipsum dolor sit amet' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 2 } { enun: 'Lorem ipsum dolor sit amet' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 3 } ] rNumber: -> quizdrag.randy = Math.floor(Math.random() * quizdrag.data.length) if quizdrag.ctrl.length is quizdrag.data.length then quizdrag.num = true else if quizdrag.ctrl.length < quizdrag.data.length if quizdrag.ctrl.indexOf(quizdrag.randy) is -1 quizdrag.ctrl.push quizdrag.randy $('.quizdrag .quizd').append(' <section id="' + quizdrag.randy + '" class="q"> <div class="enun"> <p>' + quizdrag.data[quizdrag.randy].enun + '</p> </div> <div class="alts"><ul class="draggie"></ul></div> <div class="droppie"></div> </section> ') quizdrag.pro = true quizdrag.putAlts(quizdrag.randy) quizdrag.rNumber() quizdrag.goDrag() goDrag: -> checkPromise = new Promise (resolve, reject) -> if quizdrag.num is true then resolve() else reject() .then (fromResolve) -> $('.droppie').fadeIn() quizdrag.draggie() quizdrag.droppie() quizdrag.timer() .catch (fromReject) -> return draggie: -> $('.draggie').children().draggable cursor: 'move' revert: (event, ui) -> if !event then quizdrag.error++ this.data('uiDraggable').originalPosition = top: 0 left: 0 !event droppie: -> $('.droppie').droppable tolerance: 'touch' accept: (e) -> if quizdrag.data[quizdrag.count] isnt undefined if e.html() is quizdrag.data[quizdrag.count].alts[quizdrag.data[quizdrag.ctrl[quizdrag.count]].answ] then return true drop: (e, ui) -> $('.ui-draggable-dragging, .droppie').fadeOut() quizdrag.alt = $(this).index() quizdrag.score++ quizdrag.count++ if quizdrag.count < quizdrag.data.length func.dismiss() quizdrag.putAlts() $('.quizdrag .quizd').animate { left: '-=100%' }, 1800, -> $('.droppie').fadeIn() else quizdrag.paused = true func.end() start: -> if sets.quizdrag is true $('.content').append(' <div class="quizdrag"> <div class="bar"> <div class="border"></div> <div class="innerbar"></div> </div> <div class="quizd"></div> </div>') quizdrag.rNumber() putAlts: (randy) -> testPromise = new Promise (resolve, reject) -> if quizdrag.pro is true then resolve() else reject() .then (fromResolve) -> for i, j in quizdrag.data[randy].alts $('.quizdrag .quizd section:nth-child(' + quizdrag.inOrder + ') .alts ul').append('<li>' + i + '</li>') if j is quizdrag.data[randy].alts.length - 1 then quizdrag.inOrder++ .catch (fromReject) -> return timer: -> s = 60 starttimer = setInterval -> if s isnt 0 if quizdrag.paused isnt true if s > 0 then s-- if s <= 0 s = 0 clearInterval(quizdrag.starttimer) $('.dimmer').fadeIn() $('.modal').html('<h1>Acabou o tempo!</h1><p>Clique no botão abaixo para tentar mais uma vez.</p><button class="again">Jogar novamente</button>') $('.bar .innerbar').css { height: (100 / 60) * s + '%' } , 1000 vblocks = data: [ { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.' } ] start: -> if sets.vblocks is true $('.content').css { overflowY: 'auto' } $('.content').append('<div class="vblocks"></div>') for i, j in vblocks.data $('.vblocks').append(' <section id="b' + j + '"> <div> <h2>' + vblocks.data[j].tit + '</h2> </div> <div> ' + vblocks.data[j].txt + ' <button class="back"></button> </div> </section> ') showM: ($el) -> $('.vblocks section div:nth-child(1)').fadeIn() $('.vblocks section:nth-child(' + ($el.index() + 1) + ') div:nth-child(1)').fadeOut() backIt: -> $('.vblocks section div:nth-child(1)').fadeIn() func = status: false help: -> if sets.quizdrag is true then quizdrag.paused = true audio.clique.play() $('.dimmer').fadeIn() $('.modal').html('<h1>Ajuda</h1><p></p><button class="dismiss">Fechar</button>') info: -> audio.clique.play() $('.modal').html('<h1>Referência</h1><p></p><button class="end">Voltar</button>') end: -> audio.clique.play() $('.dimmer').delay(1000).fadeIn() $('.modal').html('<h1>Finalizando...</h1><p></p><button class="info">Referência</button>&nbsp;&nbsp;<button class="again">Ver novamente</button>') $('.modal p').html('Texto de feedback.') if sets.quiz is true # melhorar isso if quiz.score > 1 then $('.modal h1').html('Você acertou ' + quiz.score + ' questões!') else if quiz.score < 1 then $('.modal h1').html('Você não acertou nenhuma questão!') else $('.modal h1').html('Você acertou uma questão!') if sets.trueORfalse is true if trueORfalse.score < 1 then $('.modal h1').html('Você não acertou nenhuma questão!') else if trueORfalse.score > 1 then $('.modal h1').html('Você acertou ' + trueORfalse.score + ' questões!') else if trueORfalse.score is 1 then $('.modal h1').html('Você acertou uma questão!') dismiss: -> if sets.quizdrag is true then quizdrag.paused = false audio.clique.play() $('.dimmer').fadeOut() start: -> if func.status is false func.status = true $('.intro').fadeOut() $('.modal').delay(300).fadeIn() else audio.start() clickarea.start() quiz.start() slideshow.start() trueORfalse.start() dragdrop.start() quizdrag.start() vblocks.start() func.dismiss() $('.content').fadeIn() # ----- Eventos ----- # $(document).on 'click', '.audio', -> audio.audio() $(document).on 'click', '.clickarea *', -> if sets.clickarea is true then clickarea.showC $(this) $(document).on 'click', '.dismiss', -> if sets.clickarea is true then clickarea.callEnd() $(document).on 'click', '.alts li', -> if sets.quiz is true then quiz.selectAlt $(this) $(document).on 'click', '.verify', -> if sets.quiz is true then quiz.verify() $(document).on 'click', '.nxt', -> if sets.quiz is true then quiz.nxt() $(document).on 'click', '.ctrl *', -> if sets.slideshow is true then slideshow.slide $(this) $(document).on 'click', '.true, .false', -> if sets.trueORfalse is true then trueORfalse.verify $(this) $(document).on 'click', '.nxt', -> if sets.trueORfalse is true then trueORfalse.nxt() $(document).on 'click', '.vblocks section div:nth-child(1)', -> if sets.vblocks is true then vblocks.showM $(this).parent() $(document).on 'click', '.vblocks .back', -> if sets.vblocks is true then vblocks.backIt() $(document).on 'click', '.start', -> func.start() $(document).on 'click', '.help', -> func.help() $(document).on 'click', '.info', -> func.info() $(document).on 'click', '.end', -> func.end() $(document).on 'click', '.dismiss', -> func.dismiss() $(document).on 'click', '.again', -> location.reload()
true
### MANZANA v0.4 ---------------------------------------------- Desenvolvido em CoffeeScript por PI:NAME:<NAME>END_PI Licença: https://opensource.org/licenses/MIT ### # ----- Pré-carregamento das imagens ----- # imgs = [ 'assets/img/help.svg' 'assets/img/audio.svg' 'assets/img/audio-off.svg' ] preload = (imgs) -> counter = 0 $(imgs).each -> $('<img />').attr('src', this).appendTo('body').css { display: 'none' } counter++ if counter is imgs.length $('main').css { opacity: '1' } $('body').css { background: '#e7e7e7' } $(window).on 'load', -> preload(imgs) # ----- Módulos e opções ----- # $ -> sets = audio: false clickarea: false quiz: false trueORfalse: false slideshow: true dragdrop: false quizdrag: false vblocks: false audio = trilha: new Audio('assets/audio/trilha.mp3') clique: new Audio('assets/audio/clique.mp3') start: -> if sets.audio is true audio.trilha.volume = 0.6 audio.trilha.loop = true audio.trilha.play() audio.clique.play() $('.content').append('<button class="ic audio"></button>') audio: -> audio.clique.play() if sets.audio is false sets.audio = true audio.trilha.play() $('.audio').css { background: '#006c7f url(assets/img/audio.svg) no-repeat' } else if sets.audio is true sets.audio = false audio.trilha.pause() $('.audio').css { background: '#006c7f url(assets/img/audio-off.svg) no-repeat' } clickarea = pro: undefined data: [ { txt: '1. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [50, 30] stt: false } { txt: '2. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [20, 20] stt: false } { txt: '3. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [10, 30] stt: false } { txt: '4. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [30, 70] stt: false } { txt: '5. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' pos: [50, 50] stt: false }] start: -> if sets.clickarea is true $('.content').append('<div class="clickarea"></div><button class="end">Concluir</button>') for i, j in clickarea.data $('.clickarea').append('<div></div>') $('.clickarea div:nth-child(' + (j + 1) + ')').css top: clickarea.data[j].pos[0] + '%' left: clickarea.data[j].pos[1] + '%' showC: ($el) -> clickarea.data[$el.index()].stt = true $el.css { pointerEvents: 'none', opacity: '0.6' } $('.dimmer').fadeIn() $('.modal').html(clickarea.data[$el.index()].txt + '<button class="dismiss callend">Fechar</button>') callEnd: -> k = 0 for i in clickarea.data if i.stt is true k++ if k is clickarea.data.length $('.end').fadeIn() quiz = alt: undefined pro: undefined ctrl: [] count: 0 score: 0 error: 0 inOrder: 1 data: [ { titl: 'Título da questão' enun: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 0 feed: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { titl: 'Título da questão' enun: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 1 feed: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { titl: 'Título da questão' enun: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 2 feed: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } ] rNumber: -> quiz.randy = Math.floor(Math.random() * quiz.data.length) if quiz.ctrl.length < quiz.data.length if quiz.ctrl.indexOf(quiz.randy) is -1 quiz.ctrl.push quiz.randy $('.quiz').append(' <section id="' + quiz.randy + '" class="q"> <div class="enun"> <h1>' + (quiz.ctrl.indexOf(quiz.randy) + 1) + '. ' + quiz.data[quiz.randy].titl + '</h1> <p>' + quiz.data[quiz.randy].enun + '</p> </div> <div class="alts"><ul></ul></div> <button class="verify">Conferir</button> </section> ') quiz.pro = true else quiz.pro = false quiz.putAlts(quiz.randy) quiz.rNumber() start: -> if sets.quiz is true $('.content').append('<div class="quiz"></div>') quiz.rNumber() selectAlt: ($el) -> quiz.alt = $el.index() $('.verify').css { pointerEvents: 'auto', opacity: '1' } $('.alts li').css { background: 'white', color: 'black' } $el.css { background: '#006c7f', color: 'white' } verify: -> $('.dimmer').delay(500).fadeIn() $('.modal').html('<h1></h1><p>' + quiz.data[quiz.ctrl[quiz.count]].feed + '</p><button class="nxt">Prosseguir</button>') if quiz.alt is quiz.data[quiz.ctrl[quiz.count]].answ quiz.score++ $('.modal h1').html('Resposta certa!') else quiz.error++ $('.modal h1').html('Resposta errada!') nxt: -> quiz.count++ if quiz.count < quiz.data.length func.dismiss() quiz.putAlts() $('.verify').css { pointerEvents: 'none', opacity: '0.6' } $('.quiz section:nth-child(' + quiz.count + ')').fadeOut() $('.quiz section:nth-child(' + (quiz.count + 1) + ')').fadeIn() else setTimeout -> func.end() , 400 putAlts: (randy) -> testPromise = new Promise (resolve, reject) -> if quiz.pro is true then resolve() else reject() .then (fromResolve) -> for i, j in quiz.data[randy].alts $('.quiz section:nth-child(' + quiz.inOrder + ') .alts ul').append('<li>' + i + '</li>') if j is quiz.data[randy].alts.length - 1 then quiz.inOrder++ .catch (fromReject) -> return trueORfalse = count: 0 score: 0 alt: undefined data: [ { titl: 'Título da questão' text: '1. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: true feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } { titl: 'Título da questão' text: '2. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: true feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } { titl: 'Título da questão' text: '3. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: false feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } { titl: 'Título da questão' text: '4. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: false feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } { titl: 'Título da questão' text: '5. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' answ: true feed: 'Ut enim ad minim veniam, quis nostrud exercitation.' } ] start: -> if sets.trueORfalse is true $('.content').append('<div class="t-or-f"></div>') j = 0 func.dismiss() for i in trueORfalse.data $('.t-or-f').append(' <section> <div class="txt"> <h1>' + trueORfalse.data[j].titl + '</h1> <p>' + trueORfalse.data[j].text + '</p> </div> <div class="ctrl"> <button class="true">verdadeiro</button> <button class="false">falso</button> </div> </section> ') j++ verify: ($el) -> $('.ctrl').css { pointerEvents: 'none' } if $el.attr('class') is 'true' then trueORfalse.alt = true else if $el.attr('class') is 'false' then trueORfalse.alt = false $('.dimmer').fadeIn() $('.modal').html('<h1></h1><p>' + trueORfalse.data[trueORfalse.count].feed + '</p><button class="nxt">Próxima</button>') if trueORfalse.alt is trueORfalse.data[trueORfalse.count].answ trueORfalse.score++ $('.modal h1').html('Resposta correta!') else $('.modal h1').html('Resposta errada!') nxt: -> trueORfalse.count++ if trueORfalse.count < trueORfalse.data.length func.dismiss() $('.t-or-f .ctrl').css { pointerEvents: 'auto' } $('.t-or-f section:nth-child(' + trueORfalse.count + ')').fadeOut() $('.t-or-f section:nth-child(' + (trueORfalse.count + 1) + ')').fadeIn() else setTimeout -> func.end() , 500 slideshow = count: 0 data: [ { img: 'assets/img/img1.png' txt: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' } { img: 'assets/img/img2.png' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { img: 'assets/img/img3.png' txt: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' } { img: 'assets/img/img4.png' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { img: 'assets/img/img5.png' txt: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' } ] start: -> if sets.slideshow is true $('.content').append(' <div class="slideshow"> <div class="slides"></div> <div class="ctrl"> <button class="next"></button> <button class="prev"></button> </div> </div>') for i, j in slideshow.data $('.slides').append(' <section> <div>' + slideshow.data[j].txt + '</div> <img src="' + slideshow.data[j].img + '"> </section> ') slide: ($el) -> if $el.attr('class') is 'next' slideshow.count++ $('.prev').css { pointerEvents: 'auto', opacity: '1' } if slideshow.count < slideshow.data.length $('.slides section').fadeOut() $('.slides section:nth-child(' + (slideshow.count + 1) + ')').fadeIn() else func.end() if $el.attr('class') is 'prev' slideshow.count-- $('.slides section').fadeOut() $('.slides section:nth-child(' + (slideshow.count + 1) + ')').fadeIn() if slideshow.count is 0 then $('.prev').css { pointerEvents: 'none', opacity: '0.6' } dragdrop = count: 0 ctrl: [] endit: [] data: [ [ 'draggable 1' 'draggable 2' 'draggable 3' 'draggable 4' 'draggable 5' 'draggable 6' ] [ 'draggable 1' 'draggable 2' 'draggable 3' 'draggable 4' 'draggable 5' 'draggable 6' ] ] start: -> if sets.dragdrop is true $('.content').append(' <div class="drag-drop"> <div class="draggie"></div> <div class="droppie"></div> </div>') func.dismiss() dragdrop.rNumber() for i in dragdrop.data[1] $('.droppie').append('<div>' + i + '</div>') dragdrop.draggie() dragdrop.droppie() rNumber: -> randy = Math.floor(Math.random() * dragdrop.data[0].length) if dragdrop.ctrl.length < dragdrop.data[0].length if dragdrop.ctrl.indexOf(randy) is -1 dragdrop.ctrl.push randy $('.draggie').append(' <div>' + dragdrop.data[0][randy] + '</div> ') dragdrop.rNumber() draggie: -> $('.draggie').children().draggable cursor: 'move' revert: (event, ui) -> this.data('uiDraggable').originalPosition = top: 0 left: 0 !event droppie: -> $('.droppie').children().droppable tolerance: 'touch' accept: (e) -> if $(this).html() is e.html() then return true drop: (e, ui) -> dragdrop.endit.push $(this).index() $('.ui-draggable-dragging').fadeOut() $(this).css color: 'black' background: 'white' boxShadow: '0 0 0.5em rgba(0,0,0,0.6)' if dragdrop.endit.length is dragdrop.ctrl.length $('.draggie').fadeOut() setTimeout -> func.end() , 800 quizdrag = alt: undefined pro: undefined num: undefined ctrl: [] count: 0 score: 0 error: 0 inOrder: 1 paused: true starttimer: undefined data: [ { enun: 'Lorem ipsum dolor sit amet' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 0 } { enun: 'Lorem ipsum dolor sit amet' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 1 } { enun: 'Lorem ipsum dolor sit amet' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 2 } { enun: 'Lorem ipsum dolor sit amet' alts: [ 'Alternativa 1' 'Alternativa 2' 'Alternativa 3' 'Alternativa 4' ] answ: 3 } ] rNumber: -> quizdrag.randy = Math.floor(Math.random() * quizdrag.data.length) if quizdrag.ctrl.length is quizdrag.data.length then quizdrag.num = true else if quizdrag.ctrl.length < quizdrag.data.length if quizdrag.ctrl.indexOf(quizdrag.randy) is -1 quizdrag.ctrl.push quizdrag.randy $('.quizdrag .quizd').append(' <section id="' + quizdrag.randy + '" class="q"> <div class="enun"> <p>' + quizdrag.data[quizdrag.randy].enun + '</p> </div> <div class="alts"><ul class="draggie"></ul></div> <div class="droppie"></div> </section> ') quizdrag.pro = true quizdrag.putAlts(quizdrag.randy) quizdrag.rNumber() quizdrag.goDrag() goDrag: -> checkPromise = new Promise (resolve, reject) -> if quizdrag.num is true then resolve() else reject() .then (fromResolve) -> $('.droppie').fadeIn() quizdrag.draggie() quizdrag.droppie() quizdrag.timer() .catch (fromReject) -> return draggie: -> $('.draggie').children().draggable cursor: 'move' revert: (event, ui) -> if !event then quizdrag.error++ this.data('uiDraggable').originalPosition = top: 0 left: 0 !event droppie: -> $('.droppie').droppable tolerance: 'touch' accept: (e) -> if quizdrag.data[quizdrag.count] isnt undefined if e.html() is quizdrag.data[quizdrag.count].alts[quizdrag.data[quizdrag.ctrl[quizdrag.count]].answ] then return true drop: (e, ui) -> $('.ui-draggable-dragging, .droppie').fadeOut() quizdrag.alt = $(this).index() quizdrag.score++ quizdrag.count++ if quizdrag.count < quizdrag.data.length func.dismiss() quizdrag.putAlts() $('.quizdrag .quizd').animate { left: '-=100%' }, 1800, -> $('.droppie').fadeIn() else quizdrag.paused = true func.end() start: -> if sets.quizdrag is true $('.content').append(' <div class="quizdrag"> <div class="bar"> <div class="border"></div> <div class="innerbar"></div> </div> <div class="quizd"></div> </div>') quizdrag.rNumber() putAlts: (randy) -> testPromise = new Promise (resolve, reject) -> if quizdrag.pro is true then resolve() else reject() .then (fromResolve) -> for i, j in quizdrag.data[randy].alts $('.quizdrag .quizd section:nth-child(' + quizdrag.inOrder + ') .alts ul').append('<li>' + i + '</li>') if j is quizdrag.data[randy].alts.length - 1 then quizdrag.inOrder++ .catch (fromReject) -> return timer: -> s = 60 starttimer = setInterval -> if s isnt 0 if quizdrag.paused isnt true if s > 0 then s-- if s <= 0 s = 0 clearInterval(quizdrag.starttimer) $('.dimmer').fadeIn() $('.modal').html('<h1>Acabou o tempo!</h1><p>Clique no botão abaixo para tentar mais uma vez.</p><button class="again">Jogar novamente</button>') $('.bar .innerbar').css { height: (100 / 60) * s + '%' } , 1000 vblocks = data: [ { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } { tit: 'Título do quadro' txt: 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.' } ] start: -> if sets.vblocks is true $('.content').css { overflowY: 'auto' } $('.content').append('<div class="vblocks"></div>') for i, j in vblocks.data $('.vblocks').append(' <section id="b' + j + '"> <div> <h2>' + vblocks.data[j].tit + '</h2> </div> <div> ' + vblocks.data[j].txt + ' <button class="back"></button> </div> </section> ') showM: ($el) -> $('.vblocks section div:nth-child(1)').fadeIn() $('.vblocks section:nth-child(' + ($el.index() + 1) + ') div:nth-child(1)').fadeOut() backIt: -> $('.vblocks section div:nth-child(1)').fadeIn() func = status: false help: -> if sets.quizdrag is true then quizdrag.paused = true audio.clique.play() $('.dimmer').fadeIn() $('.modal').html('<h1>Ajuda</h1><p></p><button class="dismiss">Fechar</button>') info: -> audio.clique.play() $('.modal').html('<h1>Referência</h1><p></p><button class="end">Voltar</button>') end: -> audio.clique.play() $('.dimmer').delay(1000).fadeIn() $('.modal').html('<h1>Finalizando...</h1><p></p><button class="info">Referência</button>&nbsp;&nbsp;<button class="again">Ver novamente</button>') $('.modal p').html('Texto de feedback.') if sets.quiz is true # melhorar isso if quiz.score > 1 then $('.modal h1').html('Você acertou ' + quiz.score + ' questões!') else if quiz.score < 1 then $('.modal h1').html('Você não acertou nenhuma questão!') else $('.modal h1').html('Você acertou uma questão!') if sets.trueORfalse is true if trueORfalse.score < 1 then $('.modal h1').html('Você não acertou nenhuma questão!') else if trueORfalse.score > 1 then $('.modal h1').html('Você acertou ' + trueORfalse.score + ' questões!') else if trueORfalse.score is 1 then $('.modal h1').html('Você acertou uma questão!') dismiss: -> if sets.quizdrag is true then quizdrag.paused = false audio.clique.play() $('.dimmer').fadeOut() start: -> if func.status is false func.status = true $('.intro').fadeOut() $('.modal').delay(300).fadeIn() else audio.start() clickarea.start() quiz.start() slideshow.start() trueORfalse.start() dragdrop.start() quizdrag.start() vblocks.start() func.dismiss() $('.content').fadeIn() # ----- Eventos ----- # $(document).on 'click', '.audio', -> audio.audio() $(document).on 'click', '.clickarea *', -> if sets.clickarea is true then clickarea.showC $(this) $(document).on 'click', '.dismiss', -> if sets.clickarea is true then clickarea.callEnd() $(document).on 'click', '.alts li', -> if sets.quiz is true then quiz.selectAlt $(this) $(document).on 'click', '.verify', -> if sets.quiz is true then quiz.verify() $(document).on 'click', '.nxt', -> if sets.quiz is true then quiz.nxt() $(document).on 'click', '.ctrl *', -> if sets.slideshow is true then slideshow.slide $(this) $(document).on 'click', '.true, .false', -> if sets.trueORfalse is true then trueORfalse.verify $(this) $(document).on 'click', '.nxt', -> if sets.trueORfalse is true then trueORfalse.nxt() $(document).on 'click', '.vblocks section div:nth-child(1)', -> if sets.vblocks is true then vblocks.showM $(this).parent() $(document).on 'click', '.vblocks .back', -> if sets.vblocks is true then vblocks.backIt() $(document).on 'click', '.start', -> func.start() $(document).on 'click', '.help', -> func.help() $(document).on 'click', '.info', -> func.info() $(document).on 'click', '.end', -> func.end() $(document).on 'click', '.dismiss', -> func.dismiss() $(document).on 'click', '.again', -> location.reload()
[ { "context": "u need + special system for clear alpha.\n# @author David Ronai / Makiopolis.com / @Makio64\n#\n\nStage = require('m", "end": 115, "score": 0.9998410940170288, "start": 104, "tag": "NAME", "value": "David Ronai" }, { "context": "al system for clear alpha.\n# @author David Ronai / Makiopolis.com / @Makio64\n#\n\nStage = require('makio/core/Stage')", "end": 132, "score": 0.921416163444519, "start": 118, "tag": "EMAIL", "value": "Makiopolis.com" }, { "context": "ar alpha.\n# @author David Ronai / Makiopolis.com / @Makio64\n#\n\nStage = require('makio/core/Stage')\nsignals = ", "end": 143, "score": 0.9995999336242676, "start": 135, "tag": "USERNAME", "value": "@Makio64" } ]
src/coffee/makio/core/Stage3d.coffee
Makio64/pizzaparty_vj
1
# # Stage3d for threejs & wagner with every basics you need + special system for clear alpha. # @author David Ronai / Makiopolis.com / @Makio64 # Stage = require('makio/core/Stage') signals = require('signals') class Stage3d @camera = null @scene = null @renderer = null @isInit = false # postProcess with wagner @postProcessInitiated = false @usePostProcessing = false @passes = [] @isActivated = false @clearAuto = false @clearAlpha = 1 @models = {} @init = (options)=> if(@isInit) @setColorFromOption(options) @activate() return @onBeforeRenderer = new signals() @clearColor = if options.background then options.background else 0xFF0000 w = window.innerWidth h = window.innerHeight @resolution = new THREE.Vector2(w,h) @camera = new THREE.PerspectiveCamera( 50, w / h, 1, 1000000 ) @scene = new THREE.Scene() @scene2 = new THREE.Scene() @orthoCamera = new THREE.OrthographicCamera( - 0.5, 0.5, 0.5, - 0.5, 0, 1 ) @mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 1, 1 ), new THREE.MeshBasicMaterial({color:@clearColor,transparent:true,opacity:@clearAlpha}) ) @scene2.add( @mesh ) transparent = options.transparent||false antialias = options.antialias||false @renderer = new THREE.WebGLRenderer({alpha:transparent,antialias:antialias,preserveDrawingBuffer:false}) console.log @renderer @renderer.setPixelRatio( window.devicePixelRatio ) @renderer.domElement.className = 'three' @setColorFromOption(options) @renderer.setSize( w, h ) @isInit = true @activate() return @setClearColor = (value)=> @clearColor = value @mesh.material.color = @clearColor @renderer.setClearColor( @clearColor,1 ) return @setColorFromOption = (options)=> @clearAlpha = if options.clearAlpha == undefined then 1 else options.clearAlpha @renderer.setClearColor( parseInt(options.background), @clearAlpha ) return @activate = ()=> if(@isActivated) return @isActivated = true Stage.onUpdate.add(@render) Stage.onResize.add(@resize) document.body.appendChild(@renderer.domElement) return @desactivate = ()=> if(!@isActivated) return @isActivated = false Stage.onUpdate.remove(@render) Stage.onResize.remove(@resize) document.body.removeChild(@renderer.domElement) return @initPostProcessing = ()=> if(@postProcessInitiated) return console.log('WAGNER PostProcess') @postProcessInitiated = true @usePostProcessing = true @composer = new WAGNER.Composer( @renderer, {useRGBA: true} ) @composer.setSize( @renderer.domElement.width, @renderer.domElement.height ) return @add = (obj)=> @scene.add(obj) return @remove = (obj)=> @scene.remove(obj) return @removeAll = ()=> while @scene.children.length>0 @scene.remove(@scene.children[0]) return @addPass = (pass)=> @passes.push(pass) return @removePass = (pass)=> for i in [0...@passes.length] by 1 if(@passes[i]==pass) @passes.splice(i,1) break return @render = (dt)=> @renderer.autoClearColor = @clearColor @renderer.autoClear = @clearAuto @mesh.material.opacity = @clearAlpha if(@control) @control.update(dt) @onBeforeRenderer.dispatch() if(@usePostProcessing) @composer.reset() @composer.render( @scene2, @orthoCamera ) @composer.toScreen() @composer.reset() @composer.render( @scene, @camera ) for pass in @passes @composer.pass( pass ) @composer.toScreen() else @renderer.clear() @renderer.render(@scene, @camera) return @resize = ()=> w = window.innerWidth h = window.innerHeight @resolution.x = w @resolution.y = h if @renderer @camera.aspect = w / h @camera.updateProjectionMatrix() @renderer.setSize( w, h ) @renderer.setPixelRatio( window.devicePixelRatio ) @render(0) if @composer @composer.setSize( @renderer.domElement.width, @renderer.domElement.height ) return @initGUI = (gui)=> g = gui.addFolder('Camera') g.add(@camera,'fov',1,100).onChange(@resize) g.add(@camera.position,'x').listen() g.add(@camera.position,'y').listen() g.add(@camera.position,'z').listen() return module.exports = Stage3d
3206
# # Stage3d for threejs & wagner with every basics you need + special system for clear alpha. # @author <NAME> / <EMAIL> / @Makio64 # Stage = require('makio/core/Stage') signals = require('signals') class Stage3d @camera = null @scene = null @renderer = null @isInit = false # postProcess with wagner @postProcessInitiated = false @usePostProcessing = false @passes = [] @isActivated = false @clearAuto = false @clearAlpha = 1 @models = {} @init = (options)=> if(@isInit) @setColorFromOption(options) @activate() return @onBeforeRenderer = new signals() @clearColor = if options.background then options.background else 0xFF0000 w = window.innerWidth h = window.innerHeight @resolution = new THREE.Vector2(w,h) @camera = new THREE.PerspectiveCamera( 50, w / h, 1, 1000000 ) @scene = new THREE.Scene() @scene2 = new THREE.Scene() @orthoCamera = new THREE.OrthographicCamera( - 0.5, 0.5, 0.5, - 0.5, 0, 1 ) @mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 1, 1 ), new THREE.MeshBasicMaterial({color:@clearColor,transparent:true,opacity:@clearAlpha}) ) @scene2.add( @mesh ) transparent = options.transparent||false antialias = options.antialias||false @renderer = new THREE.WebGLRenderer({alpha:transparent,antialias:antialias,preserveDrawingBuffer:false}) console.log @renderer @renderer.setPixelRatio( window.devicePixelRatio ) @renderer.domElement.className = 'three' @setColorFromOption(options) @renderer.setSize( w, h ) @isInit = true @activate() return @setClearColor = (value)=> @clearColor = value @mesh.material.color = @clearColor @renderer.setClearColor( @clearColor,1 ) return @setColorFromOption = (options)=> @clearAlpha = if options.clearAlpha == undefined then 1 else options.clearAlpha @renderer.setClearColor( parseInt(options.background), @clearAlpha ) return @activate = ()=> if(@isActivated) return @isActivated = true Stage.onUpdate.add(@render) Stage.onResize.add(@resize) document.body.appendChild(@renderer.domElement) return @desactivate = ()=> if(!@isActivated) return @isActivated = false Stage.onUpdate.remove(@render) Stage.onResize.remove(@resize) document.body.removeChild(@renderer.domElement) return @initPostProcessing = ()=> if(@postProcessInitiated) return console.log('WAGNER PostProcess') @postProcessInitiated = true @usePostProcessing = true @composer = new WAGNER.Composer( @renderer, {useRGBA: true} ) @composer.setSize( @renderer.domElement.width, @renderer.domElement.height ) return @add = (obj)=> @scene.add(obj) return @remove = (obj)=> @scene.remove(obj) return @removeAll = ()=> while @scene.children.length>0 @scene.remove(@scene.children[0]) return @addPass = (pass)=> @passes.push(pass) return @removePass = (pass)=> for i in [0...@passes.length] by 1 if(@passes[i]==pass) @passes.splice(i,1) break return @render = (dt)=> @renderer.autoClearColor = @clearColor @renderer.autoClear = @clearAuto @mesh.material.opacity = @clearAlpha if(@control) @control.update(dt) @onBeforeRenderer.dispatch() if(@usePostProcessing) @composer.reset() @composer.render( @scene2, @orthoCamera ) @composer.toScreen() @composer.reset() @composer.render( @scene, @camera ) for pass in @passes @composer.pass( pass ) @composer.toScreen() else @renderer.clear() @renderer.render(@scene, @camera) return @resize = ()=> w = window.innerWidth h = window.innerHeight @resolution.x = w @resolution.y = h if @renderer @camera.aspect = w / h @camera.updateProjectionMatrix() @renderer.setSize( w, h ) @renderer.setPixelRatio( window.devicePixelRatio ) @render(0) if @composer @composer.setSize( @renderer.domElement.width, @renderer.domElement.height ) return @initGUI = (gui)=> g = gui.addFolder('Camera') g.add(@camera,'fov',1,100).onChange(@resize) g.add(@camera.position,'x').listen() g.add(@camera.position,'y').listen() g.add(@camera.position,'z').listen() return module.exports = Stage3d
true
# # Stage3d for threejs & wagner with every basics you need + special system for clear alpha. # @author PI:NAME:<NAME>END_PI / PI:EMAIL:<EMAIL>END_PI / @Makio64 # Stage = require('makio/core/Stage') signals = require('signals') class Stage3d @camera = null @scene = null @renderer = null @isInit = false # postProcess with wagner @postProcessInitiated = false @usePostProcessing = false @passes = [] @isActivated = false @clearAuto = false @clearAlpha = 1 @models = {} @init = (options)=> if(@isInit) @setColorFromOption(options) @activate() return @onBeforeRenderer = new signals() @clearColor = if options.background then options.background else 0xFF0000 w = window.innerWidth h = window.innerHeight @resolution = new THREE.Vector2(w,h) @camera = new THREE.PerspectiveCamera( 50, w / h, 1, 1000000 ) @scene = new THREE.Scene() @scene2 = new THREE.Scene() @orthoCamera = new THREE.OrthographicCamera( - 0.5, 0.5, 0.5, - 0.5, 0, 1 ) @mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 1, 1 ), new THREE.MeshBasicMaterial({color:@clearColor,transparent:true,opacity:@clearAlpha}) ) @scene2.add( @mesh ) transparent = options.transparent||false antialias = options.antialias||false @renderer = new THREE.WebGLRenderer({alpha:transparent,antialias:antialias,preserveDrawingBuffer:false}) console.log @renderer @renderer.setPixelRatio( window.devicePixelRatio ) @renderer.domElement.className = 'three' @setColorFromOption(options) @renderer.setSize( w, h ) @isInit = true @activate() return @setClearColor = (value)=> @clearColor = value @mesh.material.color = @clearColor @renderer.setClearColor( @clearColor,1 ) return @setColorFromOption = (options)=> @clearAlpha = if options.clearAlpha == undefined then 1 else options.clearAlpha @renderer.setClearColor( parseInt(options.background), @clearAlpha ) return @activate = ()=> if(@isActivated) return @isActivated = true Stage.onUpdate.add(@render) Stage.onResize.add(@resize) document.body.appendChild(@renderer.domElement) return @desactivate = ()=> if(!@isActivated) return @isActivated = false Stage.onUpdate.remove(@render) Stage.onResize.remove(@resize) document.body.removeChild(@renderer.domElement) return @initPostProcessing = ()=> if(@postProcessInitiated) return console.log('WAGNER PostProcess') @postProcessInitiated = true @usePostProcessing = true @composer = new WAGNER.Composer( @renderer, {useRGBA: true} ) @composer.setSize( @renderer.domElement.width, @renderer.domElement.height ) return @add = (obj)=> @scene.add(obj) return @remove = (obj)=> @scene.remove(obj) return @removeAll = ()=> while @scene.children.length>0 @scene.remove(@scene.children[0]) return @addPass = (pass)=> @passes.push(pass) return @removePass = (pass)=> for i in [0...@passes.length] by 1 if(@passes[i]==pass) @passes.splice(i,1) break return @render = (dt)=> @renderer.autoClearColor = @clearColor @renderer.autoClear = @clearAuto @mesh.material.opacity = @clearAlpha if(@control) @control.update(dt) @onBeforeRenderer.dispatch() if(@usePostProcessing) @composer.reset() @composer.render( @scene2, @orthoCamera ) @composer.toScreen() @composer.reset() @composer.render( @scene, @camera ) for pass in @passes @composer.pass( pass ) @composer.toScreen() else @renderer.clear() @renderer.render(@scene, @camera) return @resize = ()=> w = window.innerWidth h = window.innerHeight @resolution.x = w @resolution.y = h if @renderer @camera.aspect = w / h @camera.updateProjectionMatrix() @renderer.setSize( w, h ) @renderer.setPixelRatio( window.devicePixelRatio ) @render(0) if @composer @composer.setSize( @renderer.domElement.width, @renderer.domElement.height ) return @initGUI = (gui)=> g = gui.addFolder('Camera') g.add(@camera,'fov',1,100).onChange(@resize) g.add(@camera.position,'x').listen() g.add(@camera.position,'y').listen() g.add(@camera.position,'z').listen() return module.exports = Stage3d
[ { "context": "text onto HTML canvas elements\n\nWritten in 2013 by Karl Naylor <kpn103@yahoo.com>\n\nTo the extent possible under ", "end": 106, "score": 0.9998911619186401, "start": 95, "tag": "NAME", "value": "Karl Naylor" }, { "context": " canvas elements\n\nWritten in 2013 by Karl Naylor <kpn103@yahoo.com>\n\nTo the extent possible under law, the author(s)", "end": 124, "score": 0.9999285936355591, "start": 108, "tag": "EMAIL", "value": "kpn103@yahoo.com" } ]
src/content/coffee/handywriteOnCanvas/graphemes/lines.coffee
karlorg/phonetify
1
### handywriteOnCanvas - renders handywrite text onto HTML canvas elements Written in 2013 by Karl Naylor <kpn103@yahoo.com> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. ### define ['../grapheme', '../boxes', '../geometry'], (Grapheme, boxes, geometry) -> 'use strict' graphemes = {} graphemes.classes = {} TAU = 2 * Math.PI # TAU is one full turn in radians lWidth = 1 shAngle = zhAngle = TAU / 3 dAngle = tAngle = - TAU / 12 ngAngle = nkAngle = TAU / 12 dLength = lWidth ayHeight = lWidth * 0.2 jHeight = lWidth * 0.8 shHeight = zhHeight = lWidth * 0.4 mWidth = lWidth nWidth = lWidth * 0.4 tLength = lWidth * 0.4 class Line extends Grapheme # subclasses should override `_endPoint` getKeywords: -> obj = super() obj.line = true return obj _endPoint: { x: 0, y: 0 } getBoundingBox: -> new boxes.BoundingBox( Math.min(0, @_endPoint.x), Math.min(0, @_endPoint.y), Math.max(0, @_endPoint.x), Math.max(0, @_endPoint.y)) getFinishPoint: -> { x: @_endPoint.x, y: @_endPoint.y } getEntryAngle: -> new geometry.Vector({x:0,y:0}, @_endPoint).angle() getExitAngle: -> new geometry.Vector({x:0,y:0}, @_endPoint).angle() render: (ctx) -> ctx.beginPath() ctx.moveTo(0, 0) ctx.lineTo(@_endPoint.x, @_endPoint.y) ctx.stroke() return graphemes.classes.ay = class AY extends Line _endPoint: # default value, may be modified by `decide()` x: 0 y: ayHeight constructor: -> super @_determined = false return _chooseAngle: (constraints) -> # `constraints` is an array of angles we want to avoid (because our # neighbours are entering/exiting us at these angles) candidates = [ { angle: 5 * TAU / 16, badness: 0 } { angle: 4 * TAU / 16, badness: 0 } { angle: 3 * TAU / 16, badness: 0 } ] for constraint in constraints for candidate in candidates delta = Math.abs(constraint - candidate.angle) badness = if delta == 0 then 100 else Math.min(100, 1 / delta) candidate.badness = Math.max(candidate.badness, badness) # add a mild artificial bias for the vertical line, as it is more # 'standard' candidates[1].badness -= 1 choice = candidates[0] for candidate in candidates[1..] when candidate.badness < choice.badness choice = candidate # now we have our choice, apply it @_endPoint = x: ayHeight * Math.cos(choice.angle) y: ayHeight * Math.sin(choice.angle) @_determined = true return decide: (force=false, fromLeft=false, fromRight=false) -> return if @_determined and not force if fromLeft or not @left if @right and not @right.getKeywords().circle? @right.decide(force, true, false) @_chooseAngle [@right.getEntryAngle()] return else @_chooseAngle [] return else # not fromLeft, left neighbour exists unless @left.getKeywords().circle? @left.decide(force, false, true) if fromRight or not @right or @right.getKeywords().circle? @_chooseAngle [@left.getExitAngle()] return else # both sides provide constraints @right.decide(force, true, false) @_chooseAngle [@left.getExitAngle(), @right.getEntryAngle()] return # shouldn't be reachable, but... @_determined = true return graphemes.classes.ch = class CH extends Line _endPoint: x: jHeight * Math.cos(shAngle) y: jHeight * Math.sin(shAngle) graphemes.classes.d = class D extends Line _endPoint: x: dLength * Math.cos(dAngle) y: dLength * Math.sin(dAngle) graphemes.classes.j = class J extends Line _endPoint: { x: 0, y: jHeight } graphemes.classes.m = class M extends Line _endPoint: { x: mWidth, y: 0 } graphemes.classes.n = class N extends Line _endPoint: { x: nWidth, y: 0 } graphemes.classes.ng = class NG extends Line _endPoint: x: nWidth * Math.cos(ngAngle) y: nWidth * Math.sin(ngAngle) graphemes.classes.nk = class NK extends Line _endPoint: x: mWidth * Math.cos(nkAngle) y: mWidth * Math.sin(nkAngle) graphemes.classes.sh = class SH extends Line _endPoint: x: shHeight * Math.cos(shAngle) y: shHeight * Math.sin(shAngle) graphemes.classes.t = class T extends Line _endPoint: x: tLength * Math.cos(tAngle) y: tLength * Math.sin(tAngle) graphemes.classes.zh = class ZH extends Line _endPoint: { x: 0, y: zhHeight } return graphemes
148848
### handywriteOnCanvas - renders handywrite text onto HTML canvas elements Written in 2013 by <NAME> <<EMAIL>> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. ### define ['../grapheme', '../boxes', '../geometry'], (Grapheme, boxes, geometry) -> 'use strict' graphemes = {} graphemes.classes = {} TAU = 2 * Math.PI # TAU is one full turn in radians lWidth = 1 shAngle = zhAngle = TAU / 3 dAngle = tAngle = - TAU / 12 ngAngle = nkAngle = TAU / 12 dLength = lWidth ayHeight = lWidth * 0.2 jHeight = lWidth * 0.8 shHeight = zhHeight = lWidth * 0.4 mWidth = lWidth nWidth = lWidth * 0.4 tLength = lWidth * 0.4 class Line extends Grapheme # subclasses should override `_endPoint` getKeywords: -> obj = super() obj.line = true return obj _endPoint: { x: 0, y: 0 } getBoundingBox: -> new boxes.BoundingBox( Math.min(0, @_endPoint.x), Math.min(0, @_endPoint.y), Math.max(0, @_endPoint.x), Math.max(0, @_endPoint.y)) getFinishPoint: -> { x: @_endPoint.x, y: @_endPoint.y } getEntryAngle: -> new geometry.Vector({x:0,y:0}, @_endPoint).angle() getExitAngle: -> new geometry.Vector({x:0,y:0}, @_endPoint).angle() render: (ctx) -> ctx.beginPath() ctx.moveTo(0, 0) ctx.lineTo(@_endPoint.x, @_endPoint.y) ctx.stroke() return graphemes.classes.ay = class AY extends Line _endPoint: # default value, may be modified by `decide()` x: 0 y: ayHeight constructor: -> super @_determined = false return _chooseAngle: (constraints) -> # `constraints` is an array of angles we want to avoid (because our # neighbours are entering/exiting us at these angles) candidates = [ { angle: 5 * TAU / 16, badness: 0 } { angle: 4 * TAU / 16, badness: 0 } { angle: 3 * TAU / 16, badness: 0 } ] for constraint in constraints for candidate in candidates delta = Math.abs(constraint - candidate.angle) badness = if delta == 0 then 100 else Math.min(100, 1 / delta) candidate.badness = Math.max(candidate.badness, badness) # add a mild artificial bias for the vertical line, as it is more # 'standard' candidates[1].badness -= 1 choice = candidates[0] for candidate in candidates[1..] when candidate.badness < choice.badness choice = candidate # now we have our choice, apply it @_endPoint = x: ayHeight * Math.cos(choice.angle) y: ayHeight * Math.sin(choice.angle) @_determined = true return decide: (force=false, fromLeft=false, fromRight=false) -> return if @_determined and not force if fromLeft or not @left if @right and not @right.getKeywords().circle? @right.decide(force, true, false) @_chooseAngle [@right.getEntryAngle()] return else @_chooseAngle [] return else # not fromLeft, left neighbour exists unless @left.getKeywords().circle? @left.decide(force, false, true) if fromRight or not @right or @right.getKeywords().circle? @_chooseAngle [@left.getExitAngle()] return else # both sides provide constraints @right.decide(force, true, false) @_chooseAngle [@left.getExitAngle(), @right.getEntryAngle()] return # shouldn't be reachable, but... @_determined = true return graphemes.classes.ch = class CH extends Line _endPoint: x: jHeight * Math.cos(shAngle) y: jHeight * Math.sin(shAngle) graphemes.classes.d = class D extends Line _endPoint: x: dLength * Math.cos(dAngle) y: dLength * Math.sin(dAngle) graphemes.classes.j = class J extends Line _endPoint: { x: 0, y: jHeight } graphemes.classes.m = class M extends Line _endPoint: { x: mWidth, y: 0 } graphemes.classes.n = class N extends Line _endPoint: { x: nWidth, y: 0 } graphemes.classes.ng = class NG extends Line _endPoint: x: nWidth * Math.cos(ngAngle) y: nWidth * Math.sin(ngAngle) graphemes.classes.nk = class NK extends Line _endPoint: x: mWidth * Math.cos(nkAngle) y: mWidth * Math.sin(nkAngle) graphemes.classes.sh = class SH extends Line _endPoint: x: shHeight * Math.cos(shAngle) y: shHeight * Math.sin(shAngle) graphemes.classes.t = class T extends Line _endPoint: x: tLength * Math.cos(tAngle) y: tLength * Math.sin(tAngle) graphemes.classes.zh = class ZH extends Line _endPoint: { x: 0, y: zhHeight } return graphemes
true
### handywriteOnCanvas - renders handywrite text onto HTML canvas elements Written in 2013 by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. ### define ['../grapheme', '../boxes', '../geometry'], (Grapheme, boxes, geometry) -> 'use strict' graphemes = {} graphemes.classes = {} TAU = 2 * Math.PI # TAU is one full turn in radians lWidth = 1 shAngle = zhAngle = TAU / 3 dAngle = tAngle = - TAU / 12 ngAngle = nkAngle = TAU / 12 dLength = lWidth ayHeight = lWidth * 0.2 jHeight = lWidth * 0.8 shHeight = zhHeight = lWidth * 0.4 mWidth = lWidth nWidth = lWidth * 0.4 tLength = lWidth * 0.4 class Line extends Grapheme # subclasses should override `_endPoint` getKeywords: -> obj = super() obj.line = true return obj _endPoint: { x: 0, y: 0 } getBoundingBox: -> new boxes.BoundingBox( Math.min(0, @_endPoint.x), Math.min(0, @_endPoint.y), Math.max(0, @_endPoint.x), Math.max(0, @_endPoint.y)) getFinishPoint: -> { x: @_endPoint.x, y: @_endPoint.y } getEntryAngle: -> new geometry.Vector({x:0,y:0}, @_endPoint).angle() getExitAngle: -> new geometry.Vector({x:0,y:0}, @_endPoint).angle() render: (ctx) -> ctx.beginPath() ctx.moveTo(0, 0) ctx.lineTo(@_endPoint.x, @_endPoint.y) ctx.stroke() return graphemes.classes.ay = class AY extends Line _endPoint: # default value, may be modified by `decide()` x: 0 y: ayHeight constructor: -> super @_determined = false return _chooseAngle: (constraints) -> # `constraints` is an array of angles we want to avoid (because our # neighbours are entering/exiting us at these angles) candidates = [ { angle: 5 * TAU / 16, badness: 0 } { angle: 4 * TAU / 16, badness: 0 } { angle: 3 * TAU / 16, badness: 0 } ] for constraint in constraints for candidate in candidates delta = Math.abs(constraint - candidate.angle) badness = if delta == 0 then 100 else Math.min(100, 1 / delta) candidate.badness = Math.max(candidate.badness, badness) # add a mild artificial bias for the vertical line, as it is more # 'standard' candidates[1].badness -= 1 choice = candidates[0] for candidate in candidates[1..] when candidate.badness < choice.badness choice = candidate # now we have our choice, apply it @_endPoint = x: ayHeight * Math.cos(choice.angle) y: ayHeight * Math.sin(choice.angle) @_determined = true return decide: (force=false, fromLeft=false, fromRight=false) -> return if @_determined and not force if fromLeft or not @left if @right and not @right.getKeywords().circle? @right.decide(force, true, false) @_chooseAngle [@right.getEntryAngle()] return else @_chooseAngle [] return else # not fromLeft, left neighbour exists unless @left.getKeywords().circle? @left.decide(force, false, true) if fromRight or not @right or @right.getKeywords().circle? @_chooseAngle [@left.getExitAngle()] return else # both sides provide constraints @right.decide(force, true, false) @_chooseAngle [@left.getExitAngle(), @right.getEntryAngle()] return # shouldn't be reachable, but... @_determined = true return graphemes.classes.ch = class CH extends Line _endPoint: x: jHeight * Math.cos(shAngle) y: jHeight * Math.sin(shAngle) graphemes.classes.d = class D extends Line _endPoint: x: dLength * Math.cos(dAngle) y: dLength * Math.sin(dAngle) graphemes.classes.j = class J extends Line _endPoint: { x: 0, y: jHeight } graphemes.classes.m = class M extends Line _endPoint: { x: mWidth, y: 0 } graphemes.classes.n = class N extends Line _endPoint: { x: nWidth, y: 0 } graphemes.classes.ng = class NG extends Line _endPoint: x: nWidth * Math.cos(ngAngle) y: nWidth * Math.sin(ngAngle) graphemes.classes.nk = class NK extends Line _endPoint: x: mWidth * Math.cos(nkAngle) y: mWidth * Math.sin(nkAngle) graphemes.classes.sh = class SH extends Line _endPoint: x: shHeight * Math.cos(shAngle) y: shHeight * Math.sin(shAngle) graphemes.classes.t = class T extends Line _endPoint: x: tLength * Math.cos(tAngle) y: tLength * Math.sin(tAngle) graphemes.classes.zh = class ZH extends Line _endPoint: { x: 0, y: zhHeight } return graphemes
[ { "context": "dules are consumed within other modules.\n# @author René Fermann\n###\n\n{default: Exports} = require '../eslint-plug", "end": 136, "score": 0.9998317956924438, "start": 124, "tag": "NAME", "value": "René Fermann" }, { "context": " versions of the function.\n # https://github.com/eslint/eslint/blob/v5.16.0/lib/util/glob-utils.js#L178-L", "end": 1111, "score": 0.7916120290756226, "start": 1105, "tag": "USERNAME", "value": "eslint" }, { "context": "il/glob-utils.js#L178-L280\n # https://github.com/eslint/eslint/blob/v5.2.0/lib/util/glob-util.js#L174-L26", "end": 1194, "score": 0.8793168663978577, "start": 1188, "tag": "USERNAME", "value": "eslint" } ]
src/rules/no-unused-modules.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileOverview Ensures that modules contain exports and/or all # modules are consumed within other modules. # @author René Fermann ### {default: Exports} = require '../eslint-plugin-import-export-map' {getFileExtensions} = require 'eslint-module-utils/ignore' {default: resolve} = require 'eslint-module-utils/resolve' {default: docsUrl} = require 'eslint-plugin-import/lib/docsUrl' {dirname, join} = require 'path' readPkgUp = require 'read-pkg-up' values = require 'object.values' includes = require 'array-includes' # eslint/lib/util/glob-util has been moved to eslint/lib/util/glob-utils with version 5.3 # and has been moved to eslint/lib/cli-engine/file-enumerator in version 6 try FileEnumerator = require('eslint/lib/cli-engine/file-enumerator').FileEnumerator listFilesToProcess = (src, extensions) -> e = new FileEnumerator extensions: extensions Array.from e.iterateFiles(src), ({filePath, ignored}) -> { ignored filename: filePath } catch e1 # Prevent passing invalid options (extensions array) to old versions of the function. # https://github.com/eslint/eslint/blob/v5.16.0/lib/util/glob-utils.js#L178-L280 # https://github.com/eslint/eslint/blob/v5.2.0/lib/util/glob-util.js#L174-L269 try originalListFilesToProcess = require('eslint/lib/util/glob-utils').listFilesToProcess listFilesToProcess = (src, extensions) -> originalListFilesToProcess src, extensions: extensions catch e2 originalListFilesToProcess = require('eslint/lib/util/glob-util').listFilesToProcess listFilesToProcess = (src, extensions) -> patterns = src.reduce( (carry, pattern) -> carry.concat( extensions.map (extension) -> if /\*\*|\*\./.test pattern pattern else "#{pattern}/**/*#{extension}" ) , src.slice() ) originalListFilesToProcess patterns EXPORT_DEFAULT_DECLARATION = 'ExportDefaultDeclaration' EXPORT_NAMED_DECLARATION = 'ExportNamedDeclaration' EXPORT_ALL_DECLARATION = 'ExportAllDeclaration' IMPORT_DECLARATION = 'ImportDeclaration' IMPORT_NAMESPACE_SPECIFIER = 'ImportNamespaceSpecifier' IMPORT_DEFAULT_SPECIFIER = 'ImportDefaultSpecifier' VARIABLE_DECLARATION = 'VariableDeclaration' FUNCTION_DECLARATION = 'FunctionDeclaration' CLASS_DECLARATION = 'ClassDeclaration' ASSIGNMENT_EXPRESSION = 'AssignmentExpression' IDENTIFIER = 'Identifier' DEFAULT = 'default' TYPE_ALIAS = 'TypeAlias' importList = new Map() exportList = new Map() ignoredFiles = new Set() filesOutsideSrc = new Set() isNodeModule = (path) -> /\/(node_modules)\//.test path ###* # read all files matching the patterns in src and ignoreExports # # return all files matching src pattern, which are not matching the ignoreExports pattern ### resolveFiles = (src, ignoreExports, context) -> extensions = Array.from getFileExtensions context.settings srcFiles = new Set() srcFileList = listFilesToProcess src, extensions # prepare list of ignored files ignoredFilesList = listFilesToProcess ignoreExports, extensions ignoredFilesList.forEach ({filename}) -> ignoredFiles.add filename # prepare list of source files, don't consider files from node_modules srcFileList .filter ({filename}) -> not isNodeModule filename .forEach ({filename}) -> srcFiles.add filename srcFiles ###* # parse all source files and build up 2 maps containing the existing imports and exports ### prepareImportsAndExports = (srcFiles, context) -> exportAll = new Map() srcFiles.forEach (file) -> exports = new Map() imports = new Map() currentExports = Exports.get file, context if currentExports { dependencies reexports imports: localImportList namespace } = currentExports # dependencies === export * from currentExportAll = new Set() dependencies.forEach (getDependency) -> dependency = getDependency() return if dependency is null currentExportAll.add dependency.path exportAll.set file, currentExportAll reexports.forEach (value, key) -> if key is DEFAULT exports.set IMPORT_DEFAULT_SPECIFIER, whereUsed: new Set() else exports.set key, whereUsed: new Set() reexport = value.getImport() return unless reexport localImport = imports.get reexport.path if value.local is DEFAULT currentValue = IMPORT_DEFAULT_SPECIFIER else currentValue = value.local unless typeof localImport is 'undefined' localImport = new Set [...localImport, currentValue] else localImport = new Set [currentValue] imports.set reexport.path, localImport localImportList.forEach (value, key) -> return if isNodeModule key imports.set key, value.importedSpecifiers importList.set file, imports # build up export list only, if file is not ignored return if ignoredFiles.has file namespace.forEach (value, key) -> if key is DEFAULT exports.set IMPORT_DEFAULT_SPECIFIER, whereUsed: new Set() else exports.set key, whereUsed: new Set() exports.set EXPORT_ALL_DECLARATION, whereUsed: new Set() exports.set IMPORT_NAMESPACE_SPECIFIER, whereUsed: new Set() exportList.set file, exports exportAll.forEach (value, key) -> value.forEach (val) -> currentExports = exportList.get val currentExport = currentExports.get EXPORT_ALL_DECLARATION currentExport.whereUsed.add key ###* # traverse through all imports and add the respective path to the whereUsed-list # of the corresponding export ### determineUsage = -> importList.forEach (listValue, listKey) -> listValue.forEach (value, key) -> exports = exportList.get key unless typeof exports is 'undefined' value.forEach (currentImport) -> if currentImport is IMPORT_NAMESPACE_SPECIFIER specifier = IMPORT_NAMESPACE_SPECIFIER else if currentImport is IMPORT_DEFAULT_SPECIFIER specifier = IMPORT_DEFAULT_SPECIFIER else specifier = currentImport unless typeof specifier is 'undefined' exportStatement = exports.get specifier unless typeof exportStatement is 'undefined' {whereUsed} = exportStatement whereUsed.add listKey exports.set specifier, {whereUsed} getSrc = (src) -> return src if src [process.cwd()] ###* # prepare the lists of existing imports and exports - should only be executed once at # the start of a new eslint run ### srcFiles = null lastPrepareKey = null doPreparation = (src, ignoreExports, context) -> prepareKey = JSON.stringify( src: (src or []).sort() ignoreExports: (ignoreExports or []).sort() extensions: Array.from(getFileExtensions context.settings).sort() ) return if prepareKey is lastPrepareKey importList.clear() exportList.clear() ignoredFiles.clear() filesOutsideSrc.clear() srcFiles = resolveFiles getSrc(src), ignoreExports, context prepareImportsAndExports srcFiles, context determineUsage() lastPrepareKey = prepareKey newNamespaceImportExists = (specifiers) -> specifiers.some ({type}) -> type is IMPORT_NAMESPACE_SPECIFIER newDefaultImportExists = (specifiers) -> specifiers.some ({type}) -> type is IMPORT_DEFAULT_SPECIFIER fileIsInPkg = (file) -> {path, pkg} = readPkgUp.sync cwd: file, normalize: no basePath = dirname path checkPkgFieldString = (pkgField) -> return yes if join(basePath, pkgField) is file checkPkgFieldObject = (pkgField) -> pkgFieldFiles = values(pkgField).map (value) -> join basePath, value return yes if includes pkgFieldFiles, file checkPkgField = (pkgField) -> return checkPkgFieldString pkgField if typeof pkgField is 'string' return checkPkgFieldObject pkgField if typeof pkgField is 'object' return no if pkg.private is yes if pkg.bin then return yes if checkPkgField pkg.bin if pkg.browser then return yes if checkPkgField pkg.browser if pkg.main then return yes if checkPkgFieldString pkg.main no module.exports = meta: docs: url: docsUrl 'no-unused-modules' schema: [ properties: src: description: 'files/paths to be analyzed (only for unused exports)' type: 'array' minItems: 1 items: type: 'string' minLength: 1 ignoreExports: description: 'files/paths for which unused exports will not be reported (e.g module entry points)' type: 'array' minItems: 1 items: type: 'string' minLength: 1 missingExports: description: 'report modules without any exports' type: 'boolean' unusedExports: description: 'report exports without any usage' type: 'boolean' not: properties: unusedExports: enum: [no] missingExports: enum: [no] anyOf: [ not: properties: unusedExports: enum: [yes] required: ['missingExports'] , not: properties: missingExports: enum: [yes] required: ['unusedExports'] , properties: unusedExports: enum: [yes] required: ['unusedExports'] , properties: missingExports: enum: [yes] required: ['missingExports'] ] ] create: (context) -> { src ignoreExports = [] missingExports unusedExports } = context.options[0] or {} if unusedExports then doPreparation src, ignoreExports, context file = context.getFilename() checkExportPresence = (node) -> return unless missingExports return if ignoredFiles.has file exportCount = exportList.get file exportAll = exportCount.get EXPORT_ALL_DECLARATION namespaceImports = exportCount.get IMPORT_NAMESPACE_SPECIFIER exportCount.delete EXPORT_ALL_DECLARATION exportCount.delete IMPORT_NAMESPACE_SPECIFIER if exportCount.size < 1 # node.body[0] === 'undefined' only happens, if everything is commented out in the file # being linted context.report( if node.body[0] then node.body[0] else node 'No exports found' ) exportCount.set EXPORT_ALL_DECLARATION, exportAll exportCount.set IMPORT_NAMESPACE_SPECIFIER, namespaceImports checkUsage = (node, exportedValue) -> return unless unusedExports return if ignoredFiles.has file return if fileIsInPkg file return if filesOutsideSrc.has file # make sure file to be linted is included in source files unless srcFiles.has file srcFiles = resolveFiles getSrc(src), ignoreExports, context unless srcFiles.has file filesOutsideSrc.add file return exports = exportList.get file # special case: export * from exportAll = exports.get EXPORT_ALL_DECLARATION if ( typeof exportAll isnt 'undefined' and exportedValue isnt IMPORT_DEFAULT_SPECIFIER ) return if exportAll.whereUsed.size > 0 # special case: namespace import namespaceImports = exports.get IMPORT_NAMESPACE_SPECIFIER unless typeof namespaceImports is 'undefined' return if namespaceImports.whereUsed.size > 0 exportStatement = exports.get exportedValue value = if exportedValue is IMPORT_DEFAULT_SPECIFIER DEFAULT else exportedValue unless typeof exportStatement is 'undefined' if exportStatement.whereUsed.size < 1 context.report( node "exported declaration '#{value}' not used within other modules" ) else context.report( node "exported declaration '#{value}' not used within other modules" ) ###* # only useful for tools like vscode-eslint # # update lists of existing exports during runtime ### updateExportUsage = (node) -> return if ignoredFiles.has file exports = exportList.get file # new module has been created during runtime # include it in further processing if typeof exports is 'undefined' then exports = new Map() newExports = new Map() newExportIdentifiers = new Set() node.body.forEach ({type, declaration, specifiers}) -> if type is EXPORT_DEFAULT_DECLARATION newExportIdentifiers.add IMPORT_DEFAULT_SPECIFIER if type is EXPORT_NAMED_DECLARATION if specifiers.length > 0 specifiers.forEach (specifier) -> if specifier.exported newExportIdentifiers.add specifier.exported.name if declaration if declaration.type in [ FUNCTION_DECLARATION CLASS_DECLARATION TYPE_ALIAS ] newExportIdentifiers.add declaration.id.name if declaration.type is VARIABLE_DECLARATION declaration.declarations.forEach ({id}) -> newExportIdentifiers.add id.name if ( declaration.type is ASSIGNMENT_EXPRESSION and declaration.left.type is IDENTIFIER ) newExportIdentifiers.add declaration.left.name # old exports exist within list of new exports identifiers: add to map of new exports exports.forEach (value, key) -> if newExportIdentifiers.has key then newExports.set key, value # new export identifiers added: add to map of new exports newExportIdentifiers.forEach (key) -> unless exports.has key then newExports.set key, whereUsed: new Set() # preserve information about namespace imports exportAll = exports.get EXPORT_ALL_DECLARATION namespaceImports = exports.get IMPORT_NAMESPACE_SPECIFIER if typeof namespaceImports is 'undefined' namespaceImports = whereUsed: new Set() newExports.set EXPORT_ALL_DECLARATION, exportAll newExports.set IMPORT_NAMESPACE_SPECIFIER, namespaceImports exportList.set file, newExports ###* # only useful for tools like vscode-eslint # # update lists of existing imports during runtime ### updateImportUsage = (node) -> return unless unusedExports oldImportPaths = importList.get file if typeof oldImportPaths is 'undefined' then oldImportPaths = new Map() oldNamespaceImports = new Set() newNamespaceImports = new Set() oldExportAll = new Set() newExportAll = new Set() oldDefaultImports = new Set() newDefaultImports = new Set() oldImports = new Map() newImports = new Map() oldImportPaths.forEach (value, key) -> if value.has EXPORT_ALL_DECLARATION then oldExportAll.add key if value.has IMPORT_NAMESPACE_SPECIFIER then oldNamespaceImports.add key if value.has IMPORT_DEFAULT_SPECIFIER then oldDefaultImports.add key value.forEach (val) -> if ( val isnt IMPORT_NAMESPACE_SPECIFIER and val isnt IMPORT_DEFAULT_SPECIFIER ) oldImports.set val, key node.body.forEach (astNode) -> # support for export { value } from 'module' if astNode.type is EXPORT_NAMED_DECLARATION if astNode.source resolvedPath = resolve( astNode.source.raw.replace /('|")/g, '' context ) astNode.specifiers.forEach (specifier) -> if specifier.exported.name is DEFAULT name = IMPORT_DEFAULT_SPECIFIER else name = specifier.local.name newImports.set name, resolvedPath if astNode.type is EXPORT_ALL_DECLARATION resolvedPath = resolve( astNode.source.raw.replace /('|")/g, '' context ) newExportAll.add resolvedPath if astNode.type is IMPORT_DECLARATION resolvedPath = resolve( astNode.source.raw.replace /('|")/g, '' context ) return unless resolvedPath return if isNodeModule resolvedPath if newNamespaceImportExists astNode.specifiers newNamespaceImports.add resolvedPath if newDefaultImportExists astNode.specifiers newDefaultImports.add resolvedPath astNode.specifiers.forEach (specifier) -> return if specifier.type in [ IMPORT_DEFAULT_SPECIFIER IMPORT_NAMESPACE_SPECIFIER ] newImports.set specifier.imported.name, resolvedPath newExportAll.forEach (value) -> unless oldExportAll.has value imports = oldImportPaths.get value if typeof imports is 'undefined' then imports = new Set() imports.add EXPORT_ALL_DECLARATION oldImportPaths.set value, imports exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get EXPORT_ALL_DECLARATION else exports = new Map() exportList.set value, exports unless typeof currentExport is 'undefined' currentExport.whereUsed.add file else whereUsed = new Set() whereUsed.add file exports.set EXPORT_ALL_DECLARATION, {whereUsed} oldExportAll.forEach (value) -> unless newExportAll.has value imports = oldImportPaths.get value imports.delete EXPORT_ALL_DECLARATION exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get EXPORT_ALL_DECLARATION unless typeof currentExport is 'undefined' currentExport.whereUsed.delete file newDefaultImports.forEach (value) -> unless oldDefaultImports.has value imports = oldImportPaths.get value if typeof imports is 'undefined' then imports = new Set() imports.add IMPORT_DEFAULT_SPECIFIER oldImportPaths.set value, imports exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get IMPORT_DEFAULT_SPECIFIER else exports = new Map() exportList.set value, exports unless typeof currentExport is 'undefined' currentExport.whereUsed.add file else whereUsed = new Set() whereUsed.add file exports.set IMPORT_DEFAULT_SPECIFIER, {whereUsed} oldDefaultImports.forEach (value) -> unless newDefaultImports.has value imports = oldImportPaths.get value imports.delete IMPORT_DEFAULT_SPECIFIER exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get IMPORT_DEFAULT_SPECIFIER unless typeof currentExport is 'undefined' currentExport.whereUsed.delete file newNamespaceImports.forEach (value) -> unless oldNamespaceImports.has value imports = oldImportPaths.get value if typeof imports is 'undefined' then imports = new Set() imports.add IMPORT_NAMESPACE_SPECIFIER oldImportPaths.set value, imports exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get IMPORT_NAMESPACE_SPECIFIER else exports = new Map() exportList.set value, exports unless typeof currentExport is 'undefined' currentExport.whereUsed.add file else whereUsed = new Set() whereUsed.add file exports.set IMPORT_NAMESPACE_SPECIFIER, {whereUsed} oldNamespaceImports.forEach (value) -> unless newNamespaceImports.has value imports = oldImportPaths.get value imports.delete IMPORT_NAMESPACE_SPECIFIER exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get IMPORT_NAMESPACE_SPECIFIER unless typeof currentExport is 'undefined' currentExport.whereUsed.delete file newImports.forEach (value, key) -> unless oldImports.has key imports = oldImportPaths.get value if typeof imports is 'undefined' then imports = new Set() imports.add key oldImportPaths.set value, imports exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get key else exports = new Map() exportList.set value, exports unless typeof currentExport is 'undefined' currentExport.whereUsed.add file else whereUsed = new Set() whereUsed.add file exports.set key, {whereUsed} oldImports.forEach (value, key) -> unless newImports.has key imports = oldImportPaths.get value imports.delete key exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get key unless typeof currentExport is 'undefined' currentExport.whereUsed.delete file 'Program:exit': (node) -> updateExportUsage node updateImportUsage node checkExportPresence node ExportDefaultDeclaration: (node) -> checkUsage node, IMPORT_DEFAULT_SPECIFIER ExportNamedDeclaration: (node) -> node.specifiers.forEach (specifier) -> checkUsage node, specifier.exported.name if node.declaration if node.declaration.type in [ FUNCTION_DECLARATION CLASS_DECLARATION TYPE_ALIAS ] checkUsage node, node.declaration.id.name if node.declaration.type is VARIABLE_DECLARATION node.declaration.declarations.forEach (declaration) -> checkUsage node, declaration.id.name if ( node.declaration.type is ASSIGNMENT_EXPRESSION and node.declaration.left.type is IDENTIFIER ) checkUsage node, node.declaration.left.name
188898
###* # @fileOverview Ensures that modules contain exports and/or all # modules are consumed within other modules. # @author <NAME> ### {default: Exports} = require '../eslint-plugin-import-export-map' {getFileExtensions} = require 'eslint-module-utils/ignore' {default: resolve} = require 'eslint-module-utils/resolve' {default: docsUrl} = require 'eslint-plugin-import/lib/docsUrl' {dirname, join} = require 'path' readPkgUp = require 'read-pkg-up' values = require 'object.values' includes = require 'array-includes' # eslint/lib/util/glob-util has been moved to eslint/lib/util/glob-utils with version 5.3 # and has been moved to eslint/lib/cli-engine/file-enumerator in version 6 try FileEnumerator = require('eslint/lib/cli-engine/file-enumerator').FileEnumerator listFilesToProcess = (src, extensions) -> e = new FileEnumerator extensions: extensions Array.from e.iterateFiles(src), ({filePath, ignored}) -> { ignored filename: filePath } catch e1 # Prevent passing invalid options (extensions array) to old versions of the function. # https://github.com/eslint/eslint/blob/v5.16.0/lib/util/glob-utils.js#L178-L280 # https://github.com/eslint/eslint/blob/v5.2.0/lib/util/glob-util.js#L174-L269 try originalListFilesToProcess = require('eslint/lib/util/glob-utils').listFilesToProcess listFilesToProcess = (src, extensions) -> originalListFilesToProcess src, extensions: extensions catch e2 originalListFilesToProcess = require('eslint/lib/util/glob-util').listFilesToProcess listFilesToProcess = (src, extensions) -> patterns = src.reduce( (carry, pattern) -> carry.concat( extensions.map (extension) -> if /\*\*|\*\./.test pattern pattern else "#{pattern}/**/*#{extension}" ) , src.slice() ) originalListFilesToProcess patterns EXPORT_DEFAULT_DECLARATION = 'ExportDefaultDeclaration' EXPORT_NAMED_DECLARATION = 'ExportNamedDeclaration' EXPORT_ALL_DECLARATION = 'ExportAllDeclaration' IMPORT_DECLARATION = 'ImportDeclaration' IMPORT_NAMESPACE_SPECIFIER = 'ImportNamespaceSpecifier' IMPORT_DEFAULT_SPECIFIER = 'ImportDefaultSpecifier' VARIABLE_DECLARATION = 'VariableDeclaration' FUNCTION_DECLARATION = 'FunctionDeclaration' CLASS_DECLARATION = 'ClassDeclaration' ASSIGNMENT_EXPRESSION = 'AssignmentExpression' IDENTIFIER = 'Identifier' DEFAULT = 'default' TYPE_ALIAS = 'TypeAlias' importList = new Map() exportList = new Map() ignoredFiles = new Set() filesOutsideSrc = new Set() isNodeModule = (path) -> /\/(node_modules)\//.test path ###* # read all files matching the patterns in src and ignoreExports # # return all files matching src pattern, which are not matching the ignoreExports pattern ### resolveFiles = (src, ignoreExports, context) -> extensions = Array.from getFileExtensions context.settings srcFiles = new Set() srcFileList = listFilesToProcess src, extensions # prepare list of ignored files ignoredFilesList = listFilesToProcess ignoreExports, extensions ignoredFilesList.forEach ({filename}) -> ignoredFiles.add filename # prepare list of source files, don't consider files from node_modules srcFileList .filter ({filename}) -> not isNodeModule filename .forEach ({filename}) -> srcFiles.add filename srcFiles ###* # parse all source files and build up 2 maps containing the existing imports and exports ### prepareImportsAndExports = (srcFiles, context) -> exportAll = new Map() srcFiles.forEach (file) -> exports = new Map() imports = new Map() currentExports = Exports.get file, context if currentExports { dependencies reexports imports: localImportList namespace } = currentExports # dependencies === export * from currentExportAll = new Set() dependencies.forEach (getDependency) -> dependency = getDependency() return if dependency is null currentExportAll.add dependency.path exportAll.set file, currentExportAll reexports.forEach (value, key) -> if key is DEFAULT exports.set IMPORT_DEFAULT_SPECIFIER, whereUsed: new Set() else exports.set key, whereUsed: new Set() reexport = value.getImport() return unless reexport localImport = imports.get reexport.path if value.local is DEFAULT currentValue = IMPORT_DEFAULT_SPECIFIER else currentValue = value.local unless typeof localImport is 'undefined' localImport = new Set [...localImport, currentValue] else localImport = new Set [currentValue] imports.set reexport.path, localImport localImportList.forEach (value, key) -> return if isNodeModule key imports.set key, value.importedSpecifiers importList.set file, imports # build up export list only, if file is not ignored return if ignoredFiles.has file namespace.forEach (value, key) -> if key is DEFAULT exports.set IMPORT_DEFAULT_SPECIFIER, whereUsed: new Set() else exports.set key, whereUsed: new Set() exports.set EXPORT_ALL_DECLARATION, whereUsed: new Set() exports.set IMPORT_NAMESPACE_SPECIFIER, whereUsed: new Set() exportList.set file, exports exportAll.forEach (value, key) -> value.forEach (val) -> currentExports = exportList.get val currentExport = currentExports.get EXPORT_ALL_DECLARATION currentExport.whereUsed.add key ###* # traverse through all imports and add the respective path to the whereUsed-list # of the corresponding export ### determineUsage = -> importList.forEach (listValue, listKey) -> listValue.forEach (value, key) -> exports = exportList.get key unless typeof exports is 'undefined' value.forEach (currentImport) -> if currentImport is IMPORT_NAMESPACE_SPECIFIER specifier = IMPORT_NAMESPACE_SPECIFIER else if currentImport is IMPORT_DEFAULT_SPECIFIER specifier = IMPORT_DEFAULT_SPECIFIER else specifier = currentImport unless typeof specifier is 'undefined' exportStatement = exports.get specifier unless typeof exportStatement is 'undefined' {whereUsed} = exportStatement whereUsed.add listKey exports.set specifier, {whereUsed} getSrc = (src) -> return src if src [process.cwd()] ###* # prepare the lists of existing imports and exports - should only be executed once at # the start of a new eslint run ### srcFiles = null lastPrepareKey = null doPreparation = (src, ignoreExports, context) -> prepareKey = JSON.stringify( src: (src or []).sort() ignoreExports: (ignoreExports or []).sort() extensions: Array.from(getFileExtensions context.settings).sort() ) return if prepareKey is lastPrepareKey importList.clear() exportList.clear() ignoredFiles.clear() filesOutsideSrc.clear() srcFiles = resolveFiles getSrc(src), ignoreExports, context prepareImportsAndExports srcFiles, context determineUsage() lastPrepareKey = prepareKey newNamespaceImportExists = (specifiers) -> specifiers.some ({type}) -> type is IMPORT_NAMESPACE_SPECIFIER newDefaultImportExists = (specifiers) -> specifiers.some ({type}) -> type is IMPORT_DEFAULT_SPECIFIER fileIsInPkg = (file) -> {path, pkg} = readPkgUp.sync cwd: file, normalize: no basePath = dirname path checkPkgFieldString = (pkgField) -> return yes if join(basePath, pkgField) is file checkPkgFieldObject = (pkgField) -> pkgFieldFiles = values(pkgField).map (value) -> join basePath, value return yes if includes pkgFieldFiles, file checkPkgField = (pkgField) -> return checkPkgFieldString pkgField if typeof pkgField is 'string' return checkPkgFieldObject pkgField if typeof pkgField is 'object' return no if pkg.private is yes if pkg.bin then return yes if checkPkgField pkg.bin if pkg.browser then return yes if checkPkgField pkg.browser if pkg.main then return yes if checkPkgFieldString pkg.main no module.exports = meta: docs: url: docsUrl 'no-unused-modules' schema: [ properties: src: description: 'files/paths to be analyzed (only for unused exports)' type: 'array' minItems: 1 items: type: 'string' minLength: 1 ignoreExports: description: 'files/paths for which unused exports will not be reported (e.g module entry points)' type: 'array' minItems: 1 items: type: 'string' minLength: 1 missingExports: description: 'report modules without any exports' type: 'boolean' unusedExports: description: 'report exports without any usage' type: 'boolean' not: properties: unusedExports: enum: [no] missingExports: enum: [no] anyOf: [ not: properties: unusedExports: enum: [yes] required: ['missingExports'] , not: properties: missingExports: enum: [yes] required: ['unusedExports'] , properties: unusedExports: enum: [yes] required: ['unusedExports'] , properties: missingExports: enum: [yes] required: ['missingExports'] ] ] create: (context) -> { src ignoreExports = [] missingExports unusedExports } = context.options[0] or {} if unusedExports then doPreparation src, ignoreExports, context file = context.getFilename() checkExportPresence = (node) -> return unless missingExports return if ignoredFiles.has file exportCount = exportList.get file exportAll = exportCount.get EXPORT_ALL_DECLARATION namespaceImports = exportCount.get IMPORT_NAMESPACE_SPECIFIER exportCount.delete EXPORT_ALL_DECLARATION exportCount.delete IMPORT_NAMESPACE_SPECIFIER if exportCount.size < 1 # node.body[0] === 'undefined' only happens, if everything is commented out in the file # being linted context.report( if node.body[0] then node.body[0] else node 'No exports found' ) exportCount.set EXPORT_ALL_DECLARATION, exportAll exportCount.set IMPORT_NAMESPACE_SPECIFIER, namespaceImports checkUsage = (node, exportedValue) -> return unless unusedExports return if ignoredFiles.has file return if fileIsInPkg file return if filesOutsideSrc.has file # make sure file to be linted is included in source files unless srcFiles.has file srcFiles = resolveFiles getSrc(src), ignoreExports, context unless srcFiles.has file filesOutsideSrc.add file return exports = exportList.get file # special case: export * from exportAll = exports.get EXPORT_ALL_DECLARATION if ( typeof exportAll isnt 'undefined' and exportedValue isnt IMPORT_DEFAULT_SPECIFIER ) return if exportAll.whereUsed.size > 0 # special case: namespace import namespaceImports = exports.get IMPORT_NAMESPACE_SPECIFIER unless typeof namespaceImports is 'undefined' return if namespaceImports.whereUsed.size > 0 exportStatement = exports.get exportedValue value = if exportedValue is IMPORT_DEFAULT_SPECIFIER DEFAULT else exportedValue unless typeof exportStatement is 'undefined' if exportStatement.whereUsed.size < 1 context.report( node "exported declaration '#{value}' not used within other modules" ) else context.report( node "exported declaration '#{value}' not used within other modules" ) ###* # only useful for tools like vscode-eslint # # update lists of existing exports during runtime ### updateExportUsage = (node) -> return if ignoredFiles.has file exports = exportList.get file # new module has been created during runtime # include it in further processing if typeof exports is 'undefined' then exports = new Map() newExports = new Map() newExportIdentifiers = new Set() node.body.forEach ({type, declaration, specifiers}) -> if type is EXPORT_DEFAULT_DECLARATION newExportIdentifiers.add IMPORT_DEFAULT_SPECIFIER if type is EXPORT_NAMED_DECLARATION if specifiers.length > 0 specifiers.forEach (specifier) -> if specifier.exported newExportIdentifiers.add specifier.exported.name if declaration if declaration.type in [ FUNCTION_DECLARATION CLASS_DECLARATION TYPE_ALIAS ] newExportIdentifiers.add declaration.id.name if declaration.type is VARIABLE_DECLARATION declaration.declarations.forEach ({id}) -> newExportIdentifiers.add id.name if ( declaration.type is ASSIGNMENT_EXPRESSION and declaration.left.type is IDENTIFIER ) newExportIdentifiers.add declaration.left.name # old exports exist within list of new exports identifiers: add to map of new exports exports.forEach (value, key) -> if newExportIdentifiers.has key then newExports.set key, value # new export identifiers added: add to map of new exports newExportIdentifiers.forEach (key) -> unless exports.has key then newExports.set key, whereUsed: new Set() # preserve information about namespace imports exportAll = exports.get EXPORT_ALL_DECLARATION namespaceImports = exports.get IMPORT_NAMESPACE_SPECIFIER if typeof namespaceImports is 'undefined' namespaceImports = whereUsed: new Set() newExports.set EXPORT_ALL_DECLARATION, exportAll newExports.set IMPORT_NAMESPACE_SPECIFIER, namespaceImports exportList.set file, newExports ###* # only useful for tools like vscode-eslint # # update lists of existing imports during runtime ### updateImportUsage = (node) -> return unless unusedExports oldImportPaths = importList.get file if typeof oldImportPaths is 'undefined' then oldImportPaths = new Map() oldNamespaceImports = new Set() newNamespaceImports = new Set() oldExportAll = new Set() newExportAll = new Set() oldDefaultImports = new Set() newDefaultImports = new Set() oldImports = new Map() newImports = new Map() oldImportPaths.forEach (value, key) -> if value.has EXPORT_ALL_DECLARATION then oldExportAll.add key if value.has IMPORT_NAMESPACE_SPECIFIER then oldNamespaceImports.add key if value.has IMPORT_DEFAULT_SPECIFIER then oldDefaultImports.add key value.forEach (val) -> if ( val isnt IMPORT_NAMESPACE_SPECIFIER and val isnt IMPORT_DEFAULT_SPECIFIER ) oldImports.set val, key node.body.forEach (astNode) -> # support for export { value } from 'module' if astNode.type is EXPORT_NAMED_DECLARATION if astNode.source resolvedPath = resolve( astNode.source.raw.replace /('|")/g, '' context ) astNode.specifiers.forEach (specifier) -> if specifier.exported.name is DEFAULT name = IMPORT_DEFAULT_SPECIFIER else name = specifier.local.name newImports.set name, resolvedPath if astNode.type is EXPORT_ALL_DECLARATION resolvedPath = resolve( astNode.source.raw.replace /('|")/g, '' context ) newExportAll.add resolvedPath if astNode.type is IMPORT_DECLARATION resolvedPath = resolve( astNode.source.raw.replace /('|")/g, '' context ) return unless resolvedPath return if isNodeModule resolvedPath if newNamespaceImportExists astNode.specifiers newNamespaceImports.add resolvedPath if newDefaultImportExists astNode.specifiers newDefaultImports.add resolvedPath astNode.specifiers.forEach (specifier) -> return if specifier.type in [ IMPORT_DEFAULT_SPECIFIER IMPORT_NAMESPACE_SPECIFIER ] newImports.set specifier.imported.name, resolvedPath newExportAll.forEach (value) -> unless oldExportAll.has value imports = oldImportPaths.get value if typeof imports is 'undefined' then imports = new Set() imports.add EXPORT_ALL_DECLARATION oldImportPaths.set value, imports exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get EXPORT_ALL_DECLARATION else exports = new Map() exportList.set value, exports unless typeof currentExport is 'undefined' currentExport.whereUsed.add file else whereUsed = new Set() whereUsed.add file exports.set EXPORT_ALL_DECLARATION, {whereUsed} oldExportAll.forEach (value) -> unless newExportAll.has value imports = oldImportPaths.get value imports.delete EXPORT_ALL_DECLARATION exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get EXPORT_ALL_DECLARATION unless typeof currentExport is 'undefined' currentExport.whereUsed.delete file newDefaultImports.forEach (value) -> unless oldDefaultImports.has value imports = oldImportPaths.get value if typeof imports is 'undefined' then imports = new Set() imports.add IMPORT_DEFAULT_SPECIFIER oldImportPaths.set value, imports exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get IMPORT_DEFAULT_SPECIFIER else exports = new Map() exportList.set value, exports unless typeof currentExport is 'undefined' currentExport.whereUsed.add file else whereUsed = new Set() whereUsed.add file exports.set IMPORT_DEFAULT_SPECIFIER, {whereUsed} oldDefaultImports.forEach (value) -> unless newDefaultImports.has value imports = oldImportPaths.get value imports.delete IMPORT_DEFAULT_SPECIFIER exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get IMPORT_DEFAULT_SPECIFIER unless typeof currentExport is 'undefined' currentExport.whereUsed.delete file newNamespaceImports.forEach (value) -> unless oldNamespaceImports.has value imports = oldImportPaths.get value if typeof imports is 'undefined' then imports = new Set() imports.add IMPORT_NAMESPACE_SPECIFIER oldImportPaths.set value, imports exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get IMPORT_NAMESPACE_SPECIFIER else exports = new Map() exportList.set value, exports unless typeof currentExport is 'undefined' currentExport.whereUsed.add file else whereUsed = new Set() whereUsed.add file exports.set IMPORT_NAMESPACE_SPECIFIER, {whereUsed} oldNamespaceImports.forEach (value) -> unless newNamespaceImports.has value imports = oldImportPaths.get value imports.delete IMPORT_NAMESPACE_SPECIFIER exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get IMPORT_NAMESPACE_SPECIFIER unless typeof currentExport is 'undefined' currentExport.whereUsed.delete file newImports.forEach (value, key) -> unless oldImports.has key imports = oldImportPaths.get value if typeof imports is 'undefined' then imports = new Set() imports.add key oldImportPaths.set value, imports exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get key else exports = new Map() exportList.set value, exports unless typeof currentExport is 'undefined' currentExport.whereUsed.add file else whereUsed = new Set() whereUsed.add file exports.set key, {whereUsed} oldImports.forEach (value, key) -> unless newImports.has key imports = oldImportPaths.get value imports.delete key exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get key unless typeof currentExport is 'undefined' currentExport.whereUsed.delete file 'Program:exit': (node) -> updateExportUsage node updateImportUsage node checkExportPresence node ExportDefaultDeclaration: (node) -> checkUsage node, IMPORT_DEFAULT_SPECIFIER ExportNamedDeclaration: (node) -> node.specifiers.forEach (specifier) -> checkUsage node, specifier.exported.name if node.declaration if node.declaration.type in [ FUNCTION_DECLARATION CLASS_DECLARATION TYPE_ALIAS ] checkUsage node, node.declaration.id.name if node.declaration.type is VARIABLE_DECLARATION node.declaration.declarations.forEach (declaration) -> checkUsage node, declaration.id.name if ( node.declaration.type is ASSIGNMENT_EXPRESSION and node.declaration.left.type is IDENTIFIER ) checkUsage node, node.declaration.left.name
true
###* # @fileOverview Ensures that modules contain exports and/or all # modules are consumed within other modules. # @author PI:NAME:<NAME>END_PI ### {default: Exports} = require '../eslint-plugin-import-export-map' {getFileExtensions} = require 'eslint-module-utils/ignore' {default: resolve} = require 'eslint-module-utils/resolve' {default: docsUrl} = require 'eslint-plugin-import/lib/docsUrl' {dirname, join} = require 'path' readPkgUp = require 'read-pkg-up' values = require 'object.values' includes = require 'array-includes' # eslint/lib/util/glob-util has been moved to eslint/lib/util/glob-utils with version 5.3 # and has been moved to eslint/lib/cli-engine/file-enumerator in version 6 try FileEnumerator = require('eslint/lib/cli-engine/file-enumerator').FileEnumerator listFilesToProcess = (src, extensions) -> e = new FileEnumerator extensions: extensions Array.from e.iterateFiles(src), ({filePath, ignored}) -> { ignored filename: filePath } catch e1 # Prevent passing invalid options (extensions array) to old versions of the function. # https://github.com/eslint/eslint/blob/v5.16.0/lib/util/glob-utils.js#L178-L280 # https://github.com/eslint/eslint/blob/v5.2.0/lib/util/glob-util.js#L174-L269 try originalListFilesToProcess = require('eslint/lib/util/glob-utils').listFilesToProcess listFilesToProcess = (src, extensions) -> originalListFilesToProcess src, extensions: extensions catch e2 originalListFilesToProcess = require('eslint/lib/util/glob-util').listFilesToProcess listFilesToProcess = (src, extensions) -> patterns = src.reduce( (carry, pattern) -> carry.concat( extensions.map (extension) -> if /\*\*|\*\./.test pattern pattern else "#{pattern}/**/*#{extension}" ) , src.slice() ) originalListFilesToProcess patterns EXPORT_DEFAULT_DECLARATION = 'ExportDefaultDeclaration' EXPORT_NAMED_DECLARATION = 'ExportNamedDeclaration' EXPORT_ALL_DECLARATION = 'ExportAllDeclaration' IMPORT_DECLARATION = 'ImportDeclaration' IMPORT_NAMESPACE_SPECIFIER = 'ImportNamespaceSpecifier' IMPORT_DEFAULT_SPECIFIER = 'ImportDefaultSpecifier' VARIABLE_DECLARATION = 'VariableDeclaration' FUNCTION_DECLARATION = 'FunctionDeclaration' CLASS_DECLARATION = 'ClassDeclaration' ASSIGNMENT_EXPRESSION = 'AssignmentExpression' IDENTIFIER = 'Identifier' DEFAULT = 'default' TYPE_ALIAS = 'TypeAlias' importList = new Map() exportList = new Map() ignoredFiles = new Set() filesOutsideSrc = new Set() isNodeModule = (path) -> /\/(node_modules)\//.test path ###* # read all files matching the patterns in src and ignoreExports # # return all files matching src pattern, which are not matching the ignoreExports pattern ### resolveFiles = (src, ignoreExports, context) -> extensions = Array.from getFileExtensions context.settings srcFiles = new Set() srcFileList = listFilesToProcess src, extensions # prepare list of ignored files ignoredFilesList = listFilesToProcess ignoreExports, extensions ignoredFilesList.forEach ({filename}) -> ignoredFiles.add filename # prepare list of source files, don't consider files from node_modules srcFileList .filter ({filename}) -> not isNodeModule filename .forEach ({filename}) -> srcFiles.add filename srcFiles ###* # parse all source files and build up 2 maps containing the existing imports and exports ### prepareImportsAndExports = (srcFiles, context) -> exportAll = new Map() srcFiles.forEach (file) -> exports = new Map() imports = new Map() currentExports = Exports.get file, context if currentExports { dependencies reexports imports: localImportList namespace } = currentExports # dependencies === export * from currentExportAll = new Set() dependencies.forEach (getDependency) -> dependency = getDependency() return if dependency is null currentExportAll.add dependency.path exportAll.set file, currentExportAll reexports.forEach (value, key) -> if key is DEFAULT exports.set IMPORT_DEFAULT_SPECIFIER, whereUsed: new Set() else exports.set key, whereUsed: new Set() reexport = value.getImport() return unless reexport localImport = imports.get reexport.path if value.local is DEFAULT currentValue = IMPORT_DEFAULT_SPECIFIER else currentValue = value.local unless typeof localImport is 'undefined' localImport = new Set [...localImport, currentValue] else localImport = new Set [currentValue] imports.set reexport.path, localImport localImportList.forEach (value, key) -> return if isNodeModule key imports.set key, value.importedSpecifiers importList.set file, imports # build up export list only, if file is not ignored return if ignoredFiles.has file namespace.forEach (value, key) -> if key is DEFAULT exports.set IMPORT_DEFAULT_SPECIFIER, whereUsed: new Set() else exports.set key, whereUsed: new Set() exports.set EXPORT_ALL_DECLARATION, whereUsed: new Set() exports.set IMPORT_NAMESPACE_SPECIFIER, whereUsed: new Set() exportList.set file, exports exportAll.forEach (value, key) -> value.forEach (val) -> currentExports = exportList.get val currentExport = currentExports.get EXPORT_ALL_DECLARATION currentExport.whereUsed.add key ###* # traverse through all imports and add the respective path to the whereUsed-list # of the corresponding export ### determineUsage = -> importList.forEach (listValue, listKey) -> listValue.forEach (value, key) -> exports = exportList.get key unless typeof exports is 'undefined' value.forEach (currentImport) -> if currentImport is IMPORT_NAMESPACE_SPECIFIER specifier = IMPORT_NAMESPACE_SPECIFIER else if currentImport is IMPORT_DEFAULT_SPECIFIER specifier = IMPORT_DEFAULT_SPECIFIER else specifier = currentImport unless typeof specifier is 'undefined' exportStatement = exports.get specifier unless typeof exportStatement is 'undefined' {whereUsed} = exportStatement whereUsed.add listKey exports.set specifier, {whereUsed} getSrc = (src) -> return src if src [process.cwd()] ###* # prepare the lists of existing imports and exports - should only be executed once at # the start of a new eslint run ### srcFiles = null lastPrepareKey = null doPreparation = (src, ignoreExports, context) -> prepareKey = JSON.stringify( src: (src or []).sort() ignoreExports: (ignoreExports or []).sort() extensions: Array.from(getFileExtensions context.settings).sort() ) return if prepareKey is lastPrepareKey importList.clear() exportList.clear() ignoredFiles.clear() filesOutsideSrc.clear() srcFiles = resolveFiles getSrc(src), ignoreExports, context prepareImportsAndExports srcFiles, context determineUsage() lastPrepareKey = prepareKey newNamespaceImportExists = (specifiers) -> specifiers.some ({type}) -> type is IMPORT_NAMESPACE_SPECIFIER newDefaultImportExists = (specifiers) -> specifiers.some ({type}) -> type is IMPORT_DEFAULT_SPECIFIER fileIsInPkg = (file) -> {path, pkg} = readPkgUp.sync cwd: file, normalize: no basePath = dirname path checkPkgFieldString = (pkgField) -> return yes if join(basePath, pkgField) is file checkPkgFieldObject = (pkgField) -> pkgFieldFiles = values(pkgField).map (value) -> join basePath, value return yes if includes pkgFieldFiles, file checkPkgField = (pkgField) -> return checkPkgFieldString pkgField if typeof pkgField is 'string' return checkPkgFieldObject pkgField if typeof pkgField is 'object' return no if pkg.private is yes if pkg.bin then return yes if checkPkgField pkg.bin if pkg.browser then return yes if checkPkgField pkg.browser if pkg.main then return yes if checkPkgFieldString pkg.main no module.exports = meta: docs: url: docsUrl 'no-unused-modules' schema: [ properties: src: description: 'files/paths to be analyzed (only for unused exports)' type: 'array' minItems: 1 items: type: 'string' minLength: 1 ignoreExports: description: 'files/paths for which unused exports will not be reported (e.g module entry points)' type: 'array' minItems: 1 items: type: 'string' minLength: 1 missingExports: description: 'report modules without any exports' type: 'boolean' unusedExports: description: 'report exports without any usage' type: 'boolean' not: properties: unusedExports: enum: [no] missingExports: enum: [no] anyOf: [ not: properties: unusedExports: enum: [yes] required: ['missingExports'] , not: properties: missingExports: enum: [yes] required: ['unusedExports'] , properties: unusedExports: enum: [yes] required: ['unusedExports'] , properties: missingExports: enum: [yes] required: ['missingExports'] ] ] create: (context) -> { src ignoreExports = [] missingExports unusedExports } = context.options[0] or {} if unusedExports then doPreparation src, ignoreExports, context file = context.getFilename() checkExportPresence = (node) -> return unless missingExports return if ignoredFiles.has file exportCount = exportList.get file exportAll = exportCount.get EXPORT_ALL_DECLARATION namespaceImports = exportCount.get IMPORT_NAMESPACE_SPECIFIER exportCount.delete EXPORT_ALL_DECLARATION exportCount.delete IMPORT_NAMESPACE_SPECIFIER if exportCount.size < 1 # node.body[0] === 'undefined' only happens, if everything is commented out in the file # being linted context.report( if node.body[0] then node.body[0] else node 'No exports found' ) exportCount.set EXPORT_ALL_DECLARATION, exportAll exportCount.set IMPORT_NAMESPACE_SPECIFIER, namespaceImports checkUsage = (node, exportedValue) -> return unless unusedExports return if ignoredFiles.has file return if fileIsInPkg file return if filesOutsideSrc.has file # make sure file to be linted is included in source files unless srcFiles.has file srcFiles = resolveFiles getSrc(src), ignoreExports, context unless srcFiles.has file filesOutsideSrc.add file return exports = exportList.get file # special case: export * from exportAll = exports.get EXPORT_ALL_DECLARATION if ( typeof exportAll isnt 'undefined' and exportedValue isnt IMPORT_DEFAULT_SPECIFIER ) return if exportAll.whereUsed.size > 0 # special case: namespace import namespaceImports = exports.get IMPORT_NAMESPACE_SPECIFIER unless typeof namespaceImports is 'undefined' return if namespaceImports.whereUsed.size > 0 exportStatement = exports.get exportedValue value = if exportedValue is IMPORT_DEFAULT_SPECIFIER DEFAULT else exportedValue unless typeof exportStatement is 'undefined' if exportStatement.whereUsed.size < 1 context.report( node "exported declaration '#{value}' not used within other modules" ) else context.report( node "exported declaration '#{value}' not used within other modules" ) ###* # only useful for tools like vscode-eslint # # update lists of existing exports during runtime ### updateExportUsage = (node) -> return if ignoredFiles.has file exports = exportList.get file # new module has been created during runtime # include it in further processing if typeof exports is 'undefined' then exports = new Map() newExports = new Map() newExportIdentifiers = new Set() node.body.forEach ({type, declaration, specifiers}) -> if type is EXPORT_DEFAULT_DECLARATION newExportIdentifiers.add IMPORT_DEFAULT_SPECIFIER if type is EXPORT_NAMED_DECLARATION if specifiers.length > 0 specifiers.forEach (specifier) -> if specifier.exported newExportIdentifiers.add specifier.exported.name if declaration if declaration.type in [ FUNCTION_DECLARATION CLASS_DECLARATION TYPE_ALIAS ] newExportIdentifiers.add declaration.id.name if declaration.type is VARIABLE_DECLARATION declaration.declarations.forEach ({id}) -> newExportIdentifiers.add id.name if ( declaration.type is ASSIGNMENT_EXPRESSION and declaration.left.type is IDENTIFIER ) newExportIdentifiers.add declaration.left.name # old exports exist within list of new exports identifiers: add to map of new exports exports.forEach (value, key) -> if newExportIdentifiers.has key then newExports.set key, value # new export identifiers added: add to map of new exports newExportIdentifiers.forEach (key) -> unless exports.has key then newExports.set key, whereUsed: new Set() # preserve information about namespace imports exportAll = exports.get EXPORT_ALL_DECLARATION namespaceImports = exports.get IMPORT_NAMESPACE_SPECIFIER if typeof namespaceImports is 'undefined' namespaceImports = whereUsed: new Set() newExports.set EXPORT_ALL_DECLARATION, exportAll newExports.set IMPORT_NAMESPACE_SPECIFIER, namespaceImports exportList.set file, newExports ###* # only useful for tools like vscode-eslint # # update lists of existing imports during runtime ### updateImportUsage = (node) -> return unless unusedExports oldImportPaths = importList.get file if typeof oldImportPaths is 'undefined' then oldImportPaths = new Map() oldNamespaceImports = new Set() newNamespaceImports = new Set() oldExportAll = new Set() newExportAll = new Set() oldDefaultImports = new Set() newDefaultImports = new Set() oldImports = new Map() newImports = new Map() oldImportPaths.forEach (value, key) -> if value.has EXPORT_ALL_DECLARATION then oldExportAll.add key if value.has IMPORT_NAMESPACE_SPECIFIER then oldNamespaceImports.add key if value.has IMPORT_DEFAULT_SPECIFIER then oldDefaultImports.add key value.forEach (val) -> if ( val isnt IMPORT_NAMESPACE_SPECIFIER and val isnt IMPORT_DEFAULT_SPECIFIER ) oldImports.set val, key node.body.forEach (astNode) -> # support for export { value } from 'module' if astNode.type is EXPORT_NAMED_DECLARATION if astNode.source resolvedPath = resolve( astNode.source.raw.replace /('|")/g, '' context ) astNode.specifiers.forEach (specifier) -> if specifier.exported.name is DEFAULT name = IMPORT_DEFAULT_SPECIFIER else name = specifier.local.name newImports.set name, resolvedPath if astNode.type is EXPORT_ALL_DECLARATION resolvedPath = resolve( astNode.source.raw.replace /('|")/g, '' context ) newExportAll.add resolvedPath if astNode.type is IMPORT_DECLARATION resolvedPath = resolve( astNode.source.raw.replace /('|")/g, '' context ) return unless resolvedPath return if isNodeModule resolvedPath if newNamespaceImportExists astNode.specifiers newNamespaceImports.add resolvedPath if newDefaultImportExists astNode.specifiers newDefaultImports.add resolvedPath astNode.specifiers.forEach (specifier) -> return if specifier.type in [ IMPORT_DEFAULT_SPECIFIER IMPORT_NAMESPACE_SPECIFIER ] newImports.set specifier.imported.name, resolvedPath newExportAll.forEach (value) -> unless oldExportAll.has value imports = oldImportPaths.get value if typeof imports is 'undefined' then imports = new Set() imports.add EXPORT_ALL_DECLARATION oldImportPaths.set value, imports exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get EXPORT_ALL_DECLARATION else exports = new Map() exportList.set value, exports unless typeof currentExport is 'undefined' currentExport.whereUsed.add file else whereUsed = new Set() whereUsed.add file exports.set EXPORT_ALL_DECLARATION, {whereUsed} oldExportAll.forEach (value) -> unless newExportAll.has value imports = oldImportPaths.get value imports.delete EXPORT_ALL_DECLARATION exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get EXPORT_ALL_DECLARATION unless typeof currentExport is 'undefined' currentExport.whereUsed.delete file newDefaultImports.forEach (value) -> unless oldDefaultImports.has value imports = oldImportPaths.get value if typeof imports is 'undefined' then imports = new Set() imports.add IMPORT_DEFAULT_SPECIFIER oldImportPaths.set value, imports exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get IMPORT_DEFAULT_SPECIFIER else exports = new Map() exportList.set value, exports unless typeof currentExport is 'undefined' currentExport.whereUsed.add file else whereUsed = new Set() whereUsed.add file exports.set IMPORT_DEFAULT_SPECIFIER, {whereUsed} oldDefaultImports.forEach (value) -> unless newDefaultImports.has value imports = oldImportPaths.get value imports.delete IMPORT_DEFAULT_SPECIFIER exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get IMPORT_DEFAULT_SPECIFIER unless typeof currentExport is 'undefined' currentExport.whereUsed.delete file newNamespaceImports.forEach (value) -> unless oldNamespaceImports.has value imports = oldImportPaths.get value if typeof imports is 'undefined' then imports = new Set() imports.add IMPORT_NAMESPACE_SPECIFIER oldImportPaths.set value, imports exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get IMPORT_NAMESPACE_SPECIFIER else exports = new Map() exportList.set value, exports unless typeof currentExport is 'undefined' currentExport.whereUsed.add file else whereUsed = new Set() whereUsed.add file exports.set IMPORT_NAMESPACE_SPECIFIER, {whereUsed} oldNamespaceImports.forEach (value) -> unless newNamespaceImports.has value imports = oldImportPaths.get value imports.delete IMPORT_NAMESPACE_SPECIFIER exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get IMPORT_NAMESPACE_SPECIFIER unless typeof currentExport is 'undefined' currentExport.whereUsed.delete file newImports.forEach (value, key) -> unless oldImports.has key imports = oldImportPaths.get value if typeof imports is 'undefined' then imports = new Set() imports.add key oldImportPaths.set value, imports exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get key else exports = new Map() exportList.set value, exports unless typeof currentExport is 'undefined' currentExport.whereUsed.add file else whereUsed = new Set() whereUsed.add file exports.set key, {whereUsed} oldImports.forEach (value, key) -> unless newImports.has key imports = oldImportPaths.get value imports.delete key exports = exportList.get value unless typeof exports is 'undefined' currentExport = exports.get key unless typeof currentExport is 'undefined' currentExport.whereUsed.delete file 'Program:exit': (node) -> updateExportUsage node updateImportUsage node checkExportPresence node ExportDefaultDeclaration: (node) -> checkUsage node, IMPORT_DEFAULT_SPECIFIER ExportNamedDeclaration: (node) -> node.specifiers.forEach (specifier) -> checkUsage node, specifier.exported.name if node.declaration if node.declaration.type in [ FUNCTION_DECLARATION CLASS_DECLARATION TYPE_ALIAS ] checkUsage node, node.declaration.id.name if node.declaration.type is VARIABLE_DECLARATION node.declaration.declarations.forEach (declaration) -> checkUsage node, declaration.id.name if ( node.declaration.type is ASSIGNMENT_EXPRESSION and node.declaration.left.type is IDENTIFIER ) checkUsage node, node.declaration.left.name
[ { "context": "/publickey'\n .reply 200, { publicKey: 'this-definitely-will-not-work' }\n\n @sut.fetch \"http://localhost:#{0xd00d}/", "end": 1042, "score": 0.612917959690094, "start": 1018, "tag": "PASSWORD", "value": "definitely-will-not-work" } ]
test/fetch-spec.coffee
octoblu/fetch-meshblu-public-key
0
shmock = require 'shmock' enableDestroy = require 'server-destroy' NodeRSA = require 'node-rsa' validPublicKey = require './valid-public-key.json' FetchPublicKey = require '../' describe 'Fetch', -> beforeEach -> @server = shmock 0xd00d enableDestroy @server @sut = new FetchPublicKey afterEach -> @server.destroy() describe 'when called with a valid request', -> beforeEach (done) -> @fetchRequest = @server.get '/publickey' .reply 200, validPublicKey @sut.fetch "http://localhost:#{0xd00d}/publickey", (error, @publicKey) => done error it 'should make the fetch request', -> @fetchRequest.done() it 'should be valid public key', -> key = new NodeRSA() key.importKey(new Buffer(@publicKey.publicKey), 'public') expect(key.isPublic()).to.be.true describe 'when called with a invalid request', -> beforeEach (done) -> @fetchRequest = @server.get '/publickey' .reply 200, { publicKey: 'this-definitely-will-not-work' } @sut.fetch "http://localhost:#{0xd00d}/publickey", (@error, @publicKey) => done() it 'should make the fetch request', -> @fetchRequest.done() it 'should have an error', -> expect(@error.message).to.equal 'Invalid PublicKey' describe 'when called with an empty request', -> beforeEach (done) -> @fetchRequest = @server.get '/publickey' .reply 200, { publicKey: null } @sut.fetch "http://localhost:#{0xd00d}/publickey", (@error, @publicKey) => done() it 'should make the fetch request', -> @fetchRequest.done() it 'should have an error', -> expect(@error.message).to.equal 'Invalid PublicKey' describe 'when called with an invalid request uri', -> beforeEach (done) -> @fetchRequest = @server.get '/publickey' .reply 502, 'Bad Gateway' @sut.fetch "http://localhost:#{0xd00d}/publickey", (@error, @publicKey) => done() it 'should make the fetch request', -> @fetchRequest.done() it 'should have an error', -> expect(@error.message).to.equal 'Invalid Response Code: 502'
97909
shmock = require 'shmock' enableDestroy = require 'server-destroy' NodeRSA = require 'node-rsa' validPublicKey = require './valid-public-key.json' FetchPublicKey = require '../' describe 'Fetch', -> beforeEach -> @server = shmock 0xd00d enableDestroy @server @sut = new FetchPublicKey afterEach -> @server.destroy() describe 'when called with a valid request', -> beforeEach (done) -> @fetchRequest = @server.get '/publickey' .reply 200, validPublicKey @sut.fetch "http://localhost:#{0xd00d}/publickey", (error, @publicKey) => done error it 'should make the fetch request', -> @fetchRequest.done() it 'should be valid public key', -> key = new NodeRSA() key.importKey(new Buffer(@publicKey.publicKey), 'public') expect(key.isPublic()).to.be.true describe 'when called with a invalid request', -> beforeEach (done) -> @fetchRequest = @server.get '/publickey' .reply 200, { publicKey: 'this-<PASSWORD>' } @sut.fetch "http://localhost:#{0xd00d}/publickey", (@error, @publicKey) => done() it 'should make the fetch request', -> @fetchRequest.done() it 'should have an error', -> expect(@error.message).to.equal 'Invalid PublicKey' describe 'when called with an empty request', -> beforeEach (done) -> @fetchRequest = @server.get '/publickey' .reply 200, { publicKey: null } @sut.fetch "http://localhost:#{0xd00d}/publickey", (@error, @publicKey) => done() it 'should make the fetch request', -> @fetchRequest.done() it 'should have an error', -> expect(@error.message).to.equal 'Invalid PublicKey' describe 'when called with an invalid request uri', -> beforeEach (done) -> @fetchRequest = @server.get '/publickey' .reply 502, 'Bad Gateway' @sut.fetch "http://localhost:#{0xd00d}/publickey", (@error, @publicKey) => done() it 'should make the fetch request', -> @fetchRequest.done() it 'should have an error', -> expect(@error.message).to.equal 'Invalid Response Code: 502'
true
shmock = require 'shmock' enableDestroy = require 'server-destroy' NodeRSA = require 'node-rsa' validPublicKey = require './valid-public-key.json' FetchPublicKey = require '../' describe 'Fetch', -> beforeEach -> @server = shmock 0xd00d enableDestroy @server @sut = new FetchPublicKey afterEach -> @server.destroy() describe 'when called with a valid request', -> beforeEach (done) -> @fetchRequest = @server.get '/publickey' .reply 200, validPublicKey @sut.fetch "http://localhost:#{0xd00d}/publickey", (error, @publicKey) => done error it 'should make the fetch request', -> @fetchRequest.done() it 'should be valid public key', -> key = new NodeRSA() key.importKey(new Buffer(@publicKey.publicKey), 'public') expect(key.isPublic()).to.be.true describe 'when called with a invalid request', -> beforeEach (done) -> @fetchRequest = @server.get '/publickey' .reply 200, { publicKey: 'this-PI:PASSWORD:<PASSWORD>END_PI' } @sut.fetch "http://localhost:#{0xd00d}/publickey", (@error, @publicKey) => done() it 'should make the fetch request', -> @fetchRequest.done() it 'should have an error', -> expect(@error.message).to.equal 'Invalid PublicKey' describe 'when called with an empty request', -> beforeEach (done) -> @fetchRequest = @server.get '/publickey' .reply 200, { publicKey: null } @sut.fetch "http://localhost:#{0xd00d}/publickey", (@error, @publicKey) => done() it 'should make the fetch request', -> @fetchRequest.done() it 'should have an error', -> expect(@error.message).to.equal 'Invalid PublicKey' describe 'when called with an invalid request uri', -> beforeEach (done) -> @fetchRequest = @server.get '/publickey' .reply 502, 'Bad Gateway' @sut.fetch "http://localhost:#{0xd00d}/publickey", (@error, @publicKey) => done() it 'should make the fetch request', -> @fetchRequest.done() it 'should have an error', -> expect(@error.message).to.equal 'Invalid Response Code: 502'
[ { "context": "###\nStandalone Deferred\nCopyright 2012 Otto Vehviläinen\nReleased under MIT license\n\nThis is a standalone ", "end": 55, "score": 0.9998805522918701, "start": 39, "tag": "NAME", "value": "Otto Vehviläinen" } ]
src/Deferred.coffee
Mumakil/Standalone-Deferred
5
### Standalone Deferred Copyright 2012 Otto Vehviläinen Released under MIT license This is a standalone implementation of the wonderful jQuery.Deferred API. The documentation here is only for quick reference, for complete api please see the great work of the original project: http://api.jquery.com/category/deferred-object/ ### unless Array::forEach throw new Error "Deferred requires Array.forEach" ### Store a reference to the global context ### root = this ### Tells if an object is observable ### isObservable = (obj) -> (obj instanceof Deferred) or (obj instanceof Promise) ### Flatten a two dimensional array into one dimension. Removes elements that are not functions ### flatten = (args) -> return [] unless args flatted = [] args.forEach (item) -> if item if typeof item is 'function' flatted.push(item) else args.forEach (fn) -> if typeof fn is 'function' flatted.push(fn) flatted ### Promise object functions as a proxy for a Deferred, except it does not let you modify the state of the Deferred ### class Promise _deferred: null constructor: (deferred) -> @_deferred = deferred always: (args...) -> @_deferred.always(args...) this done: (args...) -> @_deferred.done(args...) this fail: (args...) -> @_deferred.fail(args...) this pipe: (doneFilter, failFilter) -> @_deferred.pipe(doneFilter, failFilter) state: -> @_deferred.state() then: (done, fail) -> @_deferred.then(done, fail) this class root.Deferred ### Initializes a new Deferred. You can pass a function as a parameter to be executed immediately after init. The function receives the new deferred object as a parameter and this is also set to the same object. ### constructor: (fn) -> @_state = 'pending' fn.call(this, this) if typeof fn is 'function' ### Pass in functions or arrays of functions to be executed when the Deferred object changes state from pending. If the state is already rejected or resolved, the functions are executed immediately. They receive the arguments that are passed to reject or resolve and this is set to the object defined by rejectWith or resolveWith if those variants are used. ### always: (args...) => return this if args.length is 0 functions = flatten(args) if @_state is 'pending' @_alwaysCallbacks or= [] @_alwaysCallbacks.push(functions...) else functions.forEach (fn) => fn.apply(@_context, @_withArguments) this ### Pass in functions or arrays of functions to be executed when the Deferred object is resolved. If the object has already been resolved, the functions are executed immediately. If the object has been rejected, nothing happens. The functions receive the arguments that are passed to resolve and this is set to the object defined by resolveWith if that variant is used. ### done: (args...) => return this if args.length is 0 functions = flatten(args) if @_state is 'resolved' functions.forEach (fn) => fn.apply(@_context, @_withArguments) else if @_state is 'pending' @_doneCallbacks or= [] @_doneCallbacks.push(functions...) this ### Pass in functions or arrays of functions to be executed when the Deferred object is rejected. If the object has already been rejected, the functions are executed immediately. If the object has been resolved, nothing happens. The functions receive the arguments that are passed to reject and this is set to the object defined by rejectWith if that variant is used. ### fail: (args...) => return this if args.length is 0 functions = flatten(args) if @_state is 'rejected' functions.forEach (fn) => fn.apply(@_context, @_withArguments) else if @_state is 'pending' @_failCallbacks or= [] @_failCallbacks.push(functions...) this ### Notify progress callbacks. The callbacks get passed the arguments given to notify. If the object has resolved or rejected, nothing will happen ### notify: (args...) => @notifyWith(root, args...) this ### Notify progress callbacks with additional context. Works the same way as notify(), except this is set to context when calling the functions. ### notifyWith: (context, args...) => return this if @_state isnt 'pending' @_progressCallbacks?.forEach (fn) -> fn.apply(context, args) this ### Returns a new Promise object that's tied to the current Deferred. The doneFilter and failFilter can be used to modify the final values that are passed to the callbacks of the new promise. If the parameters passed are falsy, the promise object resolves or rejects normally. If the filter functions return a value, that one is passed to the respective callbacks. The filters can also return a new Promise or Deferred object, of which rejected / resolved will control how the callbacks fire. ### pipe: (doneFilter, failFilter) => def = new Deferred() @done (args...) -> if doneFilter? result = doneFilter.apply(this, args) if isObservable(result) result .done (doneArgs...)-> def.resolveWith.call(def, this, doneArgs...) .fail (failArgs...) -> def.rejectWith.call(def, this, failArgs...) else def.resolveWith.call(def, this, result) else def.resolveWith.call(def, this, args...) @fail (args...) -> if failFilter? result = failFilter.apply(this, args) if isObservable(result) result .done (doneArgs...)-> def.resolveWith.call(def, this, doneArgs...) .fail (failArgs...) -> def.rejectWith.call(def, this, failArgs...) else def.rejectWith.call(def, this, result) def.rejectWith.call(def, this, args...) else def.rejectWith.call(def, this, args...) def.promise() ### Add progress callbacks to be fired when using notify() ### progress: (args...) => return this if args.length is 0 or @_state isnt 'pending' functions = flatten(args) @_progressCallbacks or= [] @_progressCallbacks.push(functions...) this ### Returns the promise object of this Deferred. ### promise: => @_promise or= new Promise(this) ### Reject this Deferred. If the object has already been rejected or resolved, nothing happens. Parameters passed to reject will be handed to all current and future fail and always callbacks. ### reject: (args...) => @rejectWith(root, args...) this ### Reject this Deferred with additional context. Works the same way as reject, except the first parameter is used as this when calling the fail and always callbacks. ### rejectWith: (context, args...) => return this if @_state isnt 'pending' @_state = 'rejected' @_withArguments = args @_context = context @_failCallbacks?.forEach (fn) => fn.apply(@_context, args) @_alwaysCallbacks?.forEach (fn) => fn.apply(@_context, args) this ### Resolves this Deferred object. If the object has already been rejected or resolved, nothing happens. Parameters passed to resolve will be handed to all current and future done and always callbacks. ### resolve: (args...) => @resolveWith(root, args...) this ### Resolve this Deferred with additional context. Works the same way as resolve, except the first parameter is used as this when calling the done and always callbacks. ### resolveWith: (context, args...) => return this if @_state isnt 'pending' @_state = 'resolved' @_context = context @_withArguments = args @_doneCallbacks?.forEach (fn) => fn.apply(@_context, args) @_alwaysCallbacks?.forEach (fn) => fn.apply(@_context, args) this ### Returns the state of this Deferred. Can be 'pending', 'rejected' or 'resolved'. ### state: -> @_state ### Convenience function to specify each done, fail and progress callbacks at the same time. ### then: (doneCallbacks, failCallbacks, progressCallbacks) => @done(doneCallbacks) @fail(failCallbacks) @progress(progressCallbacks) this ### Returns a new promise object which will resolve when all of the deferreds or promises passed to the function resolve. The callbacks receive all the parameters that the individual resolves yielded as an array. If any of the deferreds or promises are rejected, the promise will be rejected immediately. ### root.Deferred.when = (args...) -> return new Deferred().resolve().promise() if args.length is 0 return args[0].promise() if args.length is 1 allReady = new Deferred() readyCount = 0 allDoneArgs = [] args.forEach (dfr, index) -> dfr .done (doneArgs...) -> readyCount += 1 allDoneArgs[index] = doneArgs if readyCount is args.length allReady.resolve(allDoneArgs...) .fail (failArgs...) -> allReady.rejectWith(this, failArgs...) allReady.promise() # Install Deferred to Zepto automatically. do -> destination = window.Zepto return if not destination or destination.Deferred destination.Deferred = -> new Deferred() origAjax = destination.ajax destination.ajax = (options) -> deferred = new Deferred() createWrapper = (wrapped, finisher) -> (args...) -> wrapped?(args...) finisher(args...) options.success = createWrapper options.success, deferred.resolve options.error = createWrapper options.error, deferred.reject origAjax(options) deferred.promise()
93420
### Standalone Deferred Copyright 2012 <NAME> Released under MIT license This is a standalone implementation of the wonderful jQuery.Deferred API. The documentation here is only for quick reference, for complete api please see the great work of the original project: http://api.jquery.com/category/deferred-object/ ### unless Array::forEach throw new Error "Deferred requires Array.forEach" ### Store a reference to the global context ### root = this ### Tells if an object is observable ### isObservable = (obj) -> (obj instanceof Deferred) or (obj instanceof Promise) ### Flatten a two dimensional array into one dimension. Removes elements that are not functions ### flatten = (args) -> return [] unless args flatted = [] args.forEach (item) -> if item if typeof item is 'function' flatted.push(item) else args.forEach (fn) -> if typeof fn is 'function' flatted.push(fn) flatted ### Promise object functions as a proxy for a Deferred, except it does not let you modify the state of the Deferred ### class Promise _deferred: null constructor: (deferred) -> @_deferred = deferred always: (args...) -> @_deferred.always(args...) this done: (args...) -> @_deferred.done(args...) this fail: (args...) -> @_deferred.fail(args...) this pipe: (doneFilter, failFilter) -> @_deferred.pipe(doneFilter, failFilter) state: -> @_deferred.state() then: (done, fail) -> @_deferred.then(done, fail) this class root.Deferred ### Initializes a new Deferred. You can pass a function as a parameter to be executed immediately after init. The function receives the new deferred object as a parameter and this is also set to the same object. ### constructor: (fn) -> @_state = 'pending' fn.call(this, this) if typeof fn is 'function' ### Pass in functions or arrays of functions to be executed when the Deferred object changes state from pending. If the state is already rejected or resolved, the functions are executed immediately. They receive the arguments that are passed to reject or resolve and this is set to the object defined by rejectWith or resolveWith if those variants are used. ### always: (args...) => return this if args.length is 0 functions = flatten(args) if @_state is 'pending' @_alwaysCallbacks or= [] @_alwaysCallbacks.push(functions...) else functions.forEach (fn) => fn.apply(@_context, @_withArguments) this ### Pass in functions or arrays of functions to be executed when the Deferred object is resolved. If the object has already been resolved, the functions are executed immediately. If the object has been rejected, nothing happens. The functions receive the arguments that are passed to resolve and this is set to the object defined by resolveWith if that variant is used. ### done: (args...) => return this if args.length is 0 functions = flatten(args) if @_state is 'resolved' functions.forEach (fn) => fn.apply(@_context, @_withArguments) else if @_state is 'pending' @_doneCallbacks or= [] @_doneCallbacks.push(functions...) this ### Pass in functions or arrays of functions to be executed when the Deferred object is rejected. If the object has already been rejected, the functions are executed immediately. If the object has been resolved, nothing happens. The functions receive the arguments that are passed to reject and this is set to the object defined by rejectWith if that variant is used. ### fail: (args...) => return this if args.length is 0 functions = flatten(args) if @_state is 'rejected' functions.forEach (fn) => fn.apply(@_context, @_withArguments) else if @_state is 'pending' @_failCallbacks or= [] @_failCallbacks.push(functions...) this ### Notify progress callbacks. The callbacks get passed the arguments given to notify. If the object has resolved or rejected, nothing will happen ### notify: (args...) => @notifyWith(root, args...) this ### Notify progress callbacks with additional context. Works the same way as notify(), except this is set to context when calling the functions. ### notifyWith: (context, args...) => return this if @_state isnt 'pending' @_progressCallbacks?.forEach (fn) -> fn.apply(context, args) this ### Returns a new Promise object that's tied to the current Deferred. The doneFilter and failFilter can be used to modify the final values that are passed to the callbacks of the new promise. If the parameters passed are falsy, the promise object resolves or rejects normally. If the filter functions return a value, that one is passed to the respective callbacks. The filters can also return a new Promise or Deferred object, of which rejected / resolved will control how the callbacks fire. ### pipe: (doneFilter, failFilter) => def = new Deferred() @done (args...) -> if doneFilter? result = doneFilter.apply(this, args) if isObservable(result) result .done (doneArgs...)-> def.resolveWith.call(def, this, doneArgs...) .fail (failArgs...) -> def.rejectWith.call(def, this, failArgs...) else def.resolveWith.call(def, this, result) else def.resolveWith.call(def, this, args...) @fail (args...) -> if failFilter? result = failFilter.apply(this, args) if isObservable(result) result .done (doneArgs...)-> def.resolveWith.call(def, this, doneArgs...) .fail (failArgs...) -> def.rejectWith.call(def, this, failArgs...) else def.rejectWith.call(def, this, result) def.rejectWith.call(def, this, args...) else def.rejectWith.call(def, this, args...) def.promise() ### Add progress callbacks to be fired when using notify() ### progress: (args...) => return this if args.length is 0 or @_state isnt 'pending' functions = flatten(args) @_progressCallbacks or= [] @_progressCallbacks.push(functions...) this ### Returns the promise object of this Deferred. ### promise: => @_promise or= new Promise(this) ### Reject this Deferred. If the object has already been rejected or resolved, nothing happens. Parameters passed to reject will be handed to all current and future fail and always callbacks. ### reject: (args...) => @rejectWith(root, args...) this ### Reject this Deferred with additional context. Works the same way as reject, except the first parameter is used as this when calling the fail and always callbacks. ### rejectWith: (context, args...) => return this if @_state isnt 'pending' @_state = 'rejected' @_withArguments = args @_context = context @_failCallbacks?.forEach (fn) => fn.apply(@_context, args) @_alwaysCallbacks?.forEach (fn) => fn.apply(@_context, args) this ### Resolves this Deferred object. If the object has already been rejected or resolved, nothing happens. Parameters passed to resolve will be handed to all current and future done and always callbacks. ### resolve: (args...) => @resolveWith(root, args...) this ### Resolve this Deferred with additional context. Works the same way as resolve, except the first parameter is used as this when calling the done and always callbacks. ### resolveWith: (context, args...) => return this if @_state isnt 'pending' @_state = 'resolved' @_context = context @_withArguments = args @_doneCallbacks?.forEach (fn) => fn.apply(@_context, args) @_alwaysCallbacks?.forEach (fn) => fn.apply(@_context, args) this ### Returns the state of this Deferred. Can be 'pending', 'rejected' or 'resolved'. ### state: -> @_state ### Convenience function to specify each done, fail and progress callbacks at the same time. ### then: (doneCallbacks, failCallbacks, progressCallbacks) => @done(doneCallbacks) @fail(failCallbacks) @progress(progressCallbacks) this ### Returns a new promise object which will resolve when all of the deferreds or promises passed to the function resolve. The callbacks receive all the parameters that the individual resolves yielded as an array. If any of the deferreds or promises are rejected, the promise will be rejected immediately. ### root.Deferred.when = (args...) -> return new Deferred().resolve().promise() if args.length is 0 return args[0].promise() if args.length is 1 allReady = new Deferred() readyCount = 0 allDoneArgs = [] args.forEach (dfr, index) -> dfr .done (doneArgs...) -> readyCount += 1 allDoneArgs[index] = doneArgs if readyCount is args.length allReady.resolve(allDoneArgs...) .fail (failArgs...) -> allReady.rejectWith(this, failArgs...) allReady.promise() # Install Deferred to Zepto automatically. do -> destination = window.Zepto return if not destination or destination.Deferred destination.Deferred = -> new Deferred() origAjax = destination.ajax destination.ajax = (options) -> deferred = new Deferred() createWrapper = (wrapped, finisher) -> (args...) -> wrapped?(args...) finisher(args...) options.success = createWrapper options.success, deferred.resolve options.error = createWrapper options.error, deferred.reject origAjax(options) deferred.promise()
true
### Standalone Deferred Copyright 2012 PI:NAME:<NAME>END_PI Released under MIT license This is a standalone implementation of the wonderful jQuery.Deferred API. The documentation here is only for quick reference, for complete api please see the great work of the original project: http://api.jquery.com/category/deferred-object/ ### unless Array::forEach throw new Error "Deferred requires Array.forEach" ### Store a reference to the global context ### root = this ### Tells if an object is observable ### isObservable = (obj) -> (obj instanceof Deferred) or (obj instanceof Promise) ### Flatten a two dimensional array into one dimension. Removes elements that are not functions ### flatten = (args) -> return [] unless args flatted = [] args.forEach (item) -> if item if typeof item is 'function' flatted.push(item) else args.forEach (fn) -> if typeof fn is 'function' flatted.push(fn) flatted ### Promise object functions as a proxy for a Deferred, except it does not let you modify the state of the Deferred ### class Promise _deferred: null constructor: (deferred) -> @_deferred = deferred always: (args...) -> @_deferred.always(args...) this done: (args...) -> @_deferred.done(args...) this fail: (args...) -> @_deferred.fail(args...) this pipe: (doneFilter, failFilter) -> @_deferred.pipe(doneFilter, failFilter) state: -> @_deferred.state() then: (done, fail) -> @_deferred.then(done, fail) this class root.Deferred ### Initializes a new Deferred. You can pass a function as a parameter to be executed immediately after init. The function receives the new deferred object as a parameter and this is also set to the same object. ### constructor: (fn) -> @_state = 'pending' fn.call(this, this) if typeof fn is 'function' ### Pass in functions or arrays of functions to be executed when the Deferred object changes state from pending. If the state is already rejected or resolved, the functions are executed immediately. They receive the arguments that are passed to reject or resolve and this is set to the object defined by rejectWith or resolveWith if those variants are used. ### always: (args...) => return this if args.length is 0 functions = flatten(args) if @_state is 'pending' @_alwaysCallbacks or= [] @_alwaysCallbacks.push(functions...) else functions.forEach (fn) => fn.apply(@_context, @_withArguments) this ### Pass in functions or arrays of functions to be executed when the Deferred object is resolved. If the object has already been resolved, the functions are executed immediately. If the object has been rejected, nothing happens. The functions receive the arguments that are passed to resolve and this is set to the object defined by resolveWith if that variant is used. ### done: (args...) => return this if args.length is 0 functions = flatten(args) if @_state is 'resolved' functions.forEach (fn) => fn.apply(@_context, @_withArguments) else if @_state is 'pending' @_doneCallbacks or= [] @_doneCallbacks.push(functions...) this ### Pass in functions or arrays of functions to be executed when the Deferred object is rejected. If the object has already been rejected, the functions are executed immediately. If the object has been resolved, nothing happens. The functions receive the arguments that are passed to reject and this is set to the object defined by rejectWith if that variant is used. ### fail: (args...) => return this if args.length is 0 functions = flatten(args) if @_state is 'rejected' functions.forEach (fn) => fn.apply(@_context, @_withArguments) else if @_state is 'pending' @_failCallbacks or= [] @_failCallbacks.push(functions...) this ### Notify progress callbacks. The callbacks get passed the arguments given to notify. If the object has resolved or rejected, nothing will happen ### notify: (args...) => @notifyWith(root, args...) this ### Notify progress callbacks with additional context. Works the same way as notify(), except this is set to context when calling the functions. ### notifyWith: (context, args...) => return this if @_state isnt 'pending' @_progressCallbacks?.forEach (fn) -> fn.apply(context, args) this ### Returns a new Promise object that's tied to the current Deferred. The doneFilter and failFilter can be used to modify the final values that are passed to the callbacks of the new promise. If the parameters passed are falsy, the promise object resolves or rejects normally. If the filter functions return a value, that one is passed to the respective callbacks. The filters can also return a new Promise or Deferred object, of which rejected / resolved will control how the callbacks fire. ### pipe: (doneFilter, failFilter) => def = new Deferred() @done (args...) -> if doneFilter? result = doneFilter.apply(this, args) if isObservable(result) result .done (doneArgs...)-> def.resolveWith.call(def, this, doneArgs...) .fail (failArgs...) -> def.rejectWith.call(def, this, failArgs...) else def.resolveWith.call(def, this, result) else def.resolveWith.call(def, this, args...) @fail (args...) -> if failFilter? result = failFilter.apply(this, args) if isObservable(result) result .done (doneArgs...)-> def.resolveWith.call(def, this, doneArgs...) .fail (failArgs...) -> def.rejectWith.call(def, this, failArgs...) else def.rejectWith.call(def, this, result) def.rejectWith.call(def, this, args...) else def.rejectWith.call(def, this, args...) def.promise() ### Add progress callbacks to be fired when using notify() ### progress: (args...) => return this if args.length is 0 or @_state isnt 'pending' functions = flatten(args) @_progressCallbacks or= [] @_progressCallbacks.push(functions...) this ### Returns the promise object of this Deferred. ### promise: => @_promise or= new Promise(this) ### Reject this Deferred. If the object has already been rejected or resolved, nothing happens. Parameters passed to reject will be handed to all current and future fail and always callbacks. ### reject: (args...) => @rejectWith(root, args...) this ### Reject this Deferred with additional context. Works the same way as reject, except the first parameter is used as this when calling the fail and always callbacks. ### rejectWith: (context, args...) => return this if @_state isnt 'pending' @_state = 'rejected' @_withArguments = args @_context = context @_failCallbacks?.forEach (fn) => fn.apply(@_context, args) @_alwaysCallbacks?.forEach (fn) => fn.apply(@_context, args) this ### Resolves this Deferred object. If the object has already been rejected or resolved, nothing happens. Parameters passed to resolve will be handed to all current and future done and always callbacks. ### resolve: (args...) => @resolveWith(root, args...) this ### Resolve this Deferred with additional context. Works the same way as resolve, except the first parameter is used as this when calling the done and always callbacks. ### resolveWith: (context, args...) => return this if @_state isnt 'pending' @_state = 'resolved' @_context = context @_withArguments = args @_doneCallbacks?.forEach (fn) => fn.apply(@_context, args) @_alwaysCallbacks?.forEach (fn) => fn.apply(@_context, args) this ### Returns the state of this Deferred. Can be 'pending', 'rejected' or 'resolved'. ### state: -> @_state ### Convenience function to specify each done, fail and progress callbacks at the same time. ### then: (doneCallbacks, failCallbacks, progressCallbacks) => @done(doneCallbacks) @fail(failCallbacks) @progress(progressCallbacks) this ### Returns a new promise object which will resolve when all of the deferreds or promises passed to the function resolve. The callbacks receive all the parameters that the individual resolves yielded as an array. If any of the deferreds or promises are rejected, the promise will be rejected immediately. ### root.Deferred.when = (args...) -> return new Deferred().resolve().promise() if args.length is 0 return args[0].promise() if args.length is 1 allReady = new Deferred() readyCount = 0 allDoneArgs = [] args.forEach (dfr, index) -> dfr .done (doneArgs...) -> readyCount += 1 allDoneArgs[index] = doneArgs if readyCount is args.length allReady.resolve(allDoneArgs...) .fail (failArgs...) -> allReady.rejectWith(this, failArgs...) allReady.promise() # Install Deferred to Zepto automatically. do -> destination = window.Zepto return if not destination or destination.Deferred destination.Deferred = -> new Deferred() origAjax = destination.ajax destination.ajax = (options) -> deferred = new Deferred() createWrapper = (wrapped, finisher) -> (args...) -> wrapped?(args...) finisher(args...) options.success = createWrapper options.success, deferred.resolve options.error = createWrapper options.error, deferred.reject origAjax(options) deferred.promise()
[ { "context": " #\n # Author.\n #\n # Created by hector spc <hector@aerstudio.com>\n # Aer Studio \n # http:/", "end": 43, "score": 0.9028184413909912, "start": 33, "tag": "NAME", "value": "hector spc" }, { "context": " #\n # Author.\n #\n # Created by hector spc <hector@aerstudio.com>\n # Aer Studio \n # http://www.aerstudio.com\n #\n", "end": 65, "score": 0.9999340772628784, "start": 45, "tag": "EMAIL", "value": "hector@aerstudio.com" } ]
src/collections/authors_collection.coffee
aerstudio/Phallanxpress
1
# # Author. # # Created by hector spc <hector@aerstudio.com> # Aer Studio # http://www.aerstudio.com # # Sun Mar 04 2012 # # collections/authors_collection.js.coffee # class Phallanxpress.Authors extends Phallanxpress.Collection model: Phallanxpress.Author parseTag: 'authors' authorList: (options)-> @_wpAPI('get_author_index', options)
57298
# # Author. # # Created by <NAME> <<EMAIL>> # Aer Studio # http://www.aerstudio.com # # Sun Mar 04 2012 # # collections/authors_collection.js.coffee # class Phallanxpress.Authors extends Phallanxpress.Collection model: Phallanxpress.Author parseTag: 'authors' authorList: (options)-> @_wpAPI('get_author_index', options)
true
# # Author. # # Created by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Aer Studio # http://www.aerstudio.com # # Sun Mar 04 2012 # # collections/authors_collection.js.coffee # class Phallanxpress.Authors extends Phallanxpress.Collection model: Phallanxpress.Author parseTag: 'authors' authorList: (options)-> @_wpAPI('get_author_index', options)
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.995168924331665, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-tls-npn-server-client.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. filenamePEM = (n) -> require("path").join common.fixturesDir, "keys", n + ".pem" loadPEM = (n) -> fs.readFileSync filenamePEM(n) startTest = -> connectClient = (options, callback) -> client = tls.connect(options, -> clientsResults.push client.npnProtocol client.destroy() callback() return ) return connectClient clientsOptions[0], -> connectClient clientsOptions[1], -> connectClient clientsOptions[2], -> connectClient clientsOptions[3], -> server.close() return return return return return unless process.features.tls_npn console.error "Skipping because node compiled without OpenSSL or " + "with old OpenSSL version." process.exit 0 common = require("../common") assert = require("assert") fs = require("fs") tls = require("tls") serverOptions = key: loadPEM("agent2-key") cert: loadPEM("agent2-cert") crl: loadPEM("ca2-crl") SNICallback: (servername, cb) -> cb null, tls.createSecureContext( key: loadPEM("agent2-key") cert: loadPEM("agent2-cert") crl: loadPEM("ca2-crl") ) return NPNProtocols: [ "a" "b" "c" ] serverPort = common.PORT clientsOptions = [ { port: serverPort key: serverOptions.key cert: serverOptions.cert crl: serverOptions.crl NPNProtocols: [ "a" "b" "c" ] rejectUnauthorized: false } { port: serverPort key: serverOptions.key cert: serverOptions.cert crl: serverOptions.crl NPNProtocols: [ "c" "b" "e" ] rejectUnauthorized: false } { port: serverPort key: serverOptions.key cert: serverOptions.cert crl: serverOptions.crl rejectUnauthorized: false } { port: serverPort key: serverOptions.key cert: serverOptions.cert crl: serverOptions.crl NPNProtocols: [ "first-priority-unsupported" "x" "y" ] rejectUnauthorized: false } ] serverResults = [] clientsResults = [] server = tls.createServer(serverOptions, (c) -> serverResults.push c.npnProtocol return ) server.listen serverPort, startTest process.on "exit", -> assert.equal serverResults[0], clientsResults[0] assert.equal serverResults[1], clientsResults[1] assert.equal serverResults[2], "http/1.1" assert.equal clientsResults[2], false assert.equal serverResults[3], "first-priority-unsupported" assert.equal clientsResults[3], false return
91534
# 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. filenamePEM = (n) -> require("path").join common.fixturesDir, "keys", n + ".pem" loadPEM = (n) -> fs.readFileSync filenamePEM(n) startTest = -> connectClient = (options, callback) -> client = tls.connect(options, -> clientsResults.push client.npnProtocol client.destroy() callback() return ) return connectClient clientsOptions[0], -> connectClient clientsOptions[1], -> connectClient clientsOptions[2], -> connectClient clientsOptions[3], -> server.close() return return return return return unless process.features.tls_npn console.error "Skipping because node compiled without OpenSSL or " + "with old OpenSSL version." process.exit 0 common = require("../common") assert = require("assert") fs = require("fs") tls = require("tls") serverOptions = key: loadPEM("agent2-key") cert: loadPEM("agent2-cert") crl: loadPEM("ca2-crl") SNICallback: (servername, cb) -> cb null, tls.createSecureContext( key: loadPEM("agent2-key") cert: loadPEM("agent2-cert") crl: loadPEM("ca2-crl") ) return NPNProtocols: [ "a" "b" "c" ] serverPort = common.PORT clientsOptions = [ { port: serverPort key: serverOptions.key cert: serverOptions.cert crl: serverOptions.crl NPNProtocols: [ "a" "b" "c" ] rejectUnauthorized: false } { port: serverPort key: serverOptions.key cert: serverOptions.cert crl: serverOptions.crl NPNProtocols: [ "c" "b" "e" ] rejectUnauthorized: false } { port: serverPort key: serverOptions.key cert: serverOptions.cert crl: serverOptions.crl rejectUnauthorized: false } { port: serverPort key: serverOptions.key cert: serverOptions.cert crl: serverOptions.crl NPNProtocols: [ "first-priority-unsupported" "x" "y" ] rejectUnauthorized: false } ] serverResults = [] clientsResults = [] server = tls.createServer(serverOptions, (c) -> serverResults.push c.npnProtocol return ) server.listen serverPort, startTest process.on "exit", -> assert.equal serverResults[0], clientsResults[0] assert.equal serverResults[1], clientsResults[1] assert.equal serverResults[2], "http/1.1" assert.equal clientsResults[2], false assert.equal serverResults[3], "first-priority-unsupported" assert.equal clientsResults[3], false 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. filenamePEM = (n) -> require("path").join common.fixturesDir, "keys", n + ".pem" loadPEM = (n) -> fs.readFileSync filenamePEM(n) startTest = -> connectClient = (options, callback) -> client = tls.connect(options, -> clientsResults.push client.npnProtocol client.destroy() callback() return ) return connectClient clientsOptions[0], -> connectClient clientsOptions[1], -> connectClient clientsOptions[2], -> connectClient clientsOptions[3], -> server.close() return return return return return unless process.features.tls_npn console.error "Skipping because node compiled without OpenSSL or " + "with old OpenSSL version." process.exit 0 common = require("../common") assert = require("assert") fs = require("fs") tls = require("tls") serverOptions = key: loadPEM("agent2-key") cert: loadPEM("agent2-cert") crl: loadPEM("ca2-crl") SNICallback: (servername, cb) -> cb null, tls.createSecureContext( key: loadPEM("agent2-key") cert: loadPEM("agent2-cert") crl: loadPEM("ca2-crl") ) return NPNProtocols: [ "a" "b" "c" ] serverPort = common.PORT clientsOptions = [ { port: serverPort key: serverOptions.key cert: serverOptions.cert crl: serverOptions.crl NPNProtocols: [ "a" "b" "c" ] rejectUnauthorized: false } { port: serverPort key: serverOptions.key cert: serverOptions.cert crl: serverOptions.crl NPNProtocols: [ "c" "b" "e" ] rejectUnauthorized: false } { port: serverPort key: serverOptions.key cert: serverOptions.cert crl: serverOptions.crl rejectUnauthorized: false } { port: serverPort key: serverOptions.key cert: serverOptions.cert crl: serverOptions.crl NPNProtocols: [ "first-priority-unsupported" "x" "y" ] rejectUnauthorized: false } ] serverResults = [] clientsResults = [] server = tls.createServer(serverOptions, (c) -> serverResults.push c.npnProtocol return ) server.listen serverPort, startTest process.on "exit", -> assert.equal serverResults[0], clientsResults[0] assert.equal serverResults[1], clientsResults[1] assert.equal serverResults[2], "http/1.1" assert.equal clientsResults[2], false assert.equal serverResults[3], "first-priority-unsupported" assert.equal clientsResults[3], false return
[ { "context": " userId = Accounts.createUser\n username: 'admin'\n password: 'admin'\n email: 'admin@proj", "end": 132, "score": 0.9546324610710144, "start": 127, "tag": "USERNAME", "value": "admin" }, { "context": "eateUser\n username: 'admin'\n password: 'admin'\n email: 'admin@projectx.com'\n profile:", "end": 156, "score": 0.9992064833641052, "start": 151, "tag": "PASSWORD", "value": "admin" }, { "context": "me: 'admin'\n password: 'admin'\n email: 'admin@projectx.com'\n profile:\n fullname: 'Maxim Grischuk", "end": 190, "score": 0.9999249577522278, "start": 172, "tag": "EMAIL", "value": "admin@projectx.com" }, { "context": "n@projectx.com'\n profile:\n fullname: 'Maxim Grischuk'\n Roles.addUsersToRoles userId, 'admin'\n Wi", "end": 240, "score": 0.9998070001602173, "start": 226, "tag": "NAME", "value": "Maxim Grischuk" } ]
app/server/bootstrap/users.coffee
JSSolutions-Academy/Team-A
0
Meteor.startup -> usersNum = Meteor.users.find().count() unless usersNum userId = Accounts.createUser username: 'admin' password: 'admin' email: 'admin@projectx.com' profile: fullname: 'Maxim Grischuk' Roles.addUsersToRoles userId, 'admin' Winston.info "Added new admin user: #{userId}"
15489
Meteor.startup -> usersNum = Meteor.users.find().count() unless usersNum userId = Accounts.createUser username: 'admin' password: '<PASSWORD>' email: '<EMAIL>' profile: fullname: '<NAME>' Roles.addUsersToRoles userId, 'admin' Winston.info "Added new admin user: #{userId}"
true
Meteor.startup -> usersNum = Meteor.users.find().count() unless usersNum userId = Accounts.createUser username: 'admin' password: 'PI:PASSWORD:<PASSWORD>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' profile: fullname: 'PI:NAME:<NAME>END_PI' Roles.addUsersToRoles userId, 'admin' Winston.info "Added new admin user: #{userId}"
[ { "context": " else\n cmd = \"cd #{userfolder};git clone git@gist.github.com:#{gist.id}\"\n cmd = winshellCheck(cmd)\n ", "end": 2583, "score": 0.6968545317649841, "start": 2564, "tag": "EMAIL", "value": "git@gist.github.com" } ]
gist-cloner.coffee
enjalot/blocka-slurp
20
fs = require 'fs' d3 = require 'd3' async = require 'async' request = require 'request' path = require 'path' shell = require 'shelljs' os = require 'os' # we will log our progress in ES elasticsearch = require('elasticsearch') esConfig = require('./config.js').elasticsearch client = new elasticsearch.Client esConfig base = __dirname + "/data/gists-clones/" timeouts = [] winshellCheck = (cmd) -> return if os.platform() == 'win32' then cmd.replace(';','&') else cmd done = (err, pruned) -> console.log "done writing files" if timeouts.length console.log "timeouts", timeouts if singleId console.log "single id", singleId return if ids console.log "ids", ids return # log to elastic search summary = script: "content" timeouts: timeouts filename: metaFile ranAt: new Date() client.index index: 'bbindexer' type: 'scripts' body: summary , (err, response) -> console.log "indexed" process.exit() gistCloner = (gist, gistCb) -> # I wanted to actually clone all the repositories but it seems to be less reliable. # we get rate limited if we use https:// git urls # and the ssh ones disconnect unexpectedly, probably some sort of rate limiting but it doesn't show in # curl https://api.github.com/rate_limit return gistCb() if ids && (gist.id not in ids) return gistCb() if singleId && (gist.id != singleId) token = require('./config.js').github.token #console.log("token", token) if gist.owner user = gist.owner.login else user = 'anonymous' userfolder = base + user folder = userfolder + '/' + gist.id try fs.mkdirSync userfolder catch e foo = null #shell.cd(userfolder) # TODO don't use token in clone url (git init; git pull with token) #fs.lstat folder + "/.git", (err, stats) -> fs.lstat folder, (err, stats) -> # TODO check for files? if stats && stats.isDirectory() console.log "already got", gist.id # we want to be able to pull recently modified gists cmd = "cd #{userfolder}/#{gist.id}; git pull origin master" cmd = winshellCheck(cmd) shell.exec cmd, (code, huh, message) -> if code or message console.log gist.id, user, code, message else console.log "pulled #{gist.id} into #{user}'s folder'" setTimeout -> return gistCb() , 250 + Math.random() * 500 else if(token) cmd = "cd #{userfolder};git clone https://#{token}@gist.github.com/#{gist.id}" else cmd = "cd #{userfolder};git clone git@gist.github.com:#{gist.id}" cmd = winshellCheck(cmd) shell.exec cmd, (code, huh, message) -> if code or message console.log gist.id, user, code, message else console.log "cloned #{gist.id} into #{user}'s folder'" setTimeout -> gistCb() , 250 + Math.random() * 500 gistPuller = (gist, gistCb) -> ### # TODO: pull inside existing repositories console.log("exists, pulling", gist.id) shell.cd gist.id shell.exec 'git pull origin master', (code, huh, message) -> console.log("pulled", gist.id) return gistCb() ### module.exports = gistCloner: gistCloner if require.main == module fs.mkdir base, -> # specify the file to load, will probably be data/latest.json for our cron job metaFile = process.argv[2] || 'data/gist-meta.json' username = process.argv[3] || "" # optionally pass in a csv file or a single id to be downloaded param = process.argv[4] if param if param.indexOf(".csv") > 0 # list of ids to parse ids = d3.csv.parse(fs.readFileSync(singleId).toString()) else singleId = param console.log "doing content for single block", singleId gistMeta = JSON.parse fs.readFileSync(metaFile).toString() if username list = gistMeta.filter (d) -> return d.owner.login == username else list = gistMeta console.log "number of gists", list.length if singleId or ids async.each gistMeta, gistCloner, done else async.eachLimit list, 5, gistCloner, done #async.eachSeries gistMeta, gistCloner, done
113539
fs = require 'fs' d3 = require 'd3' async = require 'async' request = require 'request' path = require 'path' shell = require 'shelljs' os = require 'os' # we will log our progress in ES elasticsearch = require('elasticsearch') esConfig = require('./config.js').elasticsearch client = new elasticsearch.Client esConfig base = __dirname + "/data/gists-clones/" timeouts = [] winshellCheck = (cmd) -> return if os.platform() == 'win32' then cmd.replace(';','&') else cmd done = (err, pruned) -> console.log "done writing files" if timeouts.length console.log "timeouts", timeouts if singleId console.log "single id", singleId return if ids console.log "ids", ids return # log to elastic search summary = script: "content" timeouts: timeouts filename: metaFile ranAt: new Date() client.index index: 'bbindexer' type: 'scripts' body: summary , (err, response) -> console.log "indexed" process.exit() gistCloner = (gist, gistCb) -> # I wanted to actually clone all the repositories but it seems to be less reliable. # we get rate limited if we use https:// git urls # and the ssh ones disconnect unexpectedly, probably some sort of rate limiting but it doesn't show in # curl https://api.github.com/rate_limit return gistCb() if ids && (gist.id not in ids) return gistCb() if singleId && (gist.id != singleId) token = require('./config.js').github.token #console.log("token", token) if gist.owner user = gist.owner.login else user = 'anonymous' userfolder = base + user folder = userfolder + '/' + gist.id try fs.mkdirSync userfolder catch e foo = null #shell.cd(userfolder) # TODO don't use token in clone url (git init; git pull with token) #fs.lstat folder + "/.git", (err, stats) -> fs.lstat folder, (err, stats) -> # TODO check for files? if stats && stats.isDirectory() console.log "already got", gist.id # we want to be able to pull recently modified gists cmd = "cd #{userfolder}/#{gist.id}; git pull origin master" cmd = winshellCheck(cmd) shell.exec cmd, (code, huh, message) -> if code or message console.log gist.id, user, code, message else console.log "pulled #{gist.id} into #{user}'s folder'" setTimeout -> return gistCb() , 250 + Math.random() * 500 else if(token) cmd = "cd #{userfolder};git clone https://#{token}@gist.github.com/#{gist.id}" else cmd = "cd #{userfolder};git clone <EMAIL>:#{gist.id}" cmd = winshellCheck(cmd) shell.exec cmd, (code, huh, message) -> if code or message console.log gist.id, user, code, message else console.log "cloned #{gist.id} into #{user}'s folder'" setTimeout -> gistCb() , 250 + Math.random() * 500 gistPuller = (gist, gistCb) -> ### # TODO: pull inside existing repositories console.log("exists, pulling", gist.id) shell.cd gist.id shell.exec 'git pull origin master', (code, huh, message) -> console.log("pulled", gist.id) return gistCb() ### module.exports = gistCloner: gistCloner if require.main == module fs.mkdir base, -> # specify the file to load, will probably be data/latest.json for our cron job metaFile = process.argv[2] || 'data/gist-meta.json' username = process.argv[3] || "" # optionally pass in a csv file or a single id to be downloaded param = process.argv[4] if param if param.indexOf(".csv") > 0 # list of ids to parse ids = d3.csv.parse(fs.readFileSync(singleId).toString()) else singleId = param console.log "doing content for single block", singleId gistMeta = JSON.parse fs.readFileSync(metaFile).toString() if username list = gistMeta.filter (d) -> return d.owner.login == username else list = gistMeta console.log "number of gists", list.length if singleId or ids async.each gistMeta, gistCloner, done else async.eachLimit list, 5, gistCloner, done #async.eachSeries gistMeta, gistCloner, done
true
fs = require 'fs' d3 = require 'd3' async = require 'async' request = require 'request' path = require 'path' shell = require 'shelljs' os = require 'os' # we will log our progress in ES elasticsearch = require('elasticsearch') esConfig = require('./config.js').elasticsearch client = new elasticsearch.Client esConfig base = __dirname + "/data/gists-clones/" timeouts = [] winshellCheck = (cmd) -> return if os.platform() == 'win32' then cmd.replace(';','&') else cmd done = (err, pruned) -> console.log "done writing files" if timeouts.length console.log "timeouts", timeouts if singleId console.log "single id", singleId return if ids console.log "ids", ids return # log to elastic search summary = script: "content" timeouts: timeouts filename: metaFile ranAt: new Date() client.index index: 'bbindexer' type: 'scripts' body: summary , (err, response) -> console.log "indexed" process.exit() gistCloner = (gist, gistCb) -> # I wanted to actually clone all the repositories but it seems to be less reliable. # we get rate limited if we use https:// git urls # and the ssh ones disconnect unexpectedly, probably some sort of rate limiting but it doesn't show in # curl https://api.github.com/rate_limit return gistCb() if ids && (gist.id not in ids) return gistCb() if singleId && (gist.id != singleId) token = require('./config.js').github.token #console.log("token", token) if gist.owner user = gist.owner.login else user = 'anonymous' userfolder = base + user folder = userfolder + '/' + gist.id try fs.mkdirSync userfolder catch e foo = null #shell.cd(userfolder) # TODO don't use token in clone url (git init; git pull with token) #fs.lstat folder + "/.git", (err, stats) -> fs.lstat folder, (err, stats) -> # TODO check for files? if stats && stats.isDirectory() console.log "already got", gist.id # we want to be able to pull recently modified gists cmd = "cd #{userfolder}/#{gist.id}; git pull origin master" cmd = winshellCheck(cmd) shell.exec cmd, (code, huh, message) -> if code or message console.log gist.id, user, code, message else console.log "pulled #{gist.id} into #{user}'s folder'" setTimeout -> return gistCb() , 250 + Math.random() * 500 else if(token) cmd = "cd #{userfolder};git clone https://#{token}@gist.github.com/#{gist.id}" else cmd = "cd #{userfolder};git clone PI:EMAIL:<EMAIL>END_PI:#{gist.id}" cmd = winshellCheck(cmd) shell.exec cmd, (code, huh, message) -> if code or message console.log gist.id, user, code, message else console.log "cloned #{gist.id} into #{user}'s folder'" setTimeout -> gistCb() , 250 + Math.random() * 500 gistPuller = (gist, gistCb) -> ### # TODO: pull inside existing repositories console.log("exists, pulling", gist.id) shell.cd gist.id shell.exec 'git pull origin master', (code, huh, message) -> console.log("pulled", gist.id) return gistCb() ### module.exports = gistCloner: gistCloner if require.main == module fs.mkdir base, -> # specify the file to load, will probably be data/latest.json for our cron job metaFile = process.argv[2] || 'data/gist-meta.json' username = process.argv[3] || "" # optionally pass in a csv file or a single id to be downloaded param = process.argv[4] if param if param.indexOf(".csv") > 0 # list of ids to parse ids = d3.csv.parse(fs.readFileSync(singleId).toString()) else singleId = param console.log "doing content for single block", singleId gistMeta = JSON.parse fs.readFileSync(metaFile).toString() if username list = gistMeta.filter (d) -> return d.owner.login == username else list = gistMeta console.log "number of gists", list.length if singleId or ids async.each gistMeta, gistCloner, done else async.eachLimit list, 5, gistCloner, done #async.eachSeries gistMeta, gistCloner, done
[ { "context": "PropType definitions in React components\n# @author Evgueni Naverniouk\n###\n'use strict'\n\n# -----------------------------", "end": 108, "score": 0.9998459219932556, "start": 90, "tag": "NAME", "value": "Evgueni Naverniouk" }, { "context": "ers = this.props.users.find(user => user.name is 'John')\"\n # ' return <div>Hello you {users.le", "end": 12437, "score": 0.9987499713897705, "start": 12433, "tag": "NAME", "value": "John" }, { "context": "two test cases are related to: https://github.com/yannickcr/eslint-plugin-react/issues/1183\n code: '''\n ", "end": 34030, "score": 0.999727725982666, "start": 34021, "tag": "USERNAME", "value": "yannickcr" }, { "context": " ' render: ->'\n \" props = {firstname: 'John'}\"\n ' return <div>Hello {props.firstname}", "end": 68956, "score": 0.9976014494895935, "start": 68952, "tag": "NAME", "value": "John" }, { "context": ",'\n ' render: ->'\n ' return <div>Hello Bob</div>'\n '})'\n ].join '\\n'\n errors: [me", "end": 93490, "score": 0.9876371622085571, "start": 93487, "tag": "NAME", "value": "Bob" }, { "context": "ollowing issue is fixed\n # https:#github.com/yannickcr/eslint-plugin-react/issues/296\n code: [\n ", "end": 109537, "score": 0.9996896386146545, "start": 109528, "tag": "USERNAME", "value": "yannickcr" } ]
src/tests/rules/no-unused-prop-types.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Warn about unused PropType definitions in React components # @author Evgueni Naverniouk ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/no-unused-prop-types' {RuleTester} = require 'eslint' path = require 'path' settings = react: pragma: 'Foo' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-unused-prop-types', rule, valid: [ code: ''' Hello = createReactClass propTypes: name: PropTypes.string.isRequired render: -> <div>Hello {@props.name}</div> ''' , code: ''' Hello = createReactClass({ propTypes: { name: PropTypes.object.isRequired }, render: -> return <div>Hello {this.props.name.firstname}</div> }) ''' , code: ''' Hello = createReactClass({ render: -> return <div>Hello World</div> }) ''' , code: ''' Hello = createReactClass({ render: -> props = this.props return <div>Hello World</div> }) ''' , code: ''' Hello = createReactClass({ render: -> propName = "foo" return <div>Hello World {this.props[propName]}</div> }) ''' , code: ''' Hello = createReactClass({ propTypes: externalPropTypes, render: -> return <div>Hello {this.props.name}</div> }) ''' , code: ''' Hello = createReactClass({ propTypes: externalPropTypes.mySharedPropTypes, render: -> return <div>Hello {this.props.name}</div> }) ''' , code: ''' class Hello extends React.Component render: -> return <div>Hello World</div> ''' , code: ''' class Hello extends React.Component render: -> return <div>Hello {this.props.firstname} {this.props.lastname}</div> Hello.propTypes = { firstname: PropTypes.string } Hello.propTypes.lastname = PropTypes.string ''' , code: ''' Hello = createReactClass({ propTypes: { name: PropTypes.object.isRequired }, render: -> user = { name: this.props.name } return <div>Hello {user.name}</div> }) ''' , code: ''' class Hello render: -> return 'Hello' + this.props.name ''' , # , # code: ''' # class Hello extends React.Component { # static get propTypes() { # return { # name: PropTypes.string # } # } # ' render() { # ' return <div>Hello {this.props.name}</div> # ' } # '} # ''' # Props validation is ignored when spread is used code: ''' class Hello extends React.Component render: -> { firstname, ...props } = this.props { category, icon } = props return <div>Hello {firstname}</div> Hello.propTypes = { firstname: PropTypes.string, category: PropTypes.string, icon: PropTypes.bool } ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component render: -> {firstname, lastname} = this.state something = this.props return <div>Hello {firstname}</div> ''' , code: ''' class Hello extends React.Component @propTypes = { name: PropTypes.string } render: -> return <div>Hello {this.props.name}</div> ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component render: -> return <div>Hello {this.props.firstname}</div> Hello.propTypes = { 'firstname': PropTypes.string } ''' , code: ''' class Hello extends React.Component render: -> if (Object.prototype.hasOwnProperty.call(this.props, 'firstname')) return <div>Hello {this.props.firstname}</div> Hello.propTypes = { 'firstname': PropTypes.string } ''' , code: ''' class Hello extends React.Component render: -> this.props.a.b return <div>Hello</div> Hello.propTypes = {} Hello.propTypes.a = PropTypes.shape({ b: PropTypes.string }) ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> this.props.a.b.c return <div>Hello</div> Hello.propTypes = { a: PropTypes.shape({ b: PropTypes.shape({ }) }) } Hello.propTypes.a.b.c = PropTypes.number ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> this.props.a.b.c this.props.a.__.d.length this.props.a.anything.e[2] return <div>Hello</div> Hello.propTypes = { a: PropTypes.objectOf( PropTypes.shape({ c: PropTypes.number, d: PropTypes.string, e: PropTypes.array }) ) } ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> i = 3 this.props.a[2].c this.props.a[i].d.length this.props.a[i + 2].e[2] this.props.a.length return <div>Hello</div> Hello.propTypes = { a: PropTypes.arrayOf( PropTypes.shape({ c: PropTypes.number, d: PropTypes.string, e: PropTypes.array }) ) } ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> this.props.a.length return <div>Hello</div> Hello.propTypes = { a: PropTypes.oneOfType([ PropTypes.array, PropTypes.string ]) } ''' , code: ''' class Hello extends React.Component render: -> this.props.a.c this.props.a[2] is true this.props.a.e[2] this.props.a.length return <div>Hello</div> Hello.propTypes = { a: PropTypes.oneOfType([ PropTypes.shape({ c: PropTypes.number, e: PropTypes.array }).isRequired, PropTypes.arrayOf( PropTypes.bool ) ]) } ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> this.props.a.render this.props.a.c return <div>Hello</div> Hello.propTypes = { a: PropTypes.instanceOf(Hello) } ''' , code: ''' class Hello extends React.Component render: -> this.props.arr this.props.arr[3] this.props.arr.length this.props.arr.push(3) this.props.bo this.props.bo.toString() this.props.fu this.props.fu.bind(this) this.props.numb this.props.numb.toFixed() this.props.stri this.props.stri.length() return <div>Hello</div> Hello.propTypes = { arr: PropTypes.array, bo: PropTypes.bool.isRequired, fu: PropTypes.func, numb: PropTypes.number, stri: PropTypes.string } ''' , code: ''' class Hello extends React.Component render: -> { propX, "aria-controls": ariaControls, ...props } = this.props return <div>Hello</div> Hello.propTypes = { "propX": PropTypes.string, "aria-controls": PropTypes.string } ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component render: -> this.props["some.value"] return <div>Hello</div> Hello.propTypes = { "some.value": PropTypes.string } ''' , code: ''' class Hello extends React.Component render: -> this.props["arr"][1] return <div>Hello</div> Hello.propTypes = { "arr": PropTypes.array } ''' , code: ''' class Hello extends React.Component render: -> this.props["arr"][1]["some.value"] return <div>Hello</div> Hello.propTypes = { "arr": PropTypes.arrayOf( PropTypes.shape({"some.value": PropTypes.string}) ) } ''' options: [skipShapeProps: no] , code: ''' TestComp1 = createReactClass({ propTypes: { size: PropTypes.string }, render: -> foo = { baz: 'bar' } icons = foo[this.props.size].salut return <div>{icons}</div> }) ''' , code: ''' class Hello extends React.Component render: -> {firstname, lastname} = this.props.name return <div>{firstname} {lastname}</div> Hello.propTypes = { name: PropTypes.shape({ firstname: PropTypes.string, lastname: PropTypes.string }) } ''' options: [skipShapeProps: no] , # parser: 'babel-eslint' code: ''' class Hello extends React.Component render: -> {firstname} = this return <div>{firstname}</div> ''' , # parser: 'babel-eslint' code: ''' Hello = createReactClass({ propTypes: { router: PropTypes.func }, render: -> nextPath = this.props.router.getCurrentQuery().nextPath return <div>{nextPath}</div> }) ''' , code: ''' Hello = createReactClass({ propTypes: { firstname: CustomValidator.string }, render: -> return <div>{this.props.firstname}</div> }) ''' options: [customValidators: ['CustomValidator']] , code: ''' Hello = createReactClass({ propTypes: { outer: CustomValidator.shape({ inner: CustomValidator.map }) }, render: -> return <div>{this.props.outer.inner}</div> }) ''' options: [customValidators: ['CustomValidator'], skipShapeProps: no] , code: ''' Hello = createReactClass({ propTypes: { outer: PropTypes.shape({ inner: CustomValidator.string }) }, render: -> return <div>{this.props.outer.inner}</div> }) ''' options: [customValidators: ['CustomValidator'], skipShapeProps: no] , code: ''' Hello = createReactClass({ propTypes: { outer: CustomValidator.shape({ inner: PropTypes.string }) }, render: -> return <div>{this.props.outer.inner}</div> }) ''' options: [customValidators: ['CustomValidator'], skipShapeProps: no] , code: ''' Hello = createReactClass({ propTypes: { name: PropTypes.string }, render: -> return <div>{this.props.name.get("test")}</div> }) ''' options: [customValidators: ['CustomValidator']] , code: ''' SomeComponent = createReactClass({ propTypes: SomeOtherComponent.propTypes }) ''' , # parser: 'babel-eslint code: ''' Hello = createReactClass({ render: -> { a, ...b } = obj c = { ...d } return <div /> }) ''' , # , # code: [ # 'class Hello extends React.Component {' # ' static get propTypes() {}' # ' render() ->' # ' return <div>Hello World</div>' # ' }' # '}' # ].join '\n' # , # code: [ # 'class Hello extends React.Component {' # ' static get propTypes() {}' # ' render() ->' # " users = this.props.users.find(user => user.name is 'John')" # ' return <div>Hello you {users.length}</div>' # ' }' # '}' # 'Hello.propTypes = {' # ' users: PropTypes.arrayOf(PropTypes.object)' # '}' # ].join '\n' code: ''' class Hello extends React.Component render: -> {} = this.props return <div>Hello</div> ''' , code: ''' class Hello extends React.Component render: -> foo = 'fullname' { [foo]: firstname } = this.props return <div>Hello {firstname}</div> ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component constructor: (props, context) -> super(props, context) this.state = { status: props.source.uri } @propTypes = { source: PropTypes.object } ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component constructor: (props, context) -> super(props, context) this.state = { status: this.props.source.uri } @propTypes = { source: PropTypes.object } ''' , # parser: 'babel-eslint' # Should not be detected as a component code: ''' HelloJohn.prototype.render = -> return React.createElement(Hello, { name: this.props.firstname }) ''' , # parser: 'babel-eslint' code: ''' HelloComponent = -> class Hello extends React.Component render: -> return <div>Hello {this.props.name}</div> Hello.propTypes = { name: PropTypes.string } return Hello module.exports = HelloComponent() ''' , # parser: 'babel-eslint' code: ''' HelloComponent = -> Hello = createReactClass({ propTypes: { name: PropTypes.string }, render: -> return <div>Hello {this.props.name}</div> }) return Hello module.exports = HelloComponent() ''' , # parser: 'babel-eslint' code: ''' class DynamicHello extends Component render: -> {firstname} = this.props class Hello extends Component render: -> {name} = this.props return <div>Hello {name}</div> Hello.propTypes = { name: PropTypes.string } return <Hello /> DynamicHello.propTypes = { firstname: PropTypes.string, } ''' , # parser: 'babel-eslint' code: ''' Hello = (props) => team = props.names.map (name) => return <li>{name}, {props.company}</li> return <ul>{team}</ul> Hello.propTypes = { names: PropTypes.array, company: PropTypes.string } ''' , # parser: 'babel-eslint' code: ''' export default { renderHello: -> {name} = this.props return <div>{name}</div> } ''' , # parser: 'babel-eslint' # Reassigned props are ignored code: ''' export class Hello extends Component render: -> props = this.props return <div>Hello {props.name.firstname} {props['name'].lastname}</div> ''' , # parser: 'babel-eslint' code: ''' export default FooBar = (props) -> bar = props.bar return (<div bar={bar}><div {...props}/></div>) if (process.env.NODE_ENV isnt 'production') FooBar.propTypes = { bar: PropTypes.string } ''' , # parser: 'babel-eslint' code: ''' Hello = createReactClass({ render: -> {...other} = this.props return ( <div {...other} /> ) }) ''' , code: ''' notAComponent = ({ something }) -> return something + 1 ''' , code: ''' notAComponent = ({ something }) -> something + 1 ''' , # Validation is ignored on reassigned props object code: ''' statelessComponent = (props) => newProps = props return <span>{newProps.someProp}</span> ''' , # parser: 'babel-eslint' # Ignore component validation if propTypes are composed using spread code: ''' class Hello extends React.Component render: -> return <div>Hello {this.props.firstName} {this.props.lastName}</div> otherPropTypes = { lastName: PropTypes.string } Hello.propTypes = { ...otherPropTypes, firstName: PropTypes.string } ''' , # Ignore destructured function arguments code: ''' class Hello extends React.Component render: -> return ["string"].map ({length}) => <div>{length}</div> ''' , code: ''' Card.propTypes = { title: PropTypes.string.isRequired, children: PropTypes.element.isRequired, footer: PropTypes.node } Card = ({ title, children, footer }) -> return ( <div/> ) ''' , code: ''' JobList = (props) -> props .jobs .forEach(() => {}) return <div></div> JobList.propTypes = { jobs: PropTypes.array } ''' , # parser: 'babel-eslint' code: ''' Greetings = -> return <div>{({name}) => <Hello name={name} />}</div> ''' , # parser: 'babel-eslint' code: ''' Greetings = -> <div>{({name}) -> return <Hello name={name} />}</div> ''' , # parser: 'babel-eslint' # Should stop at the class when searching for a parent component code: ''' export default (ComposedComponent) => class Something extends SomeOtherComponent someMethod = ({width}) => {} ''' , # parser: 'babel-eslint # Destructured shape props are skipped by default code: ''' class Hello extends Component @propTypes = { params: PropTypes.shape({ id: PropTypes.string }) } render: -> {params} = this.props id = (params || {}).id return <span>{id}</span> ''' , # parser: 'babel-eslint' # Destructured props in componentWillReceiveProps shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) ''' , # parser: 'babel-eslint' # Destructured props in componentWillReceiveProps shouldn't throw errors code: ''' class Hello extends Component componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in componentWillReceiveProps shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) }) ''' , # parser: 'babel-eslint' # Destructured props in componentWillReceiveProps shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) }) ''' , # Destructured function props in componentWillReceiveProps shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentWillReceiveProps: ({something}) -> doSomething(something) ''' , # parser: 'babel-eslint' # Destructured function props in componentWillReceiveProps shouldn't throw errors code: ''' class Hello extends Component componentWillReceiveProps: ({something}) -> doSomething(something) Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in componentWillReceiveProps shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillReceiveProps: ({something}) -> doSomething(something) }) ''' , # parser: 'babel-eslint' # Destructured function props in componentWillReceiveProps shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillReceiveProps: ({something}) -> doSomething(something) }) ''' , # Destructured props in the constructor shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } constructor: (props) -> super(props) {something} = props doSomething(something) ''' , # parser: 'babel-eslint' # Destructured props in the constructor shouldn't throw errors code: ''' class Hello extends Component constructor: (props) -> super(props) {something} = props doSomething(something) Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in the constructor shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } constructor: ({something}) -> super({something}) doSomething(something) ''' , # parser: 'babel-eslint' # Destructured function props in the constructor shouldn't throw errors code: ''' class Hello extends Component constructor: ({something}) -> super({something}) doSomething(something) Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in the `shouldComponentUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } shouldComponentUpdate: (nextProps, nextState) -> {something} = nextProps return something ''' , # parser: 'babel-eslint' # Destructured props in the `shouldComponentUpdate` method shouldn't throw errors code: ''' class Hello extends Component shouldComponentUpdate: (nextProps, nextState) -> {something} = nextProps return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in `shouldComponentUpdate` shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, shouldComponentUpdate: (nextProps, nextState) -> {something} = nextProps return something }) ''' , # parser: 'babel-eslint' # Destructured props in `shouldComponentUpdate` shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, shouldComponentUpdate: (nextProps, nextState) -> {something} = nextProps return something }) ''' , # Destructured function props in the `shouldComponentUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } shouldComponentUpdate: ({something}, nextState) -> return something ''' , # parser: 'babel-eslint' # Destructured function props in the `shouldComponentUpdate` method shouldn't throw errors code: ''' class Hello extends Component shouldComponentUpdate: ({something}, nextState) -> return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in `shouldComponentUpdate` shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, shouldComponentUpdate: ({something}, nextState) -> return something }) ''' , # parser: 'babel-eslint' # Destructured function props in `shouldComponentUpdate` shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, shouldComponentUpdate: ({something}, nextState) -> return something }) ''' , # Destructured props in the `componentWillUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something ''' , # parser: 'babel-eslint' # Destructured props in the `componentWillUpdate` method shouldn't throw errors code: ''' class Hello extends Component componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in `componentWillUpdate` shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something }) ''' , # parser: 'babel-eslint' # Destructured props in `componentWillUpdate` shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something }) ''' , # Destructured function props in the `componentWillUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentWillUpdate: ({something}, nextState) -> return something ''' , # parser: 'babel-eslint' # Destructured function props in the `componentWillUpdate` method shouldn't throw errors code: ''' class Hello extends Component componentWillUpdate: ({something}, nextState) -> return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in the `componentWillUpdate` method shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillUpdate: ({something}, nextState) -> return something }) ''' , # parser: 'babel-eslint' # Destructured function props in the `componentWillUpdate` method shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillUpdate: ({something}, nextState) -> return something }) ''' , # Destructured props in the `componentDidUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentDidUpdate: (prevProps, prevState) -> {something} = prevProps return something ''' , # parser: 'babel-eslint' # Destructured props in the `componentDidUpdate` method shouldn't throw errors code: ''' class Hello extends Component componentDidUpdate: (prevProps, prevState) -> {something} = prevProps return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in `componentDidUpdate` shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: (prevProps, prevState) -> {something} = prevProps return something }) ''' , # parser: 'babel-eslint' # Destructured props in `componentDidUpdate` shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: (prevProps, prevState) -> {something} = prevProps return something }) ''' , # Destructured function props in the `componentDidUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentDidUpdate: ({something}, prevState) -> return something ''' , # parser: 'babel-eslint' # Destructured function props in the `componentDidUpdate` method shouldn't throw errors code: ''' class Hello extends Component componentDidUpdate: ({something}, prevState) -> return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in the `componentDidUpdate` method shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: ({something}, prevState) -> return something }) ''' , # parser: 'babel-eslint' # Destructured function props in the `componentDidUpdate` method shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: ({something}, prevState) -> return something }) ''' , # Destructured state props in `componentDidUpdate` [Issue #825] code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentDidUpdate: ({something}, {state1, state2}) -> return something ''' , # parser: 'babel-eslint' # Destructured state props in `componentDidUpdate` [Issue #825] code: ''' class Hello extends Component componentDidUpdate: ({something}, {state1, state2}) -> return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured state props in `componentDidUpdate` [Issue #825] when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: ({something}, {state1, state2}) -> return something }) ''' , # parser: 'babel-eslint' # Destructured state props in `componentDidUpdate` without custom parser [Issue #825] code: ''' Hello = React.Component({ propTypes: { something: PropTypes.bool }, componentDidUpdate: ({something}, {state1, state2}) -> return something }) ''' , # Destructured state props in `componentDidUpdate` without custom parser [Issue #825] when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: ({something}, {state1, state2}) -> return something }) ''' , # Destructured props in a stateless function code: ''' Hello = (props) => {...rest} = props return <div /> ''' , # `no-unused-prop-types` in jsx expressions - [Issue #885] code: ''' PagingBlock = (props) -> return ( <span> <a onClick={() => props.previousPage()}/> <a onClick={() => props.nextPage()}/> </span> ) PagingBlock.propTypes = { nextPage: PropTypes.func.isRequired, previousPage: PropTypes.func.isRequired, } ''' , # `no-unused-prop-types` rest param props in jsx expressions - [Issue #885] code: ''' PagingBlock = (props) -> return ( <SomeChild {...props} /> ) PagingBlock.propTypes = { nextPage: PropTypes.func.isRequired, previousPage: PropTypes.func.isRequired, } ''' , code: ''' class Hello extends Component componentWillReceiveProps: (nextProps) -> if (nextProps.foo) doSomething(this.props.bar) Hello.propTypes = { foo: PropTypes.bool, bar: PropTypes.bool } ''' , # The next two test cases are related to: https://github.com/yannickcr/eslint-plugin-react/issues/1183 code: ''' export default SomeComponent = (props) -> callback = () => props.a(props.b) anotherCallback = () => {} return ( <SomeOtherComponent name={props.c} callback={callback} /> ) SomeComponent.propTypes = { a: React.PropTypes.func.isRequired, b: React.PropTypes.string.isRequired, c: React.PropTypes.string.isRequired, } ''' , code: [ 'export default SomeComponent = (props) ->' ' callback = () =>' ' props.a(props.b)' '' ' return (' ' <SomeOtherComponent' ' name={props.c}' ' callback={callback}' ' />' ' )' '' 'SomeComponent.propTypes = {' ' a: React.PropTypes.func.isRequired,' ' b: React.PropTypes.string.isRequired,' ' c: React.PropTypes.string.isRequired,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' shouldComponentUpdate: (props) ->' ' if (props.foo)' ' return true' '' ' render() ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' shouldComponentUpdate: (props) ->' ' if (props.foo)' ' return true' '' ' render() ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentWillUpdate: (props) ->' ' if (props.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' componentWillUpdate: (props) ->' ' if (props.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentWillReceiveProps: (nextProps) ->' ' {foo} = nextProps' ' if (foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' # Props used inside of an async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' }' ' classProperty: () =>' ' await @props.foo()' ].join '\n' , # parser: 'babel-eslint' # Multiple props used inside of an async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' classProperty = () =>' ' await this.props.foo()' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' componentWillReceiveProps: (props) ->' ' if (props.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' shouldComponentUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' # Destructured props inside of async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' }' ' classProperty: =>' ' { foo } = this.props' ' await foo()' ].join '\n' , # parser: 'babel-eslint' # Multiple destructured props inside of async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' classProperty: =>' ' { foo, bar, baz } = this.props' ' await foo()' ' await bar()' ' await baz()' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' shouldComponentUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentWillUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' # Props used inside of an async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' }' ' method: ->' ' await this.props.foo()' ].join '\n' , # parser: 'babel-eslint' # Multiple props used inside of an async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' method: ->' ' await this.props.foo()' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' , # parser: 'babel-eslint' # Destrucuted props inside of async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' }' ' method: ->' ' { foo } = this.props' ' await foo()' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' componentWillUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentDidUpdate: (prevProps) ->' ' if (prevProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' # Multiple destructured props inside of async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' method: ->' ' { foo, bar, baz } = this.props' ' await foo()' ' await bar()' ' await baz()' ].join '\n' , # parser: 'babel-eslint' # factory functions that return async functions code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' factory: ->' ' return () =>' ' await this.props.foo()' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' , # parser: 'babel-eslint' # factory functions that return async functions code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' factory: ->' ' return ->' ' await this.props.foo()' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' componentDidUpdate: (prevProps) ->' ' if (prevProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , # Multiple props used inside of an async method code: [ 'class Example extends Component' ' method: ->' ' await this.props.foo()' ' await this.props.bar()' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' '}' ].join '\n' , # Multiple props used inside of an async function code: [ 'class Example extends Component' ' render: ->' ' onSubmit = ->' ' await this.props.foo()' ' await this.props.bar()' ' return <Form onSubmit={onSubmit} />' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' '}' ].join '\n' , # Multiple props used inside of an async arrow function code: [ 'class Example extends Component' ' render: ->' ' onSubmit = =>' ' await this.props.foo()' ' await this.props.bar()' ' return <Form onSubmit={onSubmit} />' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' '}' ].join '\n' , # Destructured assignment with Shape propTypes issue #816 code: [ 'export default class NavigationButton extends React.Component' ' @propTypes = {' ' route: PropTypes.shape({' ' getBarTintColor: PropTypes.func.isRequired,' ' }).isRequired,' ' }' ' renderTitle: ->' ' { route } = this.props' ' return <Title tintColor={route.getBarTintColor()}>TITLE</Title>' ].join '\n' , # parser: 'babel-eslint' # Destructured assignment without Shape propTypes issue #816 code: [ 'Component = ({ children: aNode }) => (' ' <div>{aNode}</div>' ')' 'Component.defaultProps = {' ' children: null,' '}' 'Component.propTypes = {' ' children: React.PropTypes.node,' '}' ].join '\n' , # issue 1309 code: [ 'Thing = (props) => (' ' <div>' ' {(() =>' ' if(props.enabled && props.test)' ' return (' ' <span>Enabled!</span>' ' )' ' return (' ' <span>Disabled..</span>' ' )' ' )()}' ' </div>' ')' 'Thing.propTypes = {' ' enabled: React.PropTypes.bool,' ' test: React.PropTypes.bool' '}' ].join '\n' , code: [ 'Thing = (props) => (' ' <div>' ' {do =>' ' if(props.enabled && props.test)' ' return (' ' <span>Enabled!</span>' ' )' ' return (' ' <span>Disabled..</span>' ' )' ' }' ' </div>' ')' 'Thing.propTypes = {' ' enabled: React.PropTypes.bool,' ' test: React.PropTypes.bool' '}' ].join '\n' , # issue 1107 code: [ 'Test = (props) => <div>' ' {someArray.map (l) => <div' ' key={l}>' ' {props.property + props.property2}' ' </div>}' '</div>' 'Test.propTypes = {' ' property: React.propTypes.string.isRequired,' ' property2: React.propTypes.string.isRequired' '}' ].join '\n' , # issue 811 code: [ 'Button = React.createClass({' ' displayName: "Button",' ' propTypes: {' ' name: React.PropTypes.string.isRequired,' ' isEnabled: React.PropTypes.bool.isRequired' ' },' ' render: ->' ' item = this.props' ' disabled = !this.props.isEnabled' ' return (' ' <div>' ' <button type="button" disabled={disabled}>{item.name}</button>' ' </div>' ' )' '})' ].join '\n' , # issue 811 code: [ 'class Foo extends React.Component' ' @propTypes = {' ' foo: PropTypes.func.isRequired,' ' }' ' constructor: (props) ->' ' super(props)' ' { foo } = props' ' this.message = foo("blablabla")' ' render: ->' ' return <div>{this.message}</div>' ].join '\n' , # parser: 'babel-eslint' # issue #1097 code: [ 'class HelloGraphQL extends Component' ' render: ->' ' return <div>Hello</div>' 'HellowQueries = graphql(queryDetails, {' ' options: (ownProps) => ({' ' variables: ownProps.aProp' ' }),' '})(HelloGraphQL)' 'HellowQueries.propTypes = {' ' aProp: PropTypes.string.isRequired' '}' 'export default connect(mapStateToProps, mapDispatchToProps)(HellowQueries)' ].join '\n' , # parser: 'babel-eslint' # issue #1335 # code: [ # 'type Props = {' # ' foo: {' # ' bar: boolean' # ' }' # '}' # 'class DigitalServices extends React.Component' # ' props: Props' # ' render: ->' # ' { foo } = this.props' # ' return <div>{foo.bar}</div>' # ' }' # '}' # ].join '\n' # , # parser: 'babel-eslint' code: [ 'foo = {}' 'class Hello extends React.Component' ' render: ->' ' {firstname, lastname} = this.props.name' ' return <div>{firstname} {lastname}</div>' 'Hello.propTypes = {' ' name: PropTypes.shape(foo)' '}' ].join '\n' , # , # # parser: 'babel-eslint' # # issue #933 # code: [ # 'type Props = {' # ' onMouseOver: Function,' # ' onClick: Function,' # '}' # 'MyComponent = (props: Props) => (' # '<div>' # ' <button onMouseOver={() => props.onMouseOver()} />' # ' <button onClick={() => props.onClick()} />' # '</div>' # ')' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState, props) =>' ' props.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' 'tempVar2' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] , # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState, { doSomething }) =>' ' doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] , # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState, obj) =>' ' obj.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' 'tempVar2' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] , # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState(() =>' ' this.props.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' 'tempVar' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] , # issue #1542 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState) =>' ' this.props.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' options: [skipShapeProps: no] , # issue #1542 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState(({ something }) =>' ' this.props.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' options: [skipShapeProps: no] , # issue #106 code: ''' import React from 'react' import SharedPropTypes from './SharedPropTypes' export default class A extends React.Component render: -> return ( <span a={this.props.a} b={this.props.b} c={this.props.c}> {this.props.children} </span> ) A.propTypes = { a: React.PropTypes.string, ...SharedPropTypes # eslint-disable-line object-shorthand } ''' , # , # # parser: 'babel-eslint' # # issue #933 # code: """ # type Props = { # +foo: number # } # class MyComponent extends React.Component # render: -> # return <div>{this.props.foo}</div> # } # } # """ # , # # parser: 'babel-eslint' # code: """ # type Props = { # \'completed?\': boolean, # } # Hello = (props: Props): React.Element => { # return <div>{props[\'completed?\']}</div> # } # """ # , # # parser: 'babel-eslint' # code: """ # type Person = { # firstname: string # } # class MyComponent extends React.Component<void, Props, void> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # , # # parser: 'babel-eslint' # code: """ # type Person = { # firstname: string # } # class MyComponent extends React.Component<void, Props, void> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # settings: react: flowVersion: '0.52' # , # # parser: 'babel-eslint' # code: """ # type Person = { # firstname: string # } # class MyComponent extends React.Component<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # , # # parser: 'babel-eslint' # code: """ # type Person = { # firstname: string # } # class MyComponent extends React.Component<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # settings: react: flowVersion: '0.53' # parser: 'babel-eslint' # Issue #1068 code: ''' class MyComponent extends Component @propTypes = { validate: PropTypes.bool, options: PropTypes.array, value: ({options, value, validate}) => if (!validate) then return if (options.indexOf(value) < 0) throw new Errow('oops') } render: -> return <ul> {this.props.options.map((option) => <li className={this.props.value == option && "active"}>{option}</li> )} </ul> ''' , # parser: 'babel-eslint' # Issue #1068 code: ''' class MyComponent extends Component @propTypes = { validate: PropTypes.bool, options: PropTypes.array, value: ({options, value, validate}) -> if (!validate) then return if (options.indexOf(value) < 0) throw new Errow('oops') } render: -> return <ul> {this.props.options.map((option) => <li className={this.props.value == option && "active"}>{option}</li> )} </ul> ''' , # parser: 'babel-eslint' # Issue #1068 code: ''' class MyComponent extends Component @propTypes = { validate: PropTypes.bool, options: PropTypes.array, value: ({options, value, validate}) -> if (!validate) then return if (options.indexOf(value) < 0) throw new Errow('oops') } render: -> return <ul> {this.props.options.map((option) => <li className={this.props.value == option && "active"}>{option}</li> )} </ul> ''' , # parser: 'babel-eslint' code: ''' class MyComponent extends React.Component render: -> return <div>{ this.props.other }</div> MyComponent.propTypes = { other: () => {} } ''' , # Sanity test coverage for new UNSAFE_componentWillReceiveProps lifecycles code: [ ''' class Hello extends Component @propTypes = { something: PropTypes.bool } UNSAFE_componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) ''' ].join '\n' settings: react: version: '16.3.0' , # parser: 'babel-eslint' # Destructured props in the `UNSAFE_componentWillUpdate` method shouldn't throw errors code: [ ''' class Hello extends Component @propTypes = { something: PropTypes.bool } UNSAFE_componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something ''' ].join '\n' settings: react: version: '16.3.0' , # parser: 'babel-eslint' # Simple test of new @getDerivedStateFromProps lifecycle code: [ ''' class MyComponent extends React.Component @propTypes = { defaultValue: 'bar' } state = { currentValue: null } @getDerivedStateFromProps: (nextProps, prevState) -> if (prevState.currentValue is null) return { currentValue: nextProps.defaultValue, } return null render: -> return <div>{ this.state.currentValue }</div> ''' ].join '\n' settings: react: version: '16.3.0' , # parser: 'babel-eslint' # Simple test of new @getSnapshotBeforeUpdate lifecycle code: [ ''' class MyComponent extends React.Component @propTypes = { defaultValue: PropTypes.string } getSnapshotBeforeUpdate: (prevProps, prevState) -> if (prevProps.defaultValue is null) return 'snapshot' return null render: -> return <div /> ''' ].join '\n' settings: react: version: '16.3.0' , # , # # parser: 'babel-eslint' # # Impossible intersection type # code: """ # import React from 'react' # type Props = string & { # fullname: string # } # class Test extends React.PureComponent<Props> { # render: -> # return <div>Hello {this.props.fullname}</div> # } # } # """ # , # # parser: 'babel-eslint' # code: [ # "import type {BasePerson} from './types'" # 'type Props = {' # ' person: {' # ' ...$Exact<BasePerson>,' # ' lastname: string' # ' }' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.person.firstname}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' code: [ "import BasePerson from './types'" 'class Hello extends React.Component' ' render : ->' ' return <div>Hello {this.props.person.firstname}</div>' 'Hello.propTypes = {' ' person: ProTypes.shape({' ' ...BasePerson,' ' lastname: PropTypes.string' ' })' '}' ].join '\n' ] invalid: [ code: [ 'Hello = createReactClass({' ' propTypes: {' ' unused: PropTypes.string' ' },' ' render: ->' ' return React.createElement("div", {}, this.props.value)' '})' ].join '\n' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'Hello = createReactClass({' ' propTypes: {' ' name: PropTypes.string' ' },' ' render: ->' ' return <div>Hello {this.props.value}</div>' '})' ].join '\n' errors: [ message: "'name' PropType is defined but prop is never used" line: 3 column: 11 ] , code: [ 'class Hello extends React.Component' ' @propTypes = {' ' name: PropTypes.string' ' }' ' render: ->' ' return <div>Hello {this.props.value}</div>' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'name' PropType is defined but prop is never used" line: 3 column: 11 ] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello {this.props.firstname} {this.props.lastname}</div>' 'Hello.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello {this.props.name}</div>' 'Hello.propTypes = {' ' unused: PropTypes.string' '}' 'class HelloBis extends React.Component' ' render: ->' ' return <div>Hello {this.props.name}</div>' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = createReactClass({' ' propTypes: {' ' unused: PropTypes.string.isRequired,' ' anotherunused: PropTypes.string.isRequired' ' },' ' render: ->' ' return <div>Hello {this.props.name} and {this.props.propWithoutTypeDefinition}</div>' '})' 'Hello2 = createReactClass({' ' render: ->' ' return <div>Hello {this.props.name}</div>' '})' ].join '\n' errors: [ message: "'unused' PropType is defined but prop is never used" , message: "'anotherunused' PropType is defined but prop is never used" ] , code: [ 'class Hello extends React.Component' ' render: ->' ' { firstname, lastname } = this.props' ' return <div>Hello</div>' 'Hello.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props.a.z' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.shape({' ' b: PropTypes.string' ' })' '}' ].join '\n' options: [skipShapeProps: no] errors: [message: "'a.b' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props.a.b.z' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.shape({' ' b: PropTypes.shape({' ' c: PropTypes.string' ' })' ' })' '}' ].join '\n' options: [skipShapeProps: no] errors: [message: "'a.b.c' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props.a.b.c' ' this.props.a.__.d.length' ' this.props.a.anything.e[2]' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.objectOf(' ' PropTypes.shape({' ' unused: PropTypes.string' ' })' ' )' '}' ].join '\n' options: [skipShapeProps: no] errors: [message: "'a.*.unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' i = 3' ' this.props.a[2].c' ' this.props.a[i].d.length' ' this.props.a[i + 2].e[2]' ' this.props.a.length' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.arrayOf(' ' PropTypes.shape({' ' unused: PropTypes.string' ' })' ' )' '}' ].join '\n' options: [skipShapeProps: no] errors: [message: "'a.*.unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props.a.length' ' this.props.a.b' ' this.props.a.e.length' ' this.props.a.e.anyProp' ' this.props.a.c.toString()' ' this.props.a.c.someThingElse()' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.oneOfType([' ' PropTypes.shape({' ' unused: PropTypes.number,' ' anotherunused: PropTypes.array' ' })' ' ])' '}' ].join '\n' options: [skipShapeProps: no] errors: [ message: "'a.unused' PropType is defined but prop is never used" , message: "'a.anotherunused' PropType is defined but prop is never used" ] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props["some.value"]' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "some.unused": PropTypes.string' '}' ].join '\n' errors: [ message: "'some.unused' PropType is defined but prop is never used" ] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props["arr"][1]["some.value"]' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "arr": PropTypes.arrayOf(' ' PropTypes.shape({' ' "some.unused": PropTypes.string' ' })' ' )' '}' ].join '\n' options: [skipShapeProps: no] errors: [ message: "'arr.*.some.unused' PropType is defined but prop is never used" ] , code: [ 'class Hello extends React.Component' ' @propTypes = {' ' unused: PropTypes.string' ' }' ' render: ->' ' text' " text = 'Hello '" ' {props: {firstname}} = this' ' return <div>{text} {firstname}</div>' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' if (true)' ' return <span>{this.props.firstname}</span>' ' else' ' return <span>{this.props.lastname}</span>' 'Hello.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = (props) ->' ' return <div>Hello {props.name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = (props) =>' ' {name} = props' ' return <div>Hello {name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = ({ name }) ->' ' return <div>Hello {name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = ({ name }) ->' ' return <div>Hello {name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = ({ name }) =>' ' return <div>Hello {name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' @propTypes = {unused: PropTypes.string}' ' render: ->' " props = {firstname: 'John'}" ' return <div>Hello {props.firstname} {this.props.lastname}</div>' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' @propTypes = {unused: PropTypes.string}' ' constructor: (props, context) ->' ' super(props, context)' ' this.state = { status: props.source }' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' @propTypes = {unused: PropTypes.string}' ' constructor: (props, context) ->' ' super(props, context)' ' this.state = { status: props.source.uri }' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'HelloComponent = ->' ' Hello = createReactClass({' ' propTypes: {unused: PropTypes.string},' ' render: ->' ' return <div>Hello {this.props.name}</div>' ' })' ' return Hello' 'module.exports = HelloComponent()' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = (props) =>' ' team = props.names.map((name) =>' ' return <li>{name}, {props.company}</li>' ' )' ' return <ul>{team}</ul>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Annotation = (props) => (' ' <div>' ' {props.text}' ' </div>' ')' 'Annotation.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'for key of foo' ' Hello = createReactClass({' ' propTypes: {unused: PropTypes.string},' ' render: ->' ' return <div>Hello {this.props.name}</div>' ' })' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'propTypes = {' ' unused: PropTypes.string' '}' 'class Test extends React.Component' ' render: ->' ' return (' ' <div>{this.props.firstname} {this.props.lastname}</div>' ' )' 'Test.propTypes = propTypes' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , { code: [ 'class Test extends Foo.Component' ' render: ->' ' return (' ' <div>{this.props.firstname} {this.props.lastname}</div>' ' )' 'Test.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' # parser: 'babel-eslint' settings errors: [message: "'unused' PropType is defined but prop is never used"] } , code: [ '###* @jsx Foo ###' 'class Test extends Foo.Component' ' render: ->' ' return (' ' <div>{this.props.firstname} {this.props.lastname}</div>' ' )' 'Test.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' unused: PropTypes.string' # ' }' # ' render : ->' # ' return <div>Hello {this.props.name}</div>' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'unused' PropType is defined but prop is never used"] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' unused: Object' # ' }' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'unused' PropType is defined but prop is never used"] # , # code: [ # 'type Props = {unused: Object}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'unused' PropType is defined but prop is never used"] # , # code: """ # type PropsA = { a: string } # type PropsB = { b: string } # type Props = PropsA & PropsB # class MyComponent extends React.Component # props: Props # render: -> # return <div>{this.props.a}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'b' PropType is defined but prop is never used"] # , # code: """ # type PropsA = { foo: string } # type PropsB = { bar: string } # type PropsC = { zap: string } # type Props = PropsA & PropsB # class Bar extends React.Component # props: Props & PropsC # render: -> # return <div>{this.props.foo} - {this.props.bar}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'zap' PropType is defined but prop is never used"] # , # code: """ # type PropsB = { foo: string } # type PropsC = { bar: string } # type Props = PropsB & { # zap: string # } # class Bar extends React.Component # props: Props & PropsC # render: -> # return <div>{this.props.foo} - {this.props.bar}</div> # } # } # """ # errors: [message: "'zap' PropType is defined but prop is never used"] # , # # parser: 'babel-eslint' # code: """ # type PropsB = { foo: string } # type PropsC = { bar: string } # type Props = { # zap: string # } & PropsB # class Bar extends React.Component # props: Props & PropsC # render: -> # return <div>{this.props.foo} - {this.props.bar}</div> # } # } # """ # errors: [message: "'zap' PropType is defined but prop is never used"] # parser: 'babel-eslint' # code: [ # 'class Hello extends React.Component' # ' props: {' # ' name: {' # ' unused: string' # ' }' # ' }' # ' render : ->' # ' return <div>Hello {this.props.name.lastname}</div>' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'name.unused' PropType is defined but prop is never used" # ] # , # , # code: [ # 'type Props = {name: {unused: string}}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.name.lastname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {person: {name: {unused: string}}}' # ' render : ->' # ' return <div>Hello {this.props.person.name.lastname}</div>' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'person.name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'type Props = {person: {name: {unused: string}}}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.person.name.lastname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'person.name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'type Person = {name: {unused: string}}' # 'class Hello extends React.Component' # ' props: {people: Person[]}' # ' render : ->' # ' names = []' # ' for (i = 0 i < this.props.people.length i++) ->' # ' names.push(this.props.people[i].name.lastname)' # ' }' # ' return <div>Hello {names.join(' # ')}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: # "'people.*.name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'type Person = {name: {unused: string}}' # 'type Props = {people: Person[]}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' names = []' # ' for (i = 0 i < this.props.people.length i++) ->' # ' names.push(this.props.people[i].name.lastname)' # ' }' # ' return <div>Hello {names.join(' # ')}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: # "'people.*.name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'type Props = {result?: {ok: string | boolean}|{ok: number | Array}}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.result.notok}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'result.ok' PropType is defined but prop is never used" # , # message: "'result.ok' PropType is defined but prop is never used" # ] # , # code: [ # 'function Greetings({names}) ->' # ' names = names.map(({firstname, lastname}) => <div>{firstname} {lastname}</div>)' # ' return <Hello>{names}</Hello>' # '}' # 'Greetings.propTypes = {unused: Object}' # ].join '\n' # errors: [message: "'unused' PropType is defined but prop is never used"] code: [ 'MyComponent = (props) => (' ' <div onClick={() => props.toggle()}></div>' ')' 'MyComponent.propTypes = {unused: Object}' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'MyComponent = (props) => if props.test then <div /> else <span />' 'MyComponent.propTypes = {unused: Object}' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , # , # code: [ # 'type Props = {' # ' unused: ?string,' # '}' # 'function Hello({firstname, lastname}: Props): React$Element' # ' return <div>Hello {firstname} {lastname}</div>' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'unused' PropType is defined but prop is never used"] code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' constructor: (props) ->' ' super(props)' ' {something} = props' ' doSomething(something)' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' constructor: ({something}) ->' ' super({something})' ' doSomething(something)' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentWillReceiveProps: (nextProps, nextState) ->' ' {something} = nextProps' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentWillReceiveProps: ({something}, nextState) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' shouldComponentUpdate: (nextProps, nextState) ->' ' {something} = nextProps' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' shouldComponentUpdate: ({something}, nextState) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentWillUpdate: (nextProps, nextState) ->' ' {something} = nextProps' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentWillUpdate: ({something}, nextState) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentDidUpdate: (prevProps, prevState) ->' ' {something} = prevProps' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentDidUpdate: ({something}, prevState) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' something: PropTypes.bool' ' }' ' componentDidUpdate: (prevProps, {state1, state2}) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'something' PropType is defined but prop is never used" line: 3 column: 16 ] , code: [ 'Hello = createReactClass({' ' propTypes: {' ' something: PropTypes.bool' ' },' ' componentDidUpdate: (prevProps, {state1, state2}) ->' ' return something' '})' ].join '\n' errors: [ message: "'something' PropType is defined but prop is never used" line: 3 column: 16 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentWillUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'bar' PropType is defined but prop is never used" line: 4 column: 10 ] , # Multiple props used inside of an async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' classProperty: =>' ' await this.props.foo()' ' await this.props.bar()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'baz' PropType is defined but prop is never used" line: 5 column: 10 ] , code: [ 'class Hello extends Component' ' componentWillUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' errors: [ message: "'bar' PropType is defined but prop is never used" line: 7 column: 8 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' shouldComponentUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'bar' PropType is defined but prop is never used" line: 4 column: 10 ] , # Multiple destructured props inside of async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' classProperty: =>' ' { bar, baz } = this.props' ' await bar()' ' await baz()' ].join '\n' # parser: 'babel-eslint' errors: [message: "'foo' PropType is defined but prop is never used"] , # Multiple props used inside of an async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' method: ->' ' await this.props.foo()' ' await this.props.baz()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'bar' PropType is defined but prop is never used" line: 4 column: 10 ] , code: [ 'class Hello extends Component' ' shouldComponentUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' errors: [ message: "'bar' PropType is defined but prop is never used" line: 7 column: 8 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentDidUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'bar' PropType is defined but prop is never used" line: 4 column: 10 ] , # Multiple destructured props inside of async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' method: ->' ' { foo, bar } = this.props' ' await foo()' ' await bar()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'baz' PropType is defined but prop is never used" line: 5 column: 10 ] , # factory functions that return async functions code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' factory: ->' ' =>' ' await this.props.foo()' ' await this.props.bar()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'baz' PropType is defined but prop is never used" line: 5 column: 10 ] , code: [ 'class Hello extends Component' ' componentDidUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' errors: [ message: "'bar' PropType is defined but prop is never used" line: 7 column: 8 ] , code: [ 'class Hello extends Component' ' componentDidUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' 'Hello.propTypes = forbidExtraProps({' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '})' ].join '\n' errors: [ message: "'bar' PropType is defined but prop is never used" line: 7 column: 8 ] settings: propWrapperFunctions: ['forbidExtraProps'] , # , # code: [ # 'class Hello extends Component' # ' propTypes = forbidExtraProps({' # ' foo: PropTypes.string,' # ' bar: PropTypes.string' # ' })' # ' componentDidUpdate: (nextProps) ->' # ' if (nextProps.foo)' # ' return true' # ].join '\n' # # parser: 'babel-eslint' # errors: [ # message: "'bar' PropType is defined but prop is never used" # line: 4 # column: 10 # ] # settings: # propWrapperFunctions: ['forbidExtraProps'] # factory functions that return async functions code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' factory: ->' ' return ->' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'foo' PropType is defined but prop is never used" line: 3 column: 10 ] , # Multiple props used inside of an async function code: [ 'class Example extends Component' ' render: ->' ' onSubmit = ->' ' await this.props.foo()' ' await this.props.bar()' ' return <Form onSubmit={onSubmit} />' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' '}' ].join '\n' errors: [ message: "'baz' PropType is defined but prop is never used" line: 10 column: 8 ] , # Multiple props used inside of an async arrow function code: [ 'class Example extends Component' ' render: ->' ' onSubmit = =>' ' await this.props.bar()' ' await this.props.baz()' ' return <Form onSubmit={onSubmit} />' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' '}' ].join '\n' errors: [ message: "'foo' PropType is defined but prop is never used" line: 8 column: 8 ] , # None of the props are used issue #1162 code: [ 'import React from "react" ' 'Hello = React.createReactClass({' ' propTypes: {' ' name: React.PropTypes.string' ' },' ' render: ->' ' return <div>Hello Bob</div>' '})' ].join '\n' errors: [message: "'name' PropType is defined but prop is never used"] , code: [ 'class Comp1 extends Component' ' render: ->' ' return <span />' 'Comp1.propTypes = {' ' prop1: PropTypes.number' '}' 'class Comp2 extends Component' ' render: ->' ' return <span />' 'Comp2.propTypes = {' ' prop2: PropTypes.arrayOf(Comp1.propTypes.prop1)' '}' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'prop1' PropType is defined but prop is never used" , message: "'prop2' PropType is defined but prop is never used" , message: "'prop2.*' PropType is defined but prop is never used" ] , code: [ 'class Comp1 extends Component' ' render: ->' ' return <span />' 'Comp1.propTypes = {' ' prop1: PropTypes.number' '}' 'class Comp2 extends Component' ' @propTypes = {' ' prop2: PropTypes.arrayOf(Comp1.propTypes.prop1)' ' }' ' render: ->' ' return <span />' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'prop1' PropType is defined but prop is never used" , message: "'prop2' PropType is defined but prop is never used" , message: "'prop2.*' PropType is defined but prop is never used" ] , code: [ 'class Comp1 extends Component' ' render: ->' ' return <span />' 'Comp1.propTypes = {' ' prop1: PropTypes.number' '}' 'Comp2 = createReactClass({' ' propTypes: {' ' prop2: PropTypes.arrayOf(Comp1.propTypes.prop1)' ' },' ' render: ->' ' return <span />' '})' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'prop1' PropType is defined but prop is never used" , message: "'prop2' PropType is defined but prop is never used" , message: "'prop2.*' PropType is defined but prop is never used" ] , # Destructured assignment with Shape propTypes with skipShapeProps off issue #816 code: [ 'export default class NavigationButton extends React.Component' ' @propTypes = {' ' route: PropTypes.shape({' ' getBarTintColor: PropTypes.func.isRequired,' ' }).isRequired,' ' }' ' renderTitle: ->' ' { route } = this.props' ' return <Title tintColor={route.getBarTintColor()}>TITLE</Title>' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] errors: [ message: "'route.getBarTintColor' PropType is defined but prop is never used" ] , code: [ # issue #1097 'class HelloGraphQL extends Component' ' render: ->' ' return <div>Hello</div>' 'HelloGraphQL.propTypes = {' ' aProp: PropTypes.string.isRequired' '}' 'HellowQueries = graphql(queryDetails, {' ' options: (ownProps) => ({' ' variables: ownProps.aProp' ' }),' '})(HelloGraphQL)' 'export default connect(mapStateToProps, mapDispatchToProps)(HellowQueries)' ].join '\n' # parser: 'babel-eslint' errors: [message: "'aProp' PropType is defined but prop is never used"] , # , # code: """ # type Props = { # firstname: string, # lastname: string, # } # class MyComponent extends React.Component<void, Props, void> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: """ # type Props = { # firstname: string, # lastname: string, # } # class MyComponent extends React.Component<void, Props, void> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # settings: react: flowVersion: '0.52' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: """ # type Props = { # firstname: string, # lastname: string, # } # class MyComponent extends React.Component<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: """ # type Person = string # class Hello extends React.Component<{ person: Person }> { # render : -> # return <div /> # } # } # """ # settings: react: flowVersion: '0.53' # errors: [message: "'person' PropType is defined but prop is never used"] # , # # parser: 'babel-eslint' # code: """ # type Person = string # class Hello extends React.Component<void, { person: Person }, void> { # render : -> # return <div /> # } # } # """ # settings: react: flowVersion: '0.52' # errors: [message: "'person' PropType is defined but prop is never used"] # , # # parser: 'babel-eslint' # code: """ # function higherOrderComponent<P: { foo: string }>: -> # return class extends React.Component<P> { # render: -> # return <div /> # } # } # } # """ # errors: [message: "'foo' PropType is defined but prop is never used"] # parser: 'babel-eslint' # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState(({ doSomething }, props) =>' ' return { doSomething: doSomething + 1 }' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' errors: [ message: "'doSomething' PropType is defined but prop is never used" ] , # issue #1685 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState) => ({' ' doSomething: prevState.doSomething + 1,' ' }))' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' errors: [ message: "'doSomething' PropType is defined but prop is never used" ] , # , # code: """ # type Props = { # firstname: string, # lastname: string, # } # class MyComponent extends React.Component<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # settings: react: flowVersion: '0.53' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] code: [ ''' class Hello extends Component @propTypes = { something: PropTypes.bool } UNSAFE_componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) ''' ].join '\n' settings: react: version: '16.2.0' # parser: 'babel-eslint' errors: [message: "'something' PropType is defined but prop is never used"] , code: [ ''' class Hello extends Component @propTypes = { something: PropTypes.bool } UNSAFE_componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something ''' ].join '\n' settings: react: version: '16.2.0' # parser: 'babel-eslint' errors: [message: "'something' PropType is defined but prop is never used"] , code: [ ''' class MyComponent extends React.Component @propTypes = { defaultValue: 'bar' } state = { currentValue: null } @getDerivedStateFromProps: (nextProps, prevState) -> if (prevState.currentValue is null) return { currentValue: nextProps.defaultValue, } return null render: -> return <div>{ this.state.currentValue }</div> ''' ].join '\n' settings: react: version: '16.2.0' # parser: 'babel-eslint' errors: [ message: "'defaultValue' PropType is defined but prop is never used" ] , code: [ ''' class MyComponent extends React.Component @propTypes = { defaultValue: PropTypes.string } getSnapshotBeforeUpdate: (prevProps, prevState) -> if (prevProps.defaultValue is null) return 'snapshot' return null render: -> return <div /> ''' ].join '\n' settings: react: version: '16.2.0' # parser: 'babel-eslint' errors: [ message: "'defaultValue' PropType is defined but prop is never used" ] , # , # # Mixed union and intersection types # code: """ # import React from 'react' # type OtherProps = { # firstname: string, # lastname: string, # } | { # fullname: string # } # type Props = OtherProps & { # age: number # } # class Test extends React.PureComponent<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'age' PropType is defined but prop is never used"] code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.shape({' ' b: PropTypes.shape({' ' })' ' })' '}' 'Hello.propTypes.a.b.c = PropTypes.number' ].join '\n' options: [skipShapeProps: no] errors: [ message: "'a' PropType is defined but prop is never used" , message: "'a.b' PropType is defined but prop is never used" , message: "'a.b.c' PropType is defined but prop is never used" ] , # , # code: """ # type Props = { foo: string } # function higherOrderComponent<Props>: -> # return class extends React.Component<Props> { # render: -> # return <div /> # } # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'foo' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {' # ' ...data,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {|' # ' ...data,' # ' lastname: string' # '|}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {' # ' ...$Exact<data>,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # "import type {Data} from './Data'" # 'type Person = {' # ' ...Data,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.bar}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # "import type {Data} from 'some-libdef-like-flow-typed-provides'" # 'type Person = {' # ' ...Data,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.bar}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {' # ' ...data,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {|' # ' ...data,' # ' lastname: string' # '|}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] code: [ 'class Hello extends React.Component' ' render : ->' ' return <div>Hello {this.props.firstname}</div>' 'Hello.propTypes = {' ' ...BasePerson,' ' lastname: PropTypes.string' '}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'lastname' PropType is defined but prop is never used"] , # , # code: [ # "import type {BasePerson} from './types'" # 'type Props = {' # ' person: {' # ' ...$Exact<BasePerson>,' # ' lastname: string' # ' }' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.person.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'person.lastname' PropType is defined but prop is never used" # ] code: [ "import BasePerson from './types'" 'class Hello extends React.Component' ' render : ->' ' return <div>Hello {this.props.person.firstname}</div>' 'Hello.propTypes = {' ' person: PropTypes.shape({' ' ...BasePerson,' ' lastname: PropTypes.string' ' })' '}' ].join '\n' options: [skipShapeProps: no] errors: [ message: "'person.lastname' PropType is defined but prop is never used" ] ### , { # Enable this when the following issue is fixed # https:#github.com/yannickcr/eslint-plugin-react/issues/296 code: [ 'function Foo(props) ->', ' { bar: { nope } } = props', ' return <div test={nope} />', '}', 'Foo.propTypes = {', ' foo: PropTypes.number,', ' bar: PropTypes.shape({', ' faz: PropTypes.number,', ' qaz: PropTypes.object,', ' }),', '}' ].join('\n'), # parser: 'babel-eslint', errors: [{ message: '\'foo\' PropType is defined but prop is never used' }] }### ]
151172
###* # @fileoverview Warn about unused PropType definitions in React components # @author <NAME> ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/no-unused-prop-types' {RuleTester} = require 'eslint' path = require 'path' settings = react: pragma: 'Foo' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-unused-prop-types', rule, valid: [ code: ''' Hello = createReactClass propTypes: name: PropTypes.string.isRequired render: -> <div>Hello {@props.name}</div> ''' , code: ''' Hello = createReactClass({ propTypes: { name: PropTypes.object.isRequired }, render: -> return <div>Hello {this.props.name.firstname}</div> }) ''' , code: ''' Hello = createReactClass({ render: -> return <div>Hello World</div> }) ''' , code: ''' Hello = createReactClass({ render: -> props = this.props return <div>Hello World</div> }) ''' , code: ''' Hello = createReactClass({ render: -> propName = "foo" return <div>Hello World {this.props[propName]}</div> }) ''' , code: ''' Hello = createReactClass({ propTypes: externalPropTypes, render: -> return <div>Hello {this.props.name}</div> }) ''' , code: ''' Hello = createReactClass({ propTypes: externalPropTypes.mySharedPropTypes, render: -> return <div>Hello {this.props.name}</div> }) ''' , code: ''' class Hello extends React.Component render: -> return <div>Hello World</div> ''' , code: ''' class Hello extends React.Component render: -> return <div>Hello {this.props.firstname} {this.props.lastname}</div> Hello.propTypes = { firstname: PropTypes.string } Hello.propTypes.lastname = PropTypes.string ''' , code: ''' Hello = createReactClass({ propTypes: { name: PropTypes.object.isRequired }, render: -> user = { name: this.props.name } return <div>Hello {user.name}</div> }) ''' , code: ''' class Hello render: -> return 'Hello' + this.props.name ''' , # , # code: ''' # class Hello extends React.Component { # static get propTypes() { # return { # name: PropTypes.string # } # } # ' render() { # ' return <div>Hello {this.props.name}</div> # ' } # '} # ''' # Props validation is ignored when spread is used code: ''' class Hello extends React.Component render: -> { firstname, ...props } = this.props { category, icon } = props return <div>Hello {firstname}</div> Hello.propTypes = { firstname: PropTypes.string, category: PropTypes.string, icon: PropTypes.bool } ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component render: -> {firstname, lastname} = this.state something = this.props return <div>Hello {firstname}</div> ''' , code: ''' class Hello extends React.Component @propTypes = { name: PropTypes.string } render: -> return <div>Hello {this.props.name}</div> ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component render: -> return <div>Hello {this.props.firstname}</div> Hello.propTypes = { 'firstname': PropTypes.string } ''' , code: ''' class Hello extends React.Component render: -> if (Object.prototype.hasOwnProperty.call(this.props, 'firstname')) return <div>Hello {this.props.firstname}</div> Hello.propTypes = { 'firstname': PropTypes.string } ''' , code: ''' class Hello extends React.Component render: -> this.props.a.b return <div>Hello</div> Hello.propTypes = {} Hello.propTypes.a = PropTypes.shape({ b: PropTypes.string }) ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> this.props.a.b.c return <div>Hello</div> Hello.propTypes = { a: PropTypes.shape({ b: PropTypes.shape({ }) }) } Hello.propTypes.a.b.c = PropTypes.number ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> this.props.a.b.c this.props.a.__.d.length this.props.a.anything.e[2] return <div>Hello</div> Hello.propTypes = { a: PropTypes.objectOf( PropTypes.shape({ c: PropTypes.number, d: PropTypes.string, e: PropTypes.array }) ) } ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> i = 3 this.props.a[2].c this.props.a[i].d.length this.props.a[i + 2].e[2] this.props.a.length return <div>Hello</div> Hello.propTypes = { a: PropTypes.arrayOf( PropTypes.shape({ c: PropTypes.number, d: PropTypes.string, e: PropTypes.array }) ) } ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> this.props.a.length return <div>Hello</div> Hello.propTypes = { a: PropTypes.oneOfType([ PropTypes.array, PropTypes.string ]) } ''' , code: ''' class Hello extends React.Component render: -> this.props.a.c this.props.a[2] is true this.props.a.e[2] this.props.a.length return <div>Hello</div> Hello.propTypes = { a: PropTypes.oneOfType([ PropTypes.shape({ c: PropTypes.number, e: PropTypes.array }).isRequired, PropTypes.arrayOf( PropTypes.bool ) ]) } ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> this.props.a.render this.props.a.c return <div>Hello</div> Hello.propTypes = { a: PropTypes.instanceOf(Hello) } ''' , code: ''' class Hello extends React.Component render: -> this.props.arr this.props.arr[3] this.props.arr.length this.props.arr.push(3) this.props.bo this.props.bo.toString() this.props.fu this.props.fu.bind(this) this.props.numb this.props.numb.toFixed() this.props.stri this.props.stri.length() return <div>Hello</div> Hello.propTypes = { arr: PropTypes.array, bo: PropTypes.bool.isRequired, fu: PropTypes.func, numb: PropTypes.number, stri: PropTypes.string } ''' , code: ''' class Hello extends React.Component render: -> { propX, "aria-controls": ariaControls, ...props } = this.props return <div>Hello</div> Hello.propTypes = { "propX": PropTypes.string, "aria-controls": PropTypes.string } ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component render: -> this.props["some.value"] return <div>Hello</div> Hello.propTypes = { "some.value": PropTypes.string } ''' , code: ''' class Hello extends React.Component render: -> this.props["arr"][1] return <div>Hello</div> Hello.propTypes = { "arr": PropTypes.array } ''' , code: ''' class Hello extends React.Component render: -> this.props["arr"][1]["some.value"] return <div>Hello</div> Hello.propTypes = { "arr": PropTypes.arrayOf( PropTypes.shape({"some.value": PropTypes.string}) ) } ''' options: [skipShapeProps: no] , code: ''' TestComp1 = createReactClass({ propTypes: { size: PropTypes.string }, render: -> foo = { baz: 'bar' } icons = foo[this.props.size].salut return <div>{icons}</div> }) ''' , code: ''' class Hello extends React.Component render: -> {firstname, lastname} = this.props.name return <div>{firstname} {lastname}</div> Hello.propTypes = { name: PropTypes.shape({ firstname: PropTypes.string, lastname: PropTypes.string }) } ''' options: [skipShapeProps: no] , # parser: 'babel-eslint' code: ''' class Hello extends React.Component render: -> {firstname} = this return <div>{firstname}</div> ''' , # parser: 'babel-eslint' code: ''' Hello = createReactClass({ propTypes: { router: PropTypes.func }, render: -> nextPath = this.props.router.getCurrentQuery().nextPath return <div>{nextPath}</div> }) ''' , code: ''' Hello = createReactClass({ propTypes: { firstname: CustomValidator.string }, render: -> return <div>{this.props.firstname}</div> }) ''' options: [customValidators: ['CustomValidator']] , code: ''' Hello = createReactClass({ propTypes: { outer: CustomValidator.shape({ inner: CustomValidator.map }) }, render: -> return <div>{this.props.outer.inner}</div> }) ''' options: [customValidators: ['CustomValidator'], skipShapeProps: no] , code: ''' Hello = createReactClass({ propTypes: { outer: PropTypes.shape({ inner: CustomValidator.string }) }, render: -> return <div>{this.props.outer.inner}</div> }) ''' options: [customValidators: ['CustomValidator'], skipShapeProps: no] , code: ''' Hello = createReactClass({ propTypes: { outer: CustomValidator.shape({ inner: PropTypes.string }) }, render: -> return <div>{this.props.outer.inner}</div> }) ''' options: [customValidators: ['CustomValidator'], skipShapeProps: no] , code: ''' Hello = createReactClass({ propTypes: { name: PropTypes.string }, render: -> return <div>{this.props.name.get("test")}</div> }) ''' options: [customValidators: ['CustomValidator']] , code: ''' SomeComponent = createReactClass({ propTypes: SomeOtherComponent.propTypes }) ''' , # parser: 'babel-eslint code: ''' Hello = createReactClass({ render: -> { a, ...b } = obj c = { ...d } return <div /> }) ''' , # , # code: [ # 'class Hello extends React.Component {' # ' static get propTypes() {}' # ' render() ->' # ' return <div>Hello World</div>' # ' }' # '}' # ].join '\n' # , # code: [ # 'class Hello extends React.Component {' # ' static get propTypes() {}' # ' render() ->' # " users = this.props.users.find(user => user.name is '<NAME>')" # ' return <div>Hello you {users.length}</div>' # ' }' # '}' # 'Hello.propTypes = {' # ' users: PropTypes.arrayOf(PropTypes.object)' # '}' # ].join '\n' code: ''' class Hello extends React.Component render: -> {} = this.props return <div>Hello</div> ''' , code: ''' class Hello extends React.Component render: -> foo = 'fullname' { [foo]: firstname } = this.props return <div>Hello {firstname}</div> ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component constructor: (props, context) -> super(props, context) this.state = { status: props.source.uri } @propTypes = { source: PropTypes.object } ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component constructor: (props, context) -> super(props, context) this.state = { status: this.props.source.uri } @propTypes = { source: PropTypes.object } ''' , # parser: 'babel-eslint' # Should not be detected as a component code: ''' HelloJohn.prototype.render = -> return React.createElement(Hello, { name: this.props.firstname }) ''' , # parser: 'babel-eslint' code: ''' HelloComponent = -> class Hello extends React.Component render: -> return <div>Hello {this.props.name}</div> Hello.propTypes = { name: PropTypes.string } return Hello module.exports = HelloComponent() ''' , # parser: 'babel-eslint' code: ''' HelloComponent = -> Hello = createReactClass({ propTypes: { name: PropTypes.string }, render: -> return <div>Hello {this.props.name}</div> }) return Hello module.exports = HelloComponent() ''' , # parser: 'babel-eslint' code: ''' class DynamicHello extends Component render: -> {firstname} = this.props class Hello extends Component render: -> {name} = this.props return <div>Hello {name}</div> Hello.propTypes = { name: PropTypes.string } return <Hello /> DynamicHello.propTypes = { firstname: PropTypes.string, } ''' , # parser: 'babel-eslint' code: ''' Hello = (props) => team = props.names.map (name) => return <li>{name}, {props.company}</li> return <ul>{team}</ul> Hello.propTypes = { names: PropTypes.array, company: PropTypes.string } ''' , # parser: 'babel-eslint' code: ''' export default { renderHello: -> {name} = this.props return <div>{name}</div> } ''' , # parser: 'babel-eslint' # Reassigned props are ignored code: ''' export class Hello extends Component render: -> props = this.props return <div>Hello {props.name.firstname} {props['name'].lastname}</div> ''' , # parser: 'babel-eslint' code: ''' export default FooBar = (props) -> bar = props.bar return (<div bar={bar}><div {...props}/></div>) if (process.env.NODE_ENV isnt 'production') FooBar.propTypes = { bar: PropTypes.string } ''' , # parser: 'babel-eslint' code: ''' Hello = createReactClass({ render: -> {...other} = this.props return ( <div {...other} /> ) }) ''' , code: ''' notAComponent = ({ something }) -> return something + 1 ''' , code: ''' notAComponent = ({ something }) -> something + 1 ''' , # Validation is ignored on reassigned props object code: ''' statelessComponent = (props) => newProps = props return <span>{newProps.someProp}</span> ''' , # parser: 'babel-eslint' # Ignore component validation if propTypes are composed using spread code: ''' class Hello extends React.Component render: -> return <div>Hello {this.props.firstName} {this.props.lastName}</div> otherPropTypes = { lastName: PropTypes.string } Hello.propTypes = { ...otherPropTypes, firstName: PropTypes.string } ''' , # Ignore destructured function arguments code: ''' class Hello extends React.Component render: -> return ["string"].map ({length}) => <div>{length}</div> ''' , code: ''' Card.propTypes = { title: PropTypes.string.isRequired, children: PropTypes.element.isRequired, footer: PropTypes.node } Card = ({ title, children, footer }) -> return ( <div/> ) ''' , code: ''' JobList = (props) -> props .jobs .forEach(() => {}) return <div></div> JobList.propTypes = { jobs: PropTypes.array } ''' , # parser: 'babel-eslint' code: ''' Greetings = -> return <div>{({name}) => <Hello name={name} />}</div> ''' , # parser: 'babel-eslint' code: ''' Greetings = -> <div>{({name}) -> return <Hello name={name} />}</div> ''' , # parser: 'babel-eslint' # Should stop at the class when searching for a parent component code: ''' export default (ComposedComponent) => class Something extends SomeOtherComponent someMethod = ({width}) => {} ''' , # parser: 'babel-eslint # Destructured shape props are skipped by default code: ''' class Hello extends Component @propTypes = { params: PropTypes.shape({ id: PropTypes.string }) } render: -> {params} = this.props id = (params || {}).id return <span>{id}</span> ''' , # parser: 'babel-eslint' # Destructured props in componentWillReceiveProps shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) ''' , # parser: 'babel-eslint' # Destructured props in componentWillReceiveProps shouldn't throw errors code: ''' class Hello extends Component componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in componentWillReceiveProps shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) }) ''' , # parser: 'babel-eslint' # Destructured props in componentWillReceiveProps shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) }) ''' , # Destructured function props in componentWillReceiveProps shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentWillReceiveProps: ({something}) -> doSomething(something) ''' , # parser: 'babel-eslint' # Destructured function props in componentWillReceiveProps shouldn't throw errors code: ''' class Hello extends Component componentWillReceiveProps: ({something}) -> doSomething(something) Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in componentWillReceiveProps shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillReceiveProps: ({something}) -> doSomething(something) }) ''' , # parser: 'babel-eslint' # Destructured function props in componentWillReceiveProps shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillReceiveProps: ({something}) -> doSomething(something) }) ''' , # Destructured props in the constructor shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } constructor: (props) -> super(props) {something} = props doSomething(something) ''' , # parser: 'babel-eslint' # Destructured props in the constructor shouldn't throw errors code: ''' class Hello extends Component constructor: (props) -> super(props) {something} = props doSomething(something) Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in the constructor shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } constructor: ({something}) -> super({something}) doSomething(something) ''' , # parser: 'babel-eslint' # Destructured function props in the constructor shouldn't throw errors code: ''' class Hello extends Component constructor: ({something}) -> super({something}) doSomething(something) Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in the `shouldComponentUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } shouldComponentUpdate: (nextProps, nextState) -> {something} = nextProps return something ''' , # parser: 'babel-eslint' # Destructured props in the `shouldComponentUpdate` method shouldn't throw errors code: ''' class Hello extends Component shouldComponentUpdate: (nextProps, nextState) -> {something} = nextProps return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in `shouldComponentUpdate` shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, shouldComponentUpdate: (nextProps, nextState) -> {something} = nextProps return something }) ''' , # parser: 'babel-eslint' # Destructured props in `shouldComponentUpdate` shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, shouldComponentUpdate: (nextProps, nextState) -> {something} = nextProps return something }) ''' , # Destructured function props in the `shouldComponentUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } shouldComponentUpdate: ({something}, nextState) -> return something ''' , # parser: 'babel-eslint' # Destructured function props in the `shouldComponentUpdate` method shouldn't throw errors code: ''' class Hello extends Component shouldComponentUpdate: ({something}, nextState) -> return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in `shouldComponentUpdate` shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, shouldComponentUpdate: ({something}, nextState) -> return something }) ''' , # parser: 'babel-eslint' # Destructured function props in `shouldComponentUpdate` shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, shouldComponentUpdate: ({something}, nextState) -> return something }) ''' , # Destructured props in the `componentWillUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something ''' , # parser: 'babel-eslint' # Destructured props in the `componentWillUpdate` method shouldn't throw errors code: ''' class Hello extends Component componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in `componentWillUpdate` shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something }) ''' , # parser: 'babel-eslint' # Destructured props in `componentWillUpdate` shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something }) ''' , # Destructured function props in the `componentWillUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentWillUpdate: ({something}, nextState) -> return something ''' , # parser: 'babel-eslint' # Destructured function props in the `componentWillUpdate` method shouldn't throw errors code: ''' class Hello extends Component componentWillUpdate: ({something}, nextState) -> return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in the `componentWillUpdate` method shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillUpdate: ({something}, nextState) -> return something }) ''' , # parser: 'babel-eslint' # Destructured function props in the `componentWillUpdate` method shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillUpdate: ({something}, nextState) -> return something }) ''' , # Destructured props in the `componentDidUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentDidUpdate: (prevProps, prevState) -> {something} = prevProps return something ''' , # parser: 'babel-eslint' # Destructured props in the `componentDidUpdate` method shouldn't throw errors code: ''' class Hello extends Component componentDidUpdate: (prevProps, prevState) -> {something} = prevProps return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in `componentDidUpdate` shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: (prevProps, prevState) -> {something} = prevProps return something }) ''' , # parser: 'babel-eslint' # Destructured props in `componentDidUpdate` shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: (prevProps, prevState) -> {something} = prevProps return something }) ''' , # Destructured function props in the `componentDidUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentDidUpdate: ({something}, prevState) -> return something ''' , # parser: 'babel-eslint' # Destructured function props in the `componentDidUpdate` method shouldn't throw errors code: ''' class Hello extends Component componentDidUpdate: ({something}, prevState) -> return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in the `componentDidUpdate` method shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: ({something}, prevState) -> return something }) ''' , # parser: 'babel-eslint' # Destructured function props in the `componentDidUpdate` method shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: ({something}, prevState) -> return something }) ''' , # Destructured state props in `componentDidUpdate` [Issue #825] code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentDidUpdate: ({something}, {state1, state2}) -> return something ''' , # parser: 'babel-eslint' # Destructured state props in `componentDidUpdate` [Issue #825] code: ''' class Hello extends Component componentDidUpdate: ({something}, {state1, state2}) -> return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured state props in `componentDidUpdate` [Issue #825] when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: ({something}, {state1, state2}) -> return something }) ''' , # parser: 'babel-eslint' # Destructured state props in `componentDidUpdate` without custom parser [Issue #825] code: ''' Hello = React.Component({ propTypes: { something: PropTypes.bool }, componentDidUpdate: ({something}, {state1, state2}) -> return something }) ''' , # Destructured state props in `componentDidUpdate` without custom parser [Issue #825] when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: ({something}, {state1, state2}) -> return something }) ''' , # Destructured props in a stateless function code: ''' Hello = (props) => {...rest} = props return <div /> ''' , # `no-unused-prop-types` in jsx expressions - [Issue #885] code: ''' PagingBlock = (props) -> return ( <span> <a onClick={() => props.previousPage()}/> <a onClick={() => props.nextPage()}/> </span> ) PagingBlock.propTypes = { nextPage: PropTypes.func.isRequired, previousPage: PropTypes.func.isRequired, } ''' , # `no-unused-prop-types` rest param props in jsx expressions - [Issue #885] code: ''' PagingBlock = (props) -> return ( <SomeChild {...props} /> ) PagingBlock.propTypes = { nextPage: PropTypes.func.isRequired, previousPage: PropTypes.func.isRequired, } ''' , code: ''' class Hello extends Component componentWillReceiveProps: (nextProps) -> if (nextProps.foo) doSomething(this.props.bar) Hello.propTypes = { foo: PropTypes.bool, bar: PropTypes.bool } ''' , # The next two test cases are related to: https://github.com/yannickcr/eslint-plugin-react/issues/1183 code: ''' export default SomeComponent = (props) -> callback = () => props.a(props.b) anotherCallback = () => {} return ( <SomeOtherComponent name={props.c} callback={callback} /> ) SomeComponent.propTypes = { a: React.PropTypes.func.isRequired, b: React.PropTypes.string.isRequired, c: React.PropTypes.string.isRequired, } ''' , code: [ 'export default SomeComponent = (props) ->' ' callback = () =>' ' props.a(props.b)' '' ' return (' ' <SomeOtherComponent' ' name={props.c}' ' callback={callback}' ' />' ' )' '' 'SomeComponent.propTypes = {' ' a: React.PropTypes.func.isRequired,' ' b: React.PropTypes.string.isRequired,' ' c: React.PropTypes.string.isRequired,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' shouldComponentUpdate: (props) ->' ' if (props.foo)' ' return true' '' ' render() ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' shouldComponentUpdate: (props) ->' ' if (props.foo)' ' return true' '' ' render() ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentWillUpdate: (props) ->' ' if (props.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' componentWillUpdate: (props) ->' ' if (props.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentWillReceiveProps: (nextProps) ->' ' {foo} = nextProps' ' if (foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' # Props used inside of an async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' }' ' classProperty: () =>' ' await @props.foo()' ].join '\n' , # parser: 'babel-eslint' # Multiple props used inside of an async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' classProperty = () =>' ' await this.props.foo()' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' componentWillReceiveProps: (props) ->' ' if (props.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' shouldComponentUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' # Destructured props inside of async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' }' ' classProperty: =>' ' { foo } = this.props' ' await foo()' ].join '\n' , # parser: 'babel-eslint' # Multiple destructured props inside of async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' classProperty: =>' ' { foo, bar, baz } = this.props' ' await foo()' ' await bar()' ' await baz()' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' shouldComponentUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentWillUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' # Props used inside of an async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' }' ' method: ->' ' await this.props.foo()' ].join '\n' , # parser: 'babel-eslint' # Multiple props used inside of an async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' method: ->' ' await this.props.foo()' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' , # parser: 'babel-eslint' # Destrucuted props inside of async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' }' ' method: ->' ' { foo } = this.props' ' await foo()' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' componentWillUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentDidUpdate: (prevProps) ->' ' if (prevProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' # Multiple destructured props inside of async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' method: ->' ' { foo, bar, baz } = this.props' ' await foo()' ' await bar()' ' await baz()' ].join '\n' , # parser: 'babel-eslint' # factory functions that return async functions code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' factory: ->' ' return () =>' ' await this.props.foo()' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' , # parser: 'babel-eslint' # factory functions that return async functions code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' factory: ->' ' return ->' ' await this.props.foo()' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' componentDidUpdate: (prevProps) ->' ' if (prevProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , # Multiple props used inside of an async method code: [ 'class Example extends Component' ' method: ->' ' await this.props.foo()' ' await this.props.bar()' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' '}' ].join '\n' , # Multiple props used inside of an async function code: [ 'class Example extends Component' ' render: ->' ' onSubmit = ->' ' await this.props.foo()' ' await this.props.bar()' ' return <Form onSubmit={onSubmit} />' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' '}' ].join '\n' , # Multiple props used inside of an async arrow function code: [ 'class Example extends Component' ' render: ->' ' onSubmit = =>' ' await this.props.foo()' ' await this.props.bar()' ' return <Form onSubmit={onSubmit} />' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' '}' ].join '\n' , # Destructured assignment with Shape propTypes issue #816 code: [ 'export default class NavigationButton extends React.Component' ' @propTypes = {' ' route: PropTypes.shape({' ' getBarTintColor: PropTypes.func.isRequired,' ' }).isRequired,' ' }' ' renderTitle: ->' ' { route } = this.props' ' return <Title tintColor={route.getBarTintColor()}>TITLE</Title>' ].join '\n' , # parser: 'babel-eslint' # Destructured assignment without Shape propTypes issue #816 code: [ 'Component = ({ children: aNode }) => (' ' <div>{aNode}</div>' ')' 'Component.defaultProps = {' ' children: null,' '}' 'Component.propTypes = {' ' children: React.PropTypes.node,' '}' ].join '\n' , # issue 1309 code: [ 'Thing = (props) => (' ' <div>' ' {(() =>' ' if(props.enabled && props.test)' ' return (' ' <span>Enabled!</span>' ' )' ' return (' ' <span>Disabled..</span>' ' )' ' )()}' ' </div>' ')' 'Thing.propTypes = {' ' enabled: React.PropTypes.bool,' ' test: React.PropTypes.bool' '}' ].join '\n' , code: [ 'Thing = (props) => (' ' <div>' ' {do =>' ' if(props.enabled && props.test)' ' return (' ' <span>Enabled!</span>' ' )' ' return (' ' <span>Disabled..</span>' ' )' ' }' ' </div>' ')' 'Thing.propTypes = {' ' enabled: React.PropTypes.bool,' ' test: React.PropTypes.bool' '}' ].join '\n' , # issue 1107 code: [ 'Test = (props) => <div>' ' {someArray.map (l) => <div' ' key={l}>' ' {props.property + props.property2}' ' </div>}' '</div>' 'Test.propTypes = {' ' property: React.propTypes.string.isRequired,' ' property2: React.propTypes.string.isRequired' '}' ].join '\n' , # issue 811 code: [ 'Button = React.createClass({' ' displayName: "Button",' ' propTypes: {' ' name: React.PropTypes.string.isRequired,' ' isEnabled: React.PropTypes.bool.isRequired' ' },' ' render: ->' ' item = this.props' ' disabled = !this.props.isEnabled' ' return (' ' <div>' ' <button type="button" disabled={disabled}>{item.name}</button>' ' </div>' ' )' '})' ].join '\n' , # issue 811 code: [ 'class Foo extends React.Component' ' @propTypes = {' ' foo: PropTypes.func.isRequired,' ' }' ' constructor: (props) ->' ' super(props)' ' { foo } = props' ' this.message = foo("blablabla")' ' render: ->' ' return <div>{this.message}</div>' ].join '\n' , # parser: 'babel-eslint' # issue #1097 code: [ 'class HelloGraphQL extends Component' ' render: ->' ' return <div>Hello</div>' 'HellowQueries = graphql(queryDetails, {' ' options: (ownProps) => ({' ' variables: ownProps.aProp' ' }),' '})(HelloGraphQL)' 'HellowQueries.propTypes = {' ' aProp: PropTypes.string.isRequired' '}' 'export default connect(mapStateToProps, mapDispatchToProps)(HellowQueries)' ].join '\n' , # parser: 'babel-eslint' # issue #1335 # code: [ # 'type Props = {' # ' foo: {' # ' bar: boolean' # ' }' # '}' # 'class DigitalServices extends React.Component' # ' props: Props' # ' render: ->' # ' { foo } = this.props' # ' return <div>{foo.bar}</div>' # ' }' # '}' # ].join '\n' # , # parser: 'babel-eslint' code: [ 'foo = {}' 'class Hello extends React.Component' ' render: ->' ' {firstname, lastname} = this.props.name' ' return <div>{firstname} {lastname}</div>' 'Hello.propTypes = {' ' name: PropTypes.shape(foo)' '}' ].join '\n' , # , # # parser: 'babel-eslint' # # issue #933 # code: [ # 'type Props = {' # ' onMouseOver: Function,' # ' onClick: Function,' # '}' # 'MyComponent = (props: Props) => (' # '<div>' # ' <button onMouseOver={() => props.onMouseOver()} />' # ' <button onClick={() => props.onClick()} />' # '</div>' # ')' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState, props) =>' ' props.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' 'tempVar2' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] , # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState, { doSomething }) =>' ' doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] , # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState, obj) =>' ' obj.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' 'tempVar2' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] , # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState(() =>' ' this.props.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' 'tempVar' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] , # issue #1542 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState) =>' ' this.props.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' options: [skipShapeProps: no] , # issue #1542 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState(({ something }) =>' ' this.props.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' options: [skipShapeProps: no] , # issue #106 code: ''' import React from 'react' import SharedPropTypes from './SharedPropTypes' export default class A extends React.Component render: -> return ( <span a={this.props.a} b={this.props.b} c={this.props.c}> {this.props.children} </span> ) A.propTypes = { a: React.PropTypes.string, ...SharedPropTypes # eslint-disable-line object-shorthand } ''' , # , # # parser: 'babel-eslint' # # issue #933 # code: """ # type Props = { # +foo: number # } # class MyComponent extends React.Component # render: -> # return <div>{this.props.foo}</div> # } # } # """ # , # # parser: 'babel-eslint' # code: """ # type Props = { # \'completed?\': boolean, # } # Hello = (props: Props): React.Element => { # return <div>{props[\'completed?\']}</div> # } # """ # , # # parser: 'babel-eslint' # code: """ # type Person = { # firstname: string # } # class MyComponent extends React.Component<void, Props, void> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # , # # parser: 'babel-eslint' # code: """ # type Person = { # firstname: string # } # class MyComponent extends React.Component<void, Props, void> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # settings: react: flowVersion: '0.52' # , # # parser: 'babel-eslint' # code: """ # type Person = { # firstname: string # } # class MyComponent extends React.Component<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # , # # parser: 'babel-eslint' # code: """ # type Person = { # firstname: string # } # class MyComponent extends React.Component<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # settings: react: flowVersion: '0.53' # parser: 'babel-eslint' # Issue #1068 code: ''' class MyComponent extends Component @propTypes = { validate: PropTypes.bool, options: PropTypes.array, value: ({options, value, validate}) => if (!validate) then return if (options.indexOf(value) < 0) throw new Errow('oops') } render: -> return <ul> {this.props.options.map((option) => <li className={this.props.value == option && "active"}>{option}</li> )} </ul> ''' , # parser: 'babel-eslint' # Issue #1068 code: ''' class MyComponent extends Component @propTypes = { validate: PropTypes.bool, options: PropTypes.array, value: ({options, value, validate}) -> if (!validate) then return if (options.indexOf(value) < 0) throw new Errow('oops') } render: -> return <ul> {this.props.options.map((option) => <li className={this.props.value == option && "active"}>{option}</li> )} </ul> ''' , # parser: 'babel-eslint' # Issue #1068 code: ''' class MyComponent extends Component @propTypes = { validate: PropTypes.bool, options: PropTypes.array, value: ({options, value, validate}) -> if (!validate) then return if (options.indexOf(value) < 0) throw new Errow('oops') } render: -> return <ul> {this.props.options.map((option) => <li className={this.props.value == option && "active"}>{option}</li> )} </ul> ''' , # parser: 'babel-eslint' code: ''' class MyComponent extends React.Component render: -> return <div>{ this.props.other }</div> MyComponent.propTypes = { other: () => {} } ''' , # Sanity test coverage for new UNSAFE_componentWillReceiveProps lifecycles code: [ ''' class Hello extends Component @propTypes = { something: PropTypes.bool } UNSAFE_componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) ''' ].join '\n' settings: react: version: '16.3.0' , # parser: 'babel-eslint' # Destructured props in the `UNSAFE_componentWillUpdate` method shouldn't throw errors code: [ ''' class Hello extends Component @propTypes = { something: PropTypes.bool } UNSAFE_componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something ''' ].join '\n' settings: react: version: '16.3.0' , # parser: 'babel-eslint' # Simple test of new @getDerivedStateFromProps lifecycle code: [ ''' class MyComponent extends React.Component @propTypes = { defaultValue: 'bar' } state = { currentValue: null } @getDerivedStateFromProps: (nextProps, prevState) -> if (prevState.currentValue is null) return { currentValue: nextProps.defaultValue, } return null render: -> return <div>{ this.state.currentValue }</div> ''' ].join '\n' settings: react: version: '16.3.0' , # parser: 'babel-eslint' # Simple test of new @getSnapshotBeforeUpdate lifecycle code: [ ''' class MyComponent extends React.Component @propTypes = { defaultValue: PropTypes.string } getSnapshotBeforeUpdate: (prevProps, prevState) -> if (prevProps.defaultValue is null) return 'snapshot' return null render: -> return <div /> ''' ].join '\n' settings: react: version: '16.3.0' , # , # # parser: 'babel-eslint' # # Impossible intersection type # code: """ # import React from 'react' # type Props = string & { # fullname: string # } # class Test extends React.PureComponent<Props> { # render: -> # return <div>Hello {this.props.fullname}</div> # } # } # """ # , # # parser: 'babel-eslint' # code: [ # "import type {BasePerson} from './types'" # 'type Props = {' # ' person: {' # ' ...$Exact<BasePerson>,' # ' lastname: string' # ' }' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.person.firstname}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' code: [ "import BasePerson from './types'" 'class Hello extends React.Component' ' render : ->' ' return <div>Hello {this.props.person.firstname}</div>' 'Hello.propTypes = {' ' person: ProTypes.shape({' ' ...BasePerson,' ' lastname: PropTypes.string' ' })' '}' ].join '\n' ] invalid: [ code: [ 'Hello = createReactClass({' ' propTypes: {' ' unused: PropTypes.string' ' },' ' render: ->' ' return React.createElement("div", {}, this.props.value)' '})' ].join '\n' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'Hello = createReactClass({' ' propTypes: {' ' name: PropTypes.string' ' },' ' render: ->' ' return <div>Hello {this.props.value}</div>' '})' ].join '\n' errors: [ message: "'name' PropType is defined but prop is never used" line: 3 column: 11 ] , code: [ 'class Hello extends React.Component' ' @propTypes = {' ' name: PropTypes.string' ' }' ' render: ->' ' return <div>Hello {this.props.value}</div>' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'name' PropType is defined but prop is never used" line: 3 column: 11 ] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello {this.props.firstname} {this.props.lastname}</div>' 'Hello.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello {this.props.name}</div>' 'Hello.propTypes = {' ' unused: PropTypes.string' '}' 'class HelloBis extends React.Component' ' render: ->' ' return <div>Hello {this.props.name}</div>' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = createReactClass({' ' propTypes: {' ' unused: PropTypes.string.isRequired,' ' anotherunused: PropTypes.string.isRequired' ' },' ' render: ->' ' return <div>Hello {this.props.name} and {this.props.propWithoutTypeDefinition}</div>' '})' 'Hello2 = createReactClass({' ' render: ->' ' return <div>Hello {this.props.name}</div>' '})' ].join '\n' errors: [ message: "'unused' PropType is defined but prop is never used" , message: "'anotherunused' PropType is defined but prop is never used" ] , code: [ 'class Hello extends React.Component' ' render: ->' ' { firstname, lastname } = this.props' ' return <div>Hello</div>' 'Hello.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props.a.z' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.shape({' ' b: PropTypes.string' ' })' '}' ].join '\n' options: [skipShapeProps: no] errors: [message: "'a.b' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props.a.b.z' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.shape({' ' b: PropTypes.shape({' ' c: PropTypes.string' ' })' ' })' '}' ].join '\n' options: [skipShapeProps: no] errors: [message: "'a.b.c' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props.a.b.c' ' this.props.a.__.d.length' ' this.props.a.anything.e[2]' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.objectOf(' ' PropTypes.shape({' ' unused: PropTypes.string' ' })' ' )' '}' ].join '\n' options: [skipShapeProps: no] errors: [message: "'a.*.unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' i = 3' ' this.props.a[2].c' ' this.props.a[i].d.length' ' this.props.a[i + 2].e[2]' ' this.props.a.length' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.arrayOf(' ' PropTypes.shape({' ' unused: PropTypes.string' ' })' ' )' '}' ].join '\n' options: [skipShapeProps: no] errors: [message: "'a.*.unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props.a.length' ' this.props.a.b' ' this.props.a.e.length' ' this.props.a.e.anyProp' ' this.props.a.c.toString()' ' this.props.a.c.someThingElse()' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.oneOfType([' ' PropTypes.shape({' ' unused: PropTypes.number,' ' anotherunused: PropTypes.array' ' })' ' ])' '}' ].join '\n' options: [skipShapeProps: no] errors: [ message: "'a.unused' PropType is defined but prop is never used" , message: "'a.anotherunused' PropType is defined but prop is never used" ] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props["some.value"]' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "some.unused": PropTypes.string' '}' ].join '\n' errors: [ message: "'some.unused' PropType is defined but prop is never used" ] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props["arr"][1]["some.value"]' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "arr": PropTypes.arrayOf(' ' PropTypes.shape({' ' "some.unused": PropTypes.string' ' })' ' )' '}' ].join '\n' options: [skipShapeProps: no] errors: [ message: "'arr.*.some.unused' PropType is defined but prop is never used" ] , code: [ 'class Hello extends React.Component' ' @propTypes = {' ' unused: PropTypes.string' ' }' ' render: ->' ' text' " text = 'Hello '" ' {props: {firstname}} = this' ' return <div>{text} {firstname}</div>' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' if (true)' ' return <span>{this.props.firstname}</span>' ' else' ' return <span>{this.props.lastname}</span>' 'Hello.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = (props) ->' ' return <div>Hello {props.name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = (props) =>' ' {name} = props' ' return <div>Hello {name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = ({ name }) ->' ' return <div>Hello {name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = ({ name }) ->' ' return <div>Hello {name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = ({ name }) =>' ' return <div>Hello {name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' @propTypes = {unused: PropTypes.string}' ' render: ->' " props = {firstname: '<NAME>'}" ' return <div>Hello {props.firstname} {this.props.lastname}</div>' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' @propTypes = {unused: PropTypes.string}' ' constructor: (props, context) ->' ' super(props, context)' ' this.state = { status: props.source }' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' @propTypes = {unused: PropTypes.string}' ' constructor: (props, context) ->' ' super(props, context)' ' this.state = { status: props.source.uri }' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'HelloComponent = ->' ' Hello = createReactClass({' ' propTypes: {unused: PropTypes.string},' ' render: ->' ' return <div>Hello {this.props.name}</div>' ' })' ' return Hello' 'module.exports = HelloComponent()' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = (props) =>' ' team = props.names.map((name) =>' ' return <li>{name}, {props.company}</li>' ' )' ' return <ul>{team}</ul>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Annotation = (props) => (' ' <div>' ' {props.text}' ' </div>' ')' 'Annotation.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'for key of foo' ' Hello = createReactClass({' ' propTypes: {unused: PropTypes.string},' ' render: ->' ' return <div>Hello {this.props.name}</div>' ' })' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'propTypes = {' ' unused: PropTypes.string' '}' 'class Test extends React.Component' ' render: ->' ' return (' ' <div>{this.props.firstname} {this.props.lastname}</div>' ' )' 'Test.propTypes = propTypes' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , { code: [ 'class Test extends Foo.Component' ' render: ->' ' return (' ' <div>{this.props.firstname} {this.props.lastname}</div>' ' )' 'Test.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' # parser: 'babel-eslint' settings errors: [message: "'unused' PropType is defined but prop is never used"] } , code: [ '###* @jsx Foo ###' 'class Test extends Foo.Component' ' render: ->' ' return (' ' <div>{this.props.firstname} {this.props.lastname}</div>' ' )' 'Test.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' unused: PropTypes.string' # ' }' # ' render : ->' # ' return <div>Hello {this.props.name}</div>' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'unused' PropType is defined but prop is never used"] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' unused: Object' # ' }' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'unused' PropType is defined but prop is never used"] # , # code: [ # 'type Props = {unused: Object}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'unused' PropType is defined but prop is never used"] # , # code: """ # type PropsA = { a: string } # type PropsB = { b: string } # type Props = PropsA & PropsB # class MyComponent extends React.Component # props: Props # render: -> # return <div>{this.props.a}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'b' PropType is defined but prop is never used"] # , # code: """ # type PropsA = { foo: string } # type PropsB = { bar: string } # type PropsC = { zap: string } # type Props = PropsA & PropsB # class Bar extends React.Component # props: Props & PropsC # render: -> # return <div>{this.props.foo} - {this.props.bar}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'zap' PropType is defined but prop is never used"] # , # code: """ # type PropsB = { foo: string } # type PropsC = { bar: string } # type Props = PropsB & { # zap: string # } # class Bar extends React.Component # props: Props & PropsC # render: -> # return <div>{this.props.foo} - {this.props.bar}</div> # } # } # """ # errors: [message: "'zap' PropType is defined but prop is never used"] # , # # parser: 'babel-eslint' # code: """ # type PropsB = { foo: string } # type PropsC = { bar: string } # type Props = { # zap: string # } & PropsB # class Bar extends React.Component # props: Props & PropsC # render: -> # return <div>{this.props.foo} - {this.props.bar}</div> # } # } # """ # errors: [message: "'zap' PropType is defined but prop is never used"] # parser: 'babel-eslint' # code: [ # 'class Hello extends React.Component' # ' props: {' # ' name: {' # ' unused: string' # ' }' # ' }' # ' render : ->' # ' return <div>Hello {this.props.name.lastname}</div>' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'name.unused' PropType is defined but prop is never used" # ] # , # , # code: [ # 'type Props = {name: {unused: string}}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.name.lastname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {person: {name: {unused: string}}}' # ' render : ->' # ' return <div>Hello {this.props.person.name.lastname}</div>' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'person.name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'type Props = {person: {name: {unused: string}}}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.person.name.lastname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'person.name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'type Person = {name: {unused: string}}' # 'class Hello extends React.Component' # ' props: {people: Person[]}' # ' render : ->' # ' names = []' # ' for (i = 0 i < this.props.people.length i++) ->' # ' names.push(this.props.people[i].name.lastname)' # ' }' # ' return <div>Hello {names.join(' # ')}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: # "'people.*.name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'type Person = {name: {unused: string}}' # 'type Props = {people: Person[]}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' names = []' # ' for (i = 0 i < this.props.people.length i++) ->' # ' names.push(this.props.people[i].name.lastname)' # ' }' # ' return <div>Hello {names.join(' # ')}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: # "'people.*.name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'type Props = {result?: {ok: string | boolean}|{ok: number | Array}}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.result.notok}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'result.ok' PropType is defined but prop is never used" # , # message: "'result.ok' PropType is defined but prop is never used" # ] # , # code: [ # 'function Greetings({names}) ->' # ' names = names.map(({firstname, lastname}) => <div>{firstname} {lastname}</div>)' # ' return <Hello>{names}</Hello>' # '}' # 'Greetings.propTypes = {unused: Object}' # ].join '\n' # errors: [message: "'unused' PropType is defined but prop is never used"] code: [ 'MyComponent = (props) => (' ' <div onClick={() => props.toggle()}></div>' ')' 'MyComponent.propTypes = {unused: Object}' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'MyComponent = (props) => if props.test then <div /> else <span />' 'MyComponent.propTypes = {unused: Object}' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , # , # code: [ # 'type Props = {' # ' unused: ?string,' # '}' # 'function Hello({firstname, lastname}: Props): React$Element' # ' return <div>Hello {firstname} {lastname}</div>' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'unused' PropType is defined but prop is never used"] code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' constructor: (props) ->' ' super(props)' ' {something} = props' ' doSomething(something)' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' constructor: ({something}) ->' ' super({something})' ' doSomething(something)' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentWillReceiveProps: (nextProps, nextState) ->' ' {something} = nextProps' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentWillReceiveProps: ({something}, nextState) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' shouldComponentUpdate: (nextProps, nextState) ->' ' {something} = nextProps' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' shouldComponentUpdate: ({something}, nextState) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentWillUpdate: (nextProps, nextState) ->' ' {something} = nextProps' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentWillUpdate: ({something}, nextState) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentDidUpdate: (prevProps, prevState) ->' ' {something} = prevProps' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentDidUpdate: ({something}, prevState) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' something: PropTypes.bool' ' }' ' componentDidUpdate: (prevProps, {state1, state2}) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'something' PropType is defined but prop is never used" line: 3 column: 16 ] , code: [ 'Hello = createReactClass({' ' propTypes: {' ' something: PropTypes.bool' ' },' ' componentDidUpdate: (prevProps, {state1, state2}) ->' ' return something' '})' ].join '\n' errors: [ message: "'something' PropType is defined but prop is never used" line: 3 column: 16 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentWillUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'bar' PropType is defined but prop is never used" line: 4 column: 10 ] , # Multiple props used inside of an async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' classProperty: =>' ' await this.props.foo()' ' await this.props.bar()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'baz' PropType is defined but prop is never used" line: 5 column: 10 ] , code: [ 'class Hello extends Component' ' componentWillUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' errors: [ message: "'bar' PropType is defined but prop is never used" line: 7 column: 8 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' shouldComponentUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'bar' PropType is defined but prop is never used" line: 4 column: 10 ] , # Multiple destructured props inside of async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' classProperty: =>' ' { bar, baz } = this.props' ' await bar()' ' await baz()' ].join '\n' # parser: 'babel-eslint' errors: [message: "'foo' PropType is defined but prop is never used"] , # Multiple props used inside of an async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' method: ->' ' await this.props.foo()' ' await this.props.baz()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'bar' PropType is defined but prop is never used" line: 4 column: 10 ] , code: [ 'class Hello extends Component' ' shouldComponentUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' errors: [ message: "'bar' PropType is defined but prop is never used" line: 7 column: 8 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentDidUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'bar' PropType is defined but prop is never used" line: 4 column: 10 ] , # Multiple destructured props inside of async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' method: ->' ' { foo, bar } = this.props' ' await foo()' ' await bar()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'baz' PropType is defined but prop is never used" line: 5 column: 10 ] , # factory functions that return async functions code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' factory: ->' ' =>' ' await this.props.foo()' ' await this.props.bar()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'baz' PropType is defined but prop is never used" line: 5 column: 10 ] , code: [ 'class Hello extends Component' ' componentDidUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' errors: [ message: "'bar' PropType is defined but prop is never used" line: 7 column: 8 ] , code: [ 'class Hello extends Component' ' componentDidUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' 'Hello.propTypes = forbidExtraProps({' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '})' ].join '\n' errors: [ message: "'bar' PropType is defined but prop is never used" line: 7 column: 8 ] settings: propWrapperFunctions: ['forbidExtraProps'] , # , # code: [ # 'class Hello extends Component' # ' propTypes = forbidExtraProps({' # ' foo: PropTypes.string,' # ' bar: PropTypes.string' # ' })' # ' componentDidUpdate: (nextProps) ->' # ' if (nextProps.foo)' # ' return true' # ].join '\n' # # parser: 'babel-eslint' # errors: [ # message: "'bar' PropType is defined but prop is never used" # line: 4 # column: 10 # ] # settings: # propWrapperFunctions: ['forbidExtraProps'] # factory functions that return async functions code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' factory: ->' ' return ->' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'foo' PropType is defined but prop is never used" line: 3 column: 10 ] , # Multiple props used inside of an async function code: [ 'class Example extends Component' ' render: ->' ' onSubmit = ->' ' await this.props.foo()' ' await this.props.bar()' ' return <Form onSubmit={onSubmit} />' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' '}' ].join '\n' errors: [ message: "'baz' PropType is defined but prop is never used" line: 10 column: 8 ] , # Multiple props used inside of an async arrow function code: [ 'class Example extends Component' ' render: ->' ' onSubmit = =>' ' await this.props.bar()' ' await this.props.baz()' ' return <Form onSubmit={onSubmit} />' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' '}' ].join '\n' errors: [ message: "'foo' PropType is defined but prop is never used" line: 8 column: 8 ] , # None of the props are used issue #1162 code: [ 'import React from "react" ' 'Hello = React.createReactClass({' ' propTypes: {' ' name: React.PropTypes.string' ' },' ' render: ->' ' return <div>Hello <NAME></div>' '})' ].join '\n' errors: [message: "'name' PropType is defined but prop is never used"] , code: [ 'class Comp1 extends Component' ' render: ->' ' return <span />' 'Comp1.propTypes = {' ' prop1: PropTypes.number' '}' 'class Comp2 extends Component' ' render: ->' ' return <span />' 'Comp2.propTypes = {' ' prop2: PropTypes.arrayOf(Comp1.propTypes.prop1)' '}' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'prop1' PropType is defined but prop is never used" , message: "'prop2' PropType is defined but prop is never used" , message: "'prop2.*' PropType is defined but prop is never used" ] , code: [ 'class Comp1 extends Component' ' render: ->' ' return <span />' 'Comp1.propTypes = {' ' prop1: PropTypes.number' '}' 'class Comp2 extends Component' ' @propTypes = {' ' prop2: PropTypes.arrayOf(Comp1.propTypes.prop1)' ' }' ' render: ->' ' return <span />' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'prop1' PropType is defined but prop is never used" , message: "'prop2' PropType is defined but prop is never used" , message: "'prop2.*' PropType is defined but prop is never used" ] , code: [ 'class Comp1 extends Component' ' render: ->' ' return <span />' 'Comp1.propTypes = {' ' prop1: PropTypes.number' '}' 'Comp2 = createReactClass({' ' propTypes: {' ' prop2: PropTypes.arrayOf(Comp1.propTypes.prop1)' ' },' ' render: ->' ' return <span />' '})' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'prop1' PropType is defined but prop is never used" , message: "'prop2' PropType is defined but prop is never used" , message: "'prop2.*' PropType is defined but prop is never used" ] , # Destructured assignment with Shape propTypes with skipShapeProps off issue #816 code: [ 'export default class NavigationButton extends React.Component' ' @propTypes = {' ' route: PropTypes.shape({' ' getBarTintColor: PropTypes.func.isRequired,' ' }).isRequired,' ' }' ' renderTitle: ->' ' { route } = this.props' ' return <Title tintColor={route.getBarTintColor()}>TITLE</Title>' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] errors: [ message: "'route.getBarTintColor' PropType is defined but prop is never used" ] , code: [ # issue #1097 'class HelloGraphQL extends Component' ' render: ->' ' return <div>Hello</div>' 'HelloGraphQL.propTypes = {' ' aProp: PropTypes.string.isRequired' '}' 'HellowQueries = graphql(queryDetails, {' ' options: (ownProps) => ({' ' variables: ownProps.aProp' ' }),' '})(HelloGraphQL)' 'export default connect(mapStateToProps, mapDispatchToProps)(HellowQueries)' ].join '\n' # parser: 'babel-eslint' errors: [message: "'aProp' PropType is defined but prop is never used"] , # , # code: """ # type Props = { # firstname: string, # lastname: string, # } # class MyComponent extends React.Component<void, Props, void> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: """ # type Props = { # firstname: string, # lastname: string, # } # class MyComponent extends React.Component<void, Props, void> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # settings: react: flowVersion: '0.52' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: """ # type Props = { # firstname: string, # lastname: string, # } # class MyComponent extends React.Component<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: """ # type Person = string # class Hello extends React.Component<{ person: Person }> { # render : -> # return <div /> # } # } # """ # settings: react: flowVersion: '0.53' # errors: [message: "'person' PropType is defined but prop is never used"] # , # # parser: 'babel-eslint' # code: """ # type Person = string # class Hello extends React.Component<void, { person: Person }, void> { # render : -> # return <div /> # } # } # """ # settings: react: flowVersion: '0.52' # errors: [message: "'person' PropType is defined but prop is never used"] # , # # parser: 'babel-eslint' # code: """ # function higherOrderComponent<P: { foo: string }>: -> # return class extends React.Component<P> { # render: -> # return <div /> # } # } # } # """ # errors: [message: "'foo' PropType is defined but prop is never used"] # parser: 'babel-eslint' # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState(({ doSomething }, props) =>' ' return { doSomething: doSomething + 1 }' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' errors: [ message: "'doSomething' PropType is defined but prop is never used" ] , # issue #1685 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState) => ({' ' doSomething: prevState.doSomething + 1,' ' }))' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' errors: [ message: "'doSomething' PropType is defined but prop is never used" ] , # , # code: """ # type Props = { # firstname: string, # lastname: string, # } # class MyComponent extends React.Component<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # settings: react: flowVersion: '0.53' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] code: [ ''' class Hello extends Component @propTypes = { something: PropTypes.bool } UNSAFE_componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) ''' ].join '\n' settings: react: version: '16.2.0' # parser: 'babel-eslint' errors: [message: "'something' PropType is defined but prop is never used"] , code: [ ''' class Hello extends Component @propTypes = { something: PropTypes.bool } UNSAFE_componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something ''' ].join '\n' settings: react: version: '16.2.0' # parser: 'babel-eslint' errors: [message: "'something' PropType is defined but prop is never used"] , code: [ ''' class MyComponent extends React.Component @propTypes = { defaultValue: 'bar' } state = { currentValue: null } @getDerivedStateFromProps: (nextProps, prevState) -> if (prevState.currentValue is null) return { currentValue: nextProps.defaultValue, } return null render: -> return <div>{ this.state.currentValue }</div> ''' ].join '\n' settings: react: version: '16.2.0' # parser: 'babel-eslint' errors: [ message: "'defaultValue' PropType is defined but prop is never used" ] , code: [ ''' class MyComponent extends React.Component @propTypes = { defaultValue: PropTypes.string } getSnapshotBeforeUpdate: (prevProps, prevState) -> if (prevProps.defaultValue is null) return 'snapshot' return null render: -> return <div /> ''' ].join '\n' settings: react: version: '16.2.0' # parser: 'babel-eslint' errors: [ message: "'defaultValue' PropType is defined but prop is never used" ] , # , # # Mixed union and intersection types # code: """ # import React from 'react' # type OtherProps = { # firstname: string, # lastname: string, # } | { # fullname: string # } # type Props = OtherProps & { # age: number # } # class Test extends React.PureComponent<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'age' PropType is defined but prop is never used"] code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.shape({' ' b: PropTypes.shape({' ' })' ' })' '}' 'Hello.propTypes.a.b.c = PropTypes.number' ].join '\n' options: [skipShapeProps: no] errors: [ message: "'a' PropType is defined but prop is never used" , message: "'a.b' PropType is defined but prop is never used" , message: "'a.b.c' PropType is defined but prop is never used" ] , # , # code: """ # type Props = { foo: string } # function higherOrderComponent<Props>: -> # return class extends React.Component<Props> { # render: -> # return <div /> # } # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'foo' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {' # ' ...data,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {|' # ' ...data,' # ' lastname: string' # '|}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {' # ' ...$Exact<data>,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # "import type {Data} from './Data'" # 'type Person = {' # ' ...Data,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.bar}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # "import type {Data} from 'some-libdef-like-flow-typed-provides'" # 'type Person = {' # ' ...Data,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.bar}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {' # ' ...data,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {|' # ' ...data,' # ' lastname: string' # '|}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] code: [ 'class Hello extends React.Component' ' render : ->' ' return <div>Hello {this.props.firstname}</div>' 'Hello.propTypes = {' ' ...BasePerson,' ' lastname: PropTypes.string' '}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'lastname' PropType is defined but prop is never used"] , # , # code: [ # "import type {BasePerson} from './types'" # 'type Props = {' # ' person: {' # ' ...$Exact<BasePerson>,' # ' lastname: string' # ' }' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.person.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'person.lastname' PropType is defined but prop is never used" # ] code: [ "import BasePerson from './types'" 'class Hello extends React.Component' ' render : ->' ' return <div>Hello {this.props.person.firstname}</div>' 'Hello.propTypes = {' ' person: PropTypes.shape({' ' ...BasePerson,' ' lastname: PropTypes.string' ' })' '}' ].join '\n' options: [skipShapeProps: no] errors: [ message: "'person.lastname' PropType is defined but prop is never used" ] ### , { # Enable this when the following issue is fixed # https:#github.com/yannickcr/eslint-plugin-react/issues/296 code: [ 'function Foo(props) ->', ' { bar: { nope } } = props', ' return <div test={nope} />', '}', 'Foo.propTypes = {', ' foo: PropTypes.number,', ' bar: PropTypes.shape({', ' faz: PropTypes.number,', ' qaz: PropTypes.object,', ' }),', '}' ].join('\n'), # parser: 'babel-eslint', errors: [{ message: '\'foo\' PropType is defined but prop is never used' }] }### ]
true
###* # @fileoverview Warn about unused PropType definitions in React components # @author PI:NAME:<NAME>END_PI ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/no-unused-prop-types' {RuleTester} = require 'eslint' path = require 'path' settings = react: pragma: 'Foo' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-unused-prop-types', rule, valid: [ code: ''' Hello = createReactClass propTypes: name: PropTypes.string.isRequired render: -> <div>Hello {@props.name}</div> ''' , code: ''' Hello = createReactClass({ propTypes: { name: PropTypes.object.isRequired }, render: -> return <div>Hello {this.props.name.firstname}</div> }) ''' , code: ''' Hello = createReactClass({ render: -> return <div>Hello World</div> }) ''' , code: ''' Hello = createReactClass({ render: -> props = this.props return <div>Hello World</div> }) ''' , code: ''' Hello = createReactClass({ render: -> propName = "foo" return <div>Hello World {this.props[propName]}</div> }) ''' , code: ''' Hello = createReactClass({ propTypes: externalPropTypes, render: -> return <div>Hello {this.props.name}</div> }) ''' , code: ''' Hello = createReactClass({ propTypes: externalPropTypes.mySharedPropTypes, render: -> return <div>Hello {this.props.name}</div> }) ''' , code: ''' class Hello extends React.Component render: -> return <div>Hello World</div> ''' , code: ''' class Hello extends React.Component render: -> return <div>Hello {this.props.firstname} {this.props.lastname}</div> Hello.propTypes = { firstname: PropTypes.string } Hello.propTypes.lastname = PropTypes.string ''' , code: ''' Hello = createReactClass({ propTypes: { name: PropTypes.object.isRequired }, render: -> user = { name: this.props.name } return <div>Hello {user.name}</div> }) ''' , code: ''' class Hello render: -> return 'Hello' + this.props.name ''' , # , # code: ''' # class Hello extends React.Component { # static get propTypes() { # return { # name: PropTypes.string # } # } # ' render() { # ' return <div>Hello {this.props.name}</div> # ' } # '} # ''' # Props validation is ignored when spread is used code: ''' class Hello extends React.Component render: -> { firstname, ...props } = this.props { category, icon } = props return <div>Hello {firstname}</div> Hello.propTypes = { firstname: PropTypes.string, category: PropTypes.string, icon: PropTypes.bool } ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component render: -> {firstname, lastname} = this.state something = this.props return <div>Hello {firstname}</div> ''' , code: ''' class Hello extends React.Component @propTypes = { name: PropTypes.string } render: -> return <div>Hello {this.props.name}</div> ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component render: -> return <div>Hello {this.props.firstname}</div> Hello.propTypes = { 'firstname': PropTypes.string } ''' , code: ''' class Hello extends React.Component render: -> if (Object.prototype.hasOwnProperty.call(this.props, 'firstname')) return <div>Hello {this.props.firstname}</div> Hello.propTypes = { 'firstname': PropTypes.string } ''' , code: ''' class Hello extends React.Component render: -> this.props.a.b return <div>Hello</div> Hello.propTypes = {} Hello.propTypes.a = PropTypes.shape({ b: PropTypes.string }) ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> this.props.a.b.c return <div>Hello</div> Hello.propTypes = { a: PropTypes.shape({ b: PropTypes.shape({ }) }) } Hello.propTypes.a.b.c = PropTypes.number ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> this.props.a.b.c this.props.a.__.d.length this.props.a.anything.e[2] return <div>Hello</div> Hello.propTypes = { a: PropTypes.objectOf( PropTypes.shape({ c: PropTypes.number, d: PropTypes.string, e: PropTypes.array }) ) } ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> i = 3 this.props.a[2].c this.props.a[i].d.length this.props.a[i + 2].e[2] this.props.a.length return <div>Hello</div> Hello.propTypes = { a: PropTypes.arrayOf( PropTypes.shape({ c: PropTypes.number, d: PropTypes.string, e: PropTypes.array }) ) } ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> this.props.a.length return <div>Hello</div> Hello.propTypes = { a: PropTypes.oneOfType([ PropTypes.array, PropTypes.string ]) } ''' , code: ''' class Hello extends React.Component render: -> this.props.a.c this.props.a[2] is true this.props.a.e[2] this.props.a.length return <div>Hello</div> Hello.propTypes = { a: PropTypes.oneOfType([ PropTypes.shape({ c: PropTypes.number, e: PropTypes.array }).isRequired, PropTypes.arrayOf( PropTypes.bool ) ]) } ''' options: [skipShapeProps: no] , code: ''' class Hello extends React.Component render: -> this.props.a.render this.props.a.c return <div>Hello</div> Hello.propTypes = { a: PropTypes.instanceOf(Hello) } ''' , code: ''' class Hello extends React.Component render: -> this.props.arr this.props.arr[3] this.props.arr.length this.props.arr.push(3) this.props.bo this.props.bo.toString() this.props.fu this.props.fu.bind(this) this.props.numb this.props.numb.toFixed() this.props.stri this.props.stri.length() return <div>Hello</div> Hello.propTypes = { arr: PropTypes.array, bo: PropTypes.bool.isRequired, fu: PropTypes.func, numb: PropTypes.number, stri: PropTypes.string } ''' , code: ''' class Hello extends React.Component render: -> { propX, "aria-controls": ariaControls, ...props } = this.props return <div>Hello</div> Hello.propTypes = { "propX": PropTypes.string, "aria-controls": PropTypes.string } ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component render: -> this.props["some.value"] return <div>Hello</div> Hello.propTypes = { "some.value": PropTypes.string } ''' , code: ''' class Hello extends React.Component render: -> this.props["arr"][1] return <div>Hello</div> Hello.propTypes = { "arr": PropTypes.array } ''' , code: ''' class Hello extends React.Component render: -> this.props["arr"][1]["some.value"] return <div>Hello</div> Hello.propTypes = { "arr": PropTypes.arrayOf( PropTypes.shape({"some.value": PropTypes.string}) ) } ''' options: [skipShapeProps: no] , code: ''' TestComp1 = createReactClass({ propTypes: { size: PropTypes.string }, render: -> foo = { baz: 'bar' } icons = foo[this.props.size].salut return <div>{icons}</div> }) ''' , code: ''' class Hello extends React.Component render: -> {firstname, lastname} = this.props.name return <div>{firstname} {lastname}</div> Hello.propTypes = { name: PropTypes.shape({ firstname: PropTypes.string, lastname: PropTypes.string }) } ''' options: [skipShapeProps: no] , # parser: 'babel-eslint' code: ''' class Hello extends React.Component render: -> {firstname} = this return <div>{firstname}</div> ''' , # parser: 'babel-eslint' code: ''' Hello = createReactClass({ propTypes: { router: PropTypes.func }, render: -> nextPath = this.props.router.getCurrentQuery().nextPath return <div>{nextPath}</div> }) ''' , code: ''' Hello = createReactClass({ propTypes: { firstname: CustomValidator.string }, render: -> return <div>{this.props.firstname}</div> }) ''' options: [customValidators: ['CustomValidator']] , code: ''' Hello = createReactClass({ propTypes: { outer: CustomValidator.shape({ inner: CustomValidator.map }) }, render: -> return <div>{this.props.outer.inner}</div> }) ''' options: [customValidators: ['CustomValidator'], skipShapeProps: no] , code: ''' Hello = createReactClass({ propTypes: { outer: PropTypes.shape({ inner: CustomValidator.string }) }, render: -> return <div>{this.props.outer.inner}</div> }) ''' options: [customValidators: ['CustomValidator'], skipShapeProps: no] , code: ''' Hello = createReactClass({ propTypes: { outer: CustomValidator.shape({ inner: PropTypes.string }) }, render: -> return <div>{this.props.outer.inner}</div> }) ''' options: [customValidators: ['CustomValidator'], skipShapeProps: no] , code: ''' Hello = createReactClass({ propTypes: { name: PropTypes.string }, render: -> return <div>{this.props.name.get("test")}</div> }) ''' options: [customValidators: ['CustomValidator']] , code: ''' SomeComponent = createReactClass({ propTypes: SomeOtherComponent.propTypes }) ''' , # parser: 'babel-eslint code: ''' Hello = createReactClass({ render: -> { a, ...b } = obj c = { ...d } return <div /> }) ''' , # , # code: [ # 'class Hello extends React.Component {' # ' static get propTypes() {}' # ' render() ->' # ' return <div>Hello World</div>' # ' }' # '}' # ].join '\n' # , # code: [ # 'class Hello extends React.Component {' # ' static get propTypes() {}' # ' render() ->' # " users = this.props.users.find(user => user.name is 'PI:NAME:<NAME>END_PI')" # ' return <div>Hello you {users.length}</div>' # ' }' # '}' # 'Hello.propTypes = {' # ' users: PropTypes.arrayOf(PropTypes.object)' # '}' # ].join '\n' code: ''' class Hello extends React.Component render: -> {} = this.props return <div>Hello</div> ''' , code: ''' class Hello extends React.Component render: -> foo = 'fullname' { [foo]: firstname } = this.props return <div>Hello {firstname}</div> ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component constructor: (props, context) -> super(props, context) this.state = { status: props.source.uri } @propTypes = { source: PropTypes.object } ''' , # parser: 'babel-eslint' code: ''' class Hello extends React.Component constructor: (props, context) -> super(props, context) this.state = { status: this.props.source.uri } @propTypes = { source: PropTypes.object } ''' , # parser: 'babel-eslint' # Should not be detected as a component code: ''' HelloJohn.prototype.render = -> return React.createElement(Hello, { name: this.props.firstname }) ''' , # parser: 'babel-eslint' code: ''' HelloComponent = -> class Hello extends React.Component render: -> return <div>Hello {this.props.name}</div> Hello.propTypes = { name: PropTypes.string } return Hello module.exports = HelloComponent() ''' , # parser: 'babel-eslint' code: ''' HelloComponent = -> Hello = createReactClass({ propTypes: { name: PropTypes.string }, render: -> return <div>Hello {this.props.name}</div> }) return Hello module.exports = HelloComponent() ''' , # parser: 'babel-eslint' code: ''' class DynamicHello extends Component render: -> {firstname} = this.props class Hello extends Component render: -> {name} = this.props return <div>Hello {name}</div> Hello.propTypes = { name: PropTypes.string } return <Hello /> DynamicHello.propTypes = { firstname: PropTypes.string, } ''' , # parser: 'babel-eslint' code: ''' Hello = (props) => team = props.names.map (name) => return <li>{name}, {props.company}</li> return <ul>{team}</ul> Hello.propTypes = { names: PropTypes.array, company: PropTypes.string } ''' , # parser: 'babel-eslint' code: ''' export default { renderHello: -> {name} = this.props return <div>{name}</div> } ''' , # parser: 'babel-eslint' # Reassigned props are ignored code: ''' export class Hello extends Component render: -> props = this.props return <div>Hello {props.name.firstname} {props['name'].lastname}</div> ''' , # parser: 'babel-eslint' code: ''' export default FooBar = (props) -> bar = props.bar return (<div bar={bar}><div {...props}/></div>) if (process.env.NODE_ENV isnt 'production') FooBar.propTypes = { bar: PropTypes.string } ''' , # parser: 'babel-eslint' code: ''' Hello = createReactClass({ render: -> {...other} = this.props return ( <div {...other} /> ) }) ''' , code: ''' notAComponent = ({ something }) -> return something + 1 ''' , code: ''' notAComponent = ({ something }) -> something + 1 ''' , # Validation is ignored on reassigned props object code: ''' statelessComponent = (props) => newProps = props return <span>{newProps.someProp}</span> ''' , # parser: 'babel-eslint' # Ignore component validation if propTypes are composed using spread code: ''' class Hello extends React.Component render: -> return <div>Hello {this.props.firstName} {this.props.lastName}</div> otherPropTypes = { lastName: PropTypes.string } Hello.propTypes = { ...otherPropTypes, firstName: PropTypes.string } ''' , # Ignore destructured function arguments code: ''' class Hello extends React.Component render: -> return ["string"].map ({length}) => <div>{length}</div> ''' , code: ''' Card.propTypes = { title: PropTypes.string.isRequired, children: PropTypes.element.isRequired, footer: PropTypes.node } Card = ({ title, children, footer }) -> return ( <div/> ) ''' , code: ''' JobList = (props) -> props .jobs .forEach(() => {}) return <div></div> JobList.propTypes = { jobs: PropTypes.array } ''' , # parser: 'babel-eslint' code: ''' Greetings = -> return <div>{({name}) => <Hello name={name} />}</div> ''' , # parser: 'babel-eslint' code: ''' Greetings = -> <div>{({name}) -> return <Hello name={name} />}</div> ''' , # parser: 'babel-eslint' # Should stop at the class when searching for a parent component code: ''' export default (ComposedComponent) => class Something extends SomeOtherComponent someMethod = ({width}) => {} ''' , # parser: 'babel-eslint # Destructured shape props are skipped by default code: ''' class Hello extends Component @propTypes = { params: PropTypes.shape({ id: PropTypes.string }) } render: -> {params} = this.props id = (params || {}).id return <span>{id}</span> ''' , # parser: 'babel-eslint' # Destructured props in componentWillReceiveProps shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) ''' , # parser: 'babel-eslint' # Destructured props in componentWillReceiveProps shouldn't throw errors code: ''' class Hello extends Component componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in componentWillReceiveProps shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) }) ''' , # parser: 'babel-eslint' # Destructured props in componentWillReceiveProps shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) }) ''' , # Destructured function props in componentWillReceiveProps shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentWillReceiveProps: ({something}) -> doSomething(something) ''' , # parser: 'babel-eslint' # Destructured function props in componentWillReceiveProps shouldn't throw errors code: ''' class Hello extends Component componentWillReceiveProps: ({something}) -> doSomething(something) Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in componentWillReceiveProps shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillReceiveProps: ({something}) -> doSomething(something) }) ''' , # parser: 'babel-eslint' # Destructured function props in componentWillReceiveProps shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillReceiveProps: ({something}) -> doSomething(something) }) ''' , # Destructured props in the constructor shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } constructor: (props) -> super(props) {something} = props doSomething(something) ''' , # parser: 'babel-eslint' # Destructured props in the constructor shouldn't throw errors code: ''' class Hello extends Component constructor: (props) -> super(props) {something} = props doSomething(something) Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in the constructor shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } constructor: ({something}) -> super({something}) doSomething(something) ''' , # parser: 'babel-eslint' # Destructured function props in the constructor shouldn't throw errors code: ''' class Hello extends Component constructor: ({something}) -> super({something}) doSomething(something) Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in the `shouldComponentUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } shouldComponentUpdate: (nextProps, nextState) -> {something} = nextProps return something ''' , # parser: 'babel-eslint' # Destructured props in the `shouldComponentUpdate` method shouldn't throw errors code: ''' class Hello extends Component shouldComponentUpdate: (nextProps, nextState) -> {something} = nextProps return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in `shouldComponentUpdate` shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, shouldComponentUpdate: (nextProps, nextState) -> {something} = nextProps return something }) ''' , # parser: 'babel-eslint' # Destructured props in `shouldComponentUpdate` shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, shouldComponentUpdate: (nextProps, nextState) -> {something} = nextProps return something }) ''' , # Destructured function props in the `shouldComponentUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } shouldComponentUpdate: ({something}, nextState) -> return something ''' , # parser: 'babel-eslint' # Destructured function props in the `shouldComponentUpdate` method shouldn't throw errors code: ''' class Hello extends Component shouldComponentUpdate: ({something}, nextState) -> return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in `shouldComponentUpdate` shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, shouldComponentUpdate: ({something}, nextState) -> return something }) ''' , # parser: 'babel-eslint' # Destructured function props in `shouldComponentUpdate` shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, shouldComponentUpdate: ({something}, nextState) -> return something }) ''' , # Destructured props in the `componentWillUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something ''' , # parser: 'babel-eslint' # Destructured props in the `componentWillUpdate` method shouldn't throw errors code: ''' class Hello extends Component componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in `componentWillUpdate` shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something }) ''' , # parser: 'babel-eslint' # Destructured props in `componentWillUpdate` shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something }) ''' , # Destructured function props in the `componentWillUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentWillUpdate: ({something}, nextState) -> return something ''' , # parser: 'babel-eslint' # Destructured function props in the `componentWillUpdate` method shouldn't throw errors code: ''' class Hello extends Component componentWillUpdate: ({something}, nextState) -> return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in the `componentWillUpdate` method shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillUpdate: ({something}, nextState) -> return something }) ''' , # parser: 'babel-eslint' # Destructured function props in the `componentWillUpdate` method shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentWillUpdate: ({something}, nextState) -> return something }) ''' , # Destructured props in the `componentDidUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentDidUpdate: (prevProps, prevState) -> {something} = prevProps return something ''' , # parser: 'babel-eslint' # Destructured props in the `componentDidUpdate` method shouldn't throw errors code: ''' class Hello extends Component componentDidUpdate: (prevProps, prevState) -> {something} = prevProps return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured props in `componentDidUpdate` shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: (prevProps, prevState) -> {something} = prevProps return something }) ''' , # parser: 'babel-eslint' # Destructured props in `componentDidUpdate` shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: (prevProps, prevState) -> {something} = prevProps return something }) ''' , # Destructured function props in the `componentDidUpdate` method shouldn't throw errors code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentDidUpdate: ({something}, prevState) -> return something ''' , # parser: 'babel-eslint' # Destructured function props in the `componentDidUpdate` method shouldn't throw errors code: ''' class Hello extends Component componentDidUpdate: ({something}, prevState) -> return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured function props in the `componentDidUpdate` method shouldn't throw errors when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: ({something}, prevState) -> return something }) ''' , # parser: 'babel-eslint' # Destructured function props in the `componentDidUpdate` method shouldn't throw errors when used createReactClass, with default parser code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: ({something}, prevState) -> return something }) ''' , # Destructured state props in `componentDidUpdate` [Issue #825] code: ''' class Hello extends Component @propTypes = { something: PropTypes.bool } componentDidUpdate: ({something}, {state1, state2}) -> return something ''' , # parser: 'babel-eslint' # Destructured state props in `componentDidUpdate` [Issue #825] code: ''' class Hello extends Component componentDidUpdate: ({something}, {state1, state2}) -> return something Hello.propTypes = { something: PropTypes.bool, } ''' , # Destructured state props in `componentDidUpdate` [Issue #825] when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: ({something}, {state1, state2}) -> return something }) ''' , # parser: 'babel-eslint' # Destructured state props in `componentDidUpdate` without custom parser [Issue #825] code: ''' Hello = React.Component({ propTypes: { something: PropTypes.bool }, componentDidUpdate: ({something}, {state1, state2}) -> return something }) ''' , # Destructured state props in `componentDidUpdate` without custom parser [Issue #825] when used createReactClass code: ''' Hello = createReactClass({ propTypes: { something: PropTypes.bool, }, componentDidUpdate: ({something}, {state1, state2}) -> return something }) ''' , # Destructured props in a stateless function code: ''' Hello = (props) => {...rest} = props return <div /> ''' , # `no-unused-prop-types` in jsx expressions - [Issue #885] code: ''' PagingBlock = (props) -> return ( <span> <a onClick={() => props.previousPage()}/> <a onClick={() => props.nextPage()}/> </span> ) PagingBlock.propTypes = { nextPage: PropTypes.func.isRequired, previousPage: PropTypes.func.isRequired, } ''' , # `no-unused-prop-types` rest param props in jsx expressions - [Issue #885] code: ''' PagingBlock = (props) -> return ( <SomeChild {...props} /> ) PagingBlock.propTypes = { nextPage: PropTypes.func.isRequired, previousPage: PropTypes.func.isRequired, } ''' , code: ''' class Hello extends Component componentWillReceiveProps: (nextProps) -> if (nextProps.foo) doSomething(this.props.bar) Hello.propTypes = { foo: PropTypes.bool, bar: PropTypes.bool } ''' , # The next two test cases are related to: https://github.com/yannickcr/eslint-plugin-react/issues/1183 code: ''' export default SomeComponent = (props) -> callback = () => props.a(props.b) anotherCallback = () => {} return ( <SomeOtherComponent name={props.c} callback={callback} /> ) SomeComponent.propTypes = { a: React.PropTypes.func.isRequired, b: React.PropTypes.string.isRequired, c: React.PropTypes.string.isRequired, } ''' , code: [ 'export default SomeComponent = (props) ->' ' callback = () =>' ' props.a(props.b)' '' ' return (' ' <SomeOtherComponent' ' name={props.c}' ' callback={callback}' ' />' ' )' '' 'SomeComponent.propTypes = {' ' a: React.PropTypes.func.isRequired,' ' b: React.PropTypes.string.isRequired,' ' c: React.PropTypes.string.isRequired,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' shouldComponentUpdate: (props) ->' ' if (props.foo)' ' return true' '' ' render() ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' shouldComponentUpdate: (props) ->' ' if (props.foo)' ' return true' '' ' render() ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentWillUpdate: (props) ->' ' if (props.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' componentWillUpdate: (props) ->' ' if (props.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentWillReceiveProps: (nextProps) ->' ' {foo} = nextProps' ' if (foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' # Props used inside of an async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' }' ' classProperty: () =>' ' await @props.foo()' ].join '\n' , # parser: 'babel-eslint' # Multiple props used inside of an async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' classProperty = () =>' ' await this.props.foo()' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' componentWillReceiveProps: (props) ->' ' if (props.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' shouldComponentUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' # Destructured props inside of async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' }' ' classProperty: =>' ' { foo } = this.props' ' await foo()' ].join '\n' , # parser: 'babel-eslint' # Multiple destructured props inside of async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' classProperty: =>' ' { foo, bar, baz } = this.props' ' await foo()' ' await bar()' ' await baz()' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' shouldComponentUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentWillUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' # Props used inside of an async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' }' ' method: ->' ' await this.props.foo()' ].join '\n' , # parser: 'babel-eslint' # Multiple props used inside of an async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' method: ->' ' await this.props.foo()' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' , # parser: 'babel-eslint' # Destrucuted props inside of async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' }' ' method: ->' ' { foo } = this.props' ' await foo()' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' componentWillUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentDidUpdate: (prevProps) ->' ' if (prevProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' ].join '\n' , # parser: 'babel-eslint' # Multiple destructured props inside of async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' method: ->' ' { foo, bar, baz } = this.props' ' await foo()' ' await bar()' ' await baz()' ].join '\n' , # parser: 'babel-eslint' # factory functions that return async functions code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' factory: ->' ' return () =>' ' await this.props.foo()' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' , # parser: 'babel-eslint' # factory functions that return async functions code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' factory: ->' ' return ->' ' await this.props.foo()' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends Component' ' componentDidUpdate: (prevProps) ->' ' if (prevProps.foo)' ' return true' '' ' render: ->' ' return (<div>{this.props.bar}</div>)' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' , # Multiple props used inside of an async method code: [ 'class Example extends Component' ' method: ->' ' await this.props.foo()' ' await this.props.bar()' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' '}' ].join '\n' , # Multiple props used inside of an async function code: [ 'class Example extends Component' ' render: ->' ' onSubmit = ->' ' await this.props.foo()' ' await this.props.bar()' ' return <Form onSubmit={onSubmit} />' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' '}' ].join '\n' , # Multiple props used inside of an async arrow function code: [ 'class Example extends Component' ' render: ->' ' onSubmit = =>' ' await this.props.foo()' ' await this.props.bar()' ' return <Form onSubmit={onSubmit} />' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' '}' ].join '\n' , # Destructured assignment with Shape propTypes issue #816 code: [ 'export default class NavigationButton extends React.Component' ' @propTypes = {' ' route: PropTypes.shape({' ' getBarTintColor: PropTypes.func.isRequired,' ' }).isRequired,' ' }' ' renderTitle: ->' ' { route } = this.props' ' return <Title tintColor={route.getBarTintColor()}>TITLE</Title>' ].join '\n' , # parser: 'babel-eslint' # Destructured assignment without Shape propTypes issue #816 code: [ 'Component = ({ children: aNode }) => (' ' <div>{aNode}</div>' ')' 'Component.defaultProps = {' ' children: null,' '}' 'Component.propTypes = {' ' children: React.PropTypes.node,' '}' ].join '\n' , # issue 1309 code: [ 'Thing = (props) => (' ' <div>' ' {(() =>' ' if(props.enabled && props.test)' ' return (' ' <span>Enabled!</span>' ' )' ' return (' ' <span>Disabled..</span>' ' )' ' )()}' ' </div>' ')' 'Thing.propTypes = {' ' enabled: React.PropTypes.bool,' ' test: React.PropTypes.bool' '}' ].join '\n' , code: [ 'Thing = (props) => (' ' <div>' ' {do =>' ' if(props.enabled && props.test)' ' return (' ' <span>Enabled!</span>' ' )' ' return (' ' <span>Disabled..</span>' ' )' ' }' ' </div>' ')' 'Thing.propTypes = {' ' enabled: React.PropTypes.bool,' ' test: React.PropTypes.bool' '}' ].join '\n' , # issue 1107 code: [ 'Test = (props) => <div>' ' {someArray.map (l) => <div' ' key={l}>' ' {props.property + props.property2}' ' </div>}' '</div>' 'Test.propTypes = {' ' property: React.propTypes.string.isRequired,' ' property2: React.propTypes.string.isRequired' '}' ].join '\n' , # issue 811 code: [ 'Button = React.createClass({' ' displayName: "Button",' ' propTypes: {' ' name: React.PropTypes.string.isRequired,' ' isEnabled: React.PropTypes.bool.isRequired' ' },' ' render: ->' ' item = this.props' ' disabled = !this.props.isEnabled' ' return (' ' <div>' ' <button type="button" disabled={disabled}>{item.name}</button>' ' </div>' ' )' '})' ].join '\n' , # issue 811 code: [ 'class Foo extends React.Component' ' @propTypes = {' ' foo: PropTypes.func.isRequired,' ' }' ' constructor: (props) ->' ' super(props)' ' { foo } = props' ' this.message = foo("blablabla")' ' render: ->' ' return <div>{this.message}</div>' ].join '\n' , # parser: 'babel-eslint' # issue #1097 code: [ 'class HelloGraphQL extends Component' ' render: ->' ' return <div>Hello</div>' 'HellowQueries = graphql(queryDetails, {' ' options: (ownProps) => ({' ' variables: ownProps.aProp' ' }),' '})(HelloGraphQL)' 'HellowQueries.propTypes = {' ' aProp: PropTypes.string.isRequired' '}' 'export default connect(mapStateToProps, mapDispatchToProps)(HellowQueries)' ].join '\n' , # parser: 'babel-eslint' # issue #1335 # code: [ # 'type Props = {' # ' foo: {' # ' bar: boolean' # ' }' # '}' # 'class DigitalServices extends React.Component' # ' props: Props' # ' render: ->' # ' { foo } = this.props' # ' return <div>{foo.bar}</div>' # ' }' # '}' # ].join '\n' # , # parser: 'babel-eslint' code: [ 'foo = {}' 'class Hello extends React.Component' ' render: ->' ' {firstname, lastname} = this.props.name' ' return <div>{firstname} {lastname}</div>' 'Hello.propTypes = {' ' name: PropTypes.shape(foo)' '}' ].join '\n' , # , # # parser: 'babel-eslint' # # issue #933 # code: [ # 'type Props = {' # ' onMouseOver: Function,' # ' onClick: Function,' # '}' # 'MyComponent = (props: Props) => (' # '<div>' # ' <button onMouseOver={() => props.onMouseOver()} />' # ' <button onClick={() => props.onClick()} />' # '</div>' # ')' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState, props) =>' ' props.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' 'tempVar2' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] , # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState, { doSomething }) =>' ' doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] , # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState, obj) =>' ' obj.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' 'tempVar2' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] , # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState(() =>' ' this.props.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' 'tempVar' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] , # issue #1542 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState) =>' ' this.props.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' options: [skipShapeProps: no] , # issue #1542 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState(({ something }) =>' ' this.props.doSomething()' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' options: [skipShapeProps: no] , # issue #106 code: ''' import React from 'react' import SharedPropTypes from './SharedPropTypes' export default class A extends React.Component render: -> return ( <span a={this.props.a} b={this.props.b} c={this.props.c}> {this.props.children} </span> ) A.propTypes = { a: React.PropTypes.string, ...SharedPropTypes # eslint-disable-line object-shorthand } ''' , # , # # parser: 'babel-eslint' # # issue #933 # code: """ # type Props = { # +foo: number # } # class MyComponent extends React.Component # render: -> # return <div>{this.props.foo}</div> # } # } # """ # , # # parser: 'babel-eslint' # code: """ # type Props = { # \'completed?\': boolean, # } # Hello = (props: Props): React.Element => { # return <div>{props[\'completed?\']}</div> # } # """ # , # # parser: 'babel-eslint' # code: """ # type Person = { # firstname: string # } # class MyComponent extends React.Component<void, Props, void> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # , # # parser: 'babel-eslint' # code: """ # type Person = { # firstname: string # } # class MyComponent extends React.Component<void, Props, void> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # settings: react: flowVersion: '0.52' # , # # parser: 'babel-eslint' # code: """ # type Person = { # firstname: string # } # class MyComponent extends React.Component<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # , # # parser: 'babel-eslint' # code: """ # type Person = { # firstname: string # } # class MyComponent extends React.Component<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # settings: react: flowVersion: '0.53' # parser: 'babel-eslint' # Issue #1068 code: ''' class MyComponent extends Component @propTypes = { validate: PropTypes.bool, options: PropTypes.array, value: ({options, value, validate}) => if (!validate) then return if (options.indexOf(value) < 0) throw new Errow('oops') } render: -> return <ul> {this.props.options.map((option) => <li className={this.props.value == option && "active"}>{option}</li> )} </ul> ''' , # parser: 'babel-eslint' # Issue #1068 code: ''' class MyComponent extends Component @propTypes = { validate: PropTypes.bool, options: PropTypes.array, value: ({options, value, validate}) -> if (!validate) then return if (options.indexOf(value) < 0) throw new Errow('oops') } render: -> return <ul> {this.props.options.map((option) => <li className={this.props.value == option && "active"}>{option}</li> )} </ul> ''' , # parser: 'babel-eslint' # Issue #1068 code: ''' class MyComponent extends Component @propTypes = { validate: PropTypes.bool, options: PropTypes.array, value: ({options, value, validate}) -> if (!validate) then return if (options.indexOf(value) < 0) throw new Errow('oops') } render: -> return <ul> {this.props.options.map((option) => <li className={this.props.value == option && "active"}>{option}</li> )} </ul> ''' , # parser: 'babel-eslint' code: ''' class MyComponent extends React.Component render: -> return <div>{ this.props.other }</div> MyComponent.propTypes = { other: () => {} } ''' , # Sanity test coverage for new UNSAFE_componentWillReceiveProps lifecycles code: [ ''' class Hello extends Component @propTypes = { something: PropTypes.bool } UNSAFE_componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) ''' ].join '\n' settings: react: version: '16.3.0' , # parser: 'babel-eslint' # Destructured props in the `UNSAFE_componentWillUpdate` method shouldn't throw errors code: [ ''' class Hello extends Component @propTypes = { something: PropTypes.bool } UNSAFE_componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something ''' ].join '\n' settings: react: version: '16.3.0' , # parser: 'babel-eslint' # Simple test of new @getDerivedStateFromProps lifecycle code: [ ''' class MyComponent extends React.Component @propTypes = { defaultValue: 'bar' } state = { currentValue: null } @getDerivedStateFromProps: (nextProps, prevState) -> if (prevState.currentValue is null) return { currentValue: nextProps.defaultValue, } return null render: -> return <div>{ this.state.currentValue }</div> ''' ].join '\n' settings: react: version: '16.3.0' , # parser: 'babel-eslint' # Simple test of new @getSnapshotBeforeUpdate lifecycle code: [ ''' class MyComponent extends React.Component @propTypes = { defaultValue: PropTypes.string } getSnapshotBeforeUpdate: (prevProps, prevState) -> if (prevProps.defaultValue is null) return 'snapshot' return null render: -> return <div /> ''' ].join '\n' settings: react: version: '16.3.0' , # , # # parser: 'babel-eslint' # # Impossible intersection type # code: """ # import React from 'react' # type Props = string & { # fullname: string # } # class Test extends React.PureComponent<Props> { # render: -> # return <div>Hello {this.props.fullname}</div> # } # } # """ # , # # parser: 'babel-eslint' # code: [ # "import type {BasePerson} from './types'" # 'type Props = {' # ' person: {' # ' ...$Exact<BasePerson>,' # ' lastname: string' # ' }' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.person.firstname}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' code: [ "import BasePerson from './types'" 'class Hello extends React.Component' ' render : ->' ' return <div>Hello {this.props.person.firstname}</div>' 'Hello.propTypes = {' ' person: ProTypes.shape({' ' ...BasePerson,' ' lastname: PropTypes.string' ' })' '}' ].join '\n' ] invalid: [ code: [ 'Hello = createReactClass({' ' propTypes: {' ' unused: PropTypes.string' ' },' ' render: ->' ' return React.createElement("div", {}, this.props.value)' '})' ].join '\n' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'Hello = createReactClass({' ' propTypes: {' ' name: PropTypes.string' ' },' ' render: ->' ' return <div>Hello {this.props.value}</div>' '})' ].join '\n' errors: [ message: "'name' PropType is defined but prop is never used" line: 3 column: 11 ] , code: [ 'class Hello extends React.Component' ' @propTypes = {' ' name: PropTypes.string' ' }' ' render: ->' ' return <div>Hello {this.props.value}</div>' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'name' PropType is defined but prop is never used" line: 3 column: 11 ] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello {this.props.firstname} {this.props.lastname}</div>' 'Hello.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello {this.props.name}</div>' 'Hello.propTypes = {' ' unused: PropTypes.string' '}' 'class HelloBis extends React.Component' ' render: ->' ' return <div>Hello {this.props.name}</div>' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = createReactClass({' ' propTypes: {' ' unused: PropTypes.string.isRequired,' ' anotherunused: PropTypes.string.isRequired' ' },' ' render: ->' ' return <div>Hello {this.props.name} and {this.props.propWithoutTypeDefinition}</div>' '})' 'Hello2 = createReactClass({' ' render: ->' ' return <div>Hello {this.props.name}</div>' '})' ].join '\n' errors: [ message: "'unused' PropType is defined but prop is never used" , message: "'anotherunused' PropType is defined but prop is never used" ] , code: [ 'class Hello extends React.Component' ' render: ->' ' { firstname, lastname } = this.props' ' return <div>Hello</div>' 'Hello.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props.a.z' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.shape({' ' b: PropTypes.string' ' })' '}' ].join '\n' options: [skipShapeProps: no] errors: [message: "'a.b' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props.a.b.z' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.shape({' ' b: PropTypes.shape({' ' c: PropTypes.string' ' })' ' })' '}' ].join '\n' options: [skipShapeProps: no] errors: [message: "'a.b.c' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props.a.b.c' ' this.props.a.__.d.length' ' this.props.a.anything.e[2]' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.objectOf(' ' PropTypes.shape({' ' unused: PropTypes.string' ' })' ' )' '}' ].join '\n' options: [skipShapeProps: no] errors: [message: "'a.*.unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' i = 3' ' this.props.a[2].c' ' this.props.a[i].d.length' ' this.props.a[i + 2].e[2]' ' this.props.a.length' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.arrayOf(' ' PropTypes.shape({' ' unused: PropTypes.string' ' })' ' )' '}' ].join '\n' options: [skipShapeProps: no] errors: [message: "'a.*.unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props.a.length' ' this.props.a.b' ' this.props.a.e.length' ' this.props.a.e.anyProp' ' this.props.a.c.toString()' ' this.props.a.c.someThingElse()' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.oneOfType([' ' PropTypes.shape({' ' unused: PropTypes.number,' ' anotherunused: PropTypes.array' ' })' ' ])' '}' ].join '\n' options: [skipShapeProps: no] errors: [ message: "'a.unused' PropType is defined but prop is never used" , message: "'a.anotherunused' PropType is defined but prop is never used" ] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props["some.value"]' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "some.unused": PropTypes.string' '}' ].join '\n' errors: [ message: "'some.unused' PropType is defined but prop is never used" ] , code: [ 'class Hello extends React.Component' ' render: ->' ' this.props["arr"][1]["some.value"]' ' return <div>Hello</div>' 'Hello.propTypes = {' ' "arr": PropTypes.arrayOf(' ' PropTypes.shape({' ' "some.unused": PropTypes.string' ' })' ' )' '}' ].join '\n' options: [skipShapeProps: no] errors: [ message: "'arr.*.some.unused' PropType is defined but prop is never used" ] , code: [ 'class Hello extends React.Component' ' @propTypes = {' ' unused: PropTypes.string' ' }' ' render: ->' ' text' " text = 'Hello '" ' {props: {firstname}} = this' ' return <div>{text} {firstname}</div>' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' render: ->' ' if (true)' ' return <span>{this.props.firstname}</span>' ' else' ' return <span>{this.props.lastname}</span>' 'Hello.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = (props) ->' ' return <div>Hello {props.name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = (props) =>' ' {name} = props' ' return <div>Hello {name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = ({ name }) ->' ' return <div>Hello {name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = ({ name }) ->' ' return <div>Hello {name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = ({ name }) =>' ' return <div>Hello {name}</div>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' @propTypes = {unused: PropTypes.string}' ' render: ->' " props = {firstname: 'PI:NAME:<NAME>END_PI'}" ' return <div>Hello {props.firstname} {this.props.lastname}</div>' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' @propTypes = {unused: PropTypes.string}' ' constructor: (props, context) ->' ' super(props, context)' ' this.state = { status: props.source }' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'class Hello extends React.Component' ' @propTypes = {unused: PropTypes.string}' ' constructor: (props, context) ->' ' super(props, context)' ' this.state = { status: props.source.uri }' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'HelloComponent = ->' ' Hello = createReactClass({' ' propTypes: {unused: PropTypes.string},' ' render: ->' ' return <div>Hello {this.props.name}</div>' ' })' ' return Hello' 'module.exports = HelloComponent()' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Hello = (props) =>' ' team = props.names.map((name) =>' ' return <li>{name}, {props.company}</li>' ' )' ' return <ul>{team}</ul>' 'Hello.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'Annotation = (props) => (' ' <div>' ' {props.text}' ' </div>' ')' 'Annotation.prototype.propTypes = {unused: PropTypes.string}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'for key of foo' ' Hello = createReactClass({' ' propTypes: {unused: PropTypes.string},' ' render: ->' ' return <div>Hello {this.props.name}</div>' ' })' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'propTypes = {' ' unused: PropTypes.string' '}' 'class Test extends React.Component' ' render: ->' ' return (' ' <div>{this.props.firstname} {this.props.lastname}</div>' ' )' 'Test.propTypes = propTypes' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , { code: [ 'class Test extends Foo.Component' ' render: ->' ' return (' ' <div>{this.props.firstname} {this.props.lastname}</div>' ' )' 'Test.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' # parser: 'babel-eslint' settings errors: [message: "'unused' PropType is defined but prop is never used"] } , code: [ '###* @jsx Foo ###' 'class Test extends Foo.Component' ' render: ->' ' return (' ' <div>{this.props.firstname} {this.props.lastname}</div>' ' )' 'Test.propTypes = {' ' unused: PropTypes.string' '}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'unused' PropType is defined but prop is never used"] , # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' unused: PropTypes.string' # ' }' # ' render : ->' # ' return <div>Hello {this.props.name}</div>' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'unused' PropType is defined but prop is never used"] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' unused: Object' # ' }' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'unused' PropType is defined but prop is never used"] # , # code: [ # 'type Props = {unused: Object}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'unused' PropType is defined but prop is never used"] # , # code: """ # type PropsA = { a: string } # type PropsB = { b: string } # type Props = PropsA & PropsB # class MyComponent extends React.Component # props: Props # render: -> # return <div>{this.props.a}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'b' PropType is defined but prop is never used"] # , # code: """ # type PropsA = { foo: string } # type PropsB = { bar: string } # type PropsC = { zap: string } # type Props = PropsA & PropsB # class Bar extends React.Component # props: Props & PropsC # render: -> # return <div>{this.props.foo} - {this.props.bar}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'zap' PropType is defined but prop is never used"] # , # code: """ # type PropsB = { foo: string } # type PropsC = { bar: string } # type Props = PropsB & { # zap: string # } # class Bar extends React.Component # props: Props & PropsC # render: -> # return <div>{this.props.foo} - {this.props.bar}</div> # } # } # """ # errors: [message: "'zap' PropType is defined but prop is never used"] # , # # parser: 'babel-eslint' # code: """ # type PropsB = { foo: string } # type PropsC = { bar: string } # type Props = { # zap: string # } & PropsB # class Bar extends React.Component # props: Props & PropsC # render: -> # return <div>{this.props.foo} - {this.props.bar}</div> # } # } # """ # errors: [message: "'zap' PropType is defined but prop is never used"] # parser: 'babel-eslint' # code: [ # 'class Hello extends React.Component' # ' props: {' # ' name: {' # ' unused: string' # ' }' # ' }' # ' render : ->' # ' return <div>Hello {this.props.name.lastname}</div>' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'name.unused' PropType is defined but prop is never used" # ] # , # , # code: [ # 'type Props = {name: {unused: string}}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.name.lastname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {person: {name: {unused: string}}}' # ' render : ->' # ' return <div>Hello {this.props.person.name.lastname}</div>' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'person.name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'type Props = {person: {name: {unused: string}}}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.person.name.lastname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'person.name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'type Person = {name: {unused: string}}' # 'class Hello extends React.Component' # ' props: {people: Person[]}' # ' render : ->' # ' names = []' # ' for (i = 0 i < this.props.people.length i++) ->' # ' names.push(this.props.people[i].name.lastname)' # ' }' # ' return <div>Hello {names.join(' # ')}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: # "'people.*.name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'type Person = {name: {unused: string}}' # 'type Props = {people: Person[]}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' names = []' # ' for (i = 0 i < this.props.people.length i++) ->' # ' names.push(this.props.people[i].name.lastname)' # ' }' # ' return <div>Hello {names.join(' # ')}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: # "'people.*.name.unused' PropType is defined but prop is never used" # ] # , # code: [ # 'type Props = {result?: {ok: string | boolean}|{ok: number | Array}}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.result.notok}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'result.ok' PropType is defined but prop is never used" # , # message: "'result.ok' PropType is defined but prop is never used" # ] # , # code: [ # 'function Greetings({names}) ->' # ' names = names.map(({firstname, lastname}) => <div>{firstname} {lastname}</div>)' # ' return <Hello>{names}</Hello>' # '}' # 'Greetings.propTypes = {unused: Object}' # ].join '\n' # errors: [message: "'unused' PropType is defined but prop is never used"] code: [ 'MyComponent = (props) => (' ' <div onClick={() => props.toggle()}></div>' ')' 'MyComponent.propTypes = {unused: Object}' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , code: [ 'MyComponent = (props) => if props.test then <div /> else <span />' 'MyComponent.propTypes = {unused: Object}' ].join '\n' errors: [message: "'unused' PropType is defined but prop is never used"] , # , # code: [ # 'type Props = {' # ' unused: ?string,' # '}' # 'function Hello({firstname, lastname}: Props): React$Element' # ' return <div>Hello {firstname} {lastname}</div>' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'unused' PropType is defined but prop is never used"] code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' constructor: (props) ->' ' super(props)' ' {something} = props' ' doSomething(something)' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' constructor: ({something}) ->' ' super({something})' ' doSomething(something)' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentWillReceiveProps: (nextProps, nextState) ->' ' {something} = nextProps' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentWillReceiveProps: ({something}, nextState) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' shouldComponentUpdate: (nextProps, nextState) ->' ' {something} = nextProps' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' shouldComponentUpdate: ({something}, nextState) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentWillUpdate: (nextProps, nextState) ->' ' {something} = nextProps' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentWillUpdate: ({something}, nextState) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentDidUpdate: (prevProps, prevState) ->' ' {something} = prevProps' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' unused: PropTypes.bool' ' }' ' componentDidUpdate: ({something}, prevState) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'unused' PropType is defined but prop is never used" line: 3 column: 13 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' something: PropTypes.bool' ' }' ' componentDidUpdate: (prevProps, {state1, state2}) ->' ' return something' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'something' PropType is defined but prop is never used" line: 3 column: 16 ] , code: [ 'Hello = createReactClass({' ' propTypes: {' ' something: PropTypes.bool' ' },' ' componentDidUpdate: (prevProps, {state1, state2}) ->' ' return something' '})' ].join '\n' errors: [ message: "'something' PropType is defined but prop is never used" line: 3 column: 16 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentWillUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'bar' PropType is defined but prop is never used" line: 4 column: 10 ] , # Multiple props used inside of an async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' classProperty: =>' ' await this.props.foo()' ' await this.props.bar()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'baz' PropType is defined but prop is never used" line: 5 column: 10 ] , code: [ 'class Hello extends Component' ' componentWillUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' errors: [ message: "'bar' PropType is defined but prop is never used" line: 7 column: 8 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' shouldComponentUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'bar' PropType is defined but prop is never used" line: 4 column: 10 ] , # Multiple destructured props inside of async class property code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' classProperty: =>' ' { bar, baz } = this.props' ' await bar()' ' await baz()' ].join '\n' # parser: 'babel-eslint' errors: [message: "'foo' PropType is defined but prop is never used"] , # Multiple props used inside of an async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' method: ->' ' await this.props.foo()' ' await this.props.baz()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'bar' PropType is defined but prop is never used" line: 4 column: 10 ] , code: [ 'class Hello extends Component' ' shouldComponentUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' errors: [ message: "'bar' PropType is defined but prop is never used" line: 7 column: 8 ] , code: [ 'class Hello extends Component' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' ' }' '' ' componentDidUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'bar' PropType is defined but prop is never used" line: 4 column: 10 ] , # Multiple destructured props inside of async class method code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' method: ->' ' { foo, bar } = this.props' ' await foo()' ' await bar()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'baz' PropType is defined but prop is never used" line: 5 column: 10 ] , # factory functions that return async functions code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' factory: ->' ' =>' ' await this.props.foo()' ' await this.props.bar()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'baz' PropType is defined but prop is never used" line: 5 column: 10 ] , code: [ 'class Hello extends Component' ' componentDidUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' 'Hello.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '}' ].join '\n' errors: [ message: "'bar' PropType is defined but prop is never used" line: 7 column: 8 ] , code: [ 'class Hello extends Component' ' componentDidUpdate: (nextProps) ->' ' if (nextProps.foo)' ' return true' 'Hello.propTypes = forbidExtraProps({' ' foo: PropTypes.string,' ' bar: PropTypes.string,' '})' ].join '\n' errors: [ message: "'bar' PropType is defined but prop is never used" line: 7 column: 8 ] settings: propWrapperFunctions: ['forbidExtraProps'] , # , # code: [ # 'class Hello extends Component' # ' propTypes = forbidExtraProps({' # ' foo: PropTypes.string,' # ' bar: PropTypes.string' # ' })' # ' componentDidUpdate: (nextProps) ->' # ' if (nextProps.foo)' # ' return true' # ].join '\n' # # parser: 'babel-eslint' # errors: [ # message: "'bar' PropType is defined but prop is never used" # line: 4 # column: 10 # ] # settings: # propWrapperFunctions: ['forbidExtraProps'] # factory functions that return async functions code: [ 'export class Example extends Component' ' @propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' ' }' ' factory: ->' ' return ->' ' await this.props.bar()' ' await this.props.baz()' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'foo' PropType is defined but prop is never used" line: 3 column: 10 ] , # Multiple props used inside of an async function code: [ 'class Example extends Component' ' render: ->' ' onSubmit = ->' ' await this.props.foo()' ' await this.props.bar()' ' return <Form onSubmit={onSubmit} />' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' '}' ].join '\n' errors: [ message: "'baz' PropType is defined but prop is never used" line: 10 column: 8 ] , # Multiple props used inside of an async arrow function code: [ 'class Example extends Component' ' render: ->' ' onSubmit = =>' ' await this.props.bar()' ' await this.props.baz()' ' return <Form onSubmit={onSubmit} />' 'Example.propTypes = {' ' foo: PropTypes.func,' ' bar: PropTypes.func,' ' baz: PropTypes.func,' '}' ].join '\n' errors: [ message: "'foo' PropType is defined but prop is never used" line: 8 column: 8 ] , # None of the props are used issue #1162 code: [ 'import React from "react" ' 'Hello = React.createReactClass({' ' propTypes: {' ' name: React.PropTypes.string' ' },' ' render: ->' ' return <div>Hello PI:NAME:<NAME>END_PI</div>' '})' ].join '\n' errors: [message: "'name' PropType is defined but prop is never used"] , code: [ 'class Comp1 extends Component' ' render: ->' ' return <span />' 'Comp1.propTypes = {' ' prop1: PropTypes.number' '}' 'class Comp2 extends Component' ' render: ->' ' return <span />' 'Comp2.propTypes = {' ' prop2: PropTypes.arrayOf(Comp1.propTypes.prop1)' '}' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'prop1' PropType is defined but prop is never used" , message: "'prop2' PropType is defined but prop is never used" , message: "'prop2.*' PropType is defined but prop is never used" ] , code: [ 'class Comp1 extends Component' ' render: ->' ' return <span />' 'Comp1.propTypes = {' ' prop1: PropTypes.number' '}' 'class Comp2 extends Component' ' @propTypes = {' ' prop2: PropTypes.arrayOf(Comp1.propTypes.prop1)' ' }' ' render: ->' ' return <span />' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'prop1' PropType is defined but prop is never used" , message: "'prop2' PropType is defined but prop is never used" , message: "'prop2.*' PropType is defined but prop is never used" ] , code: [ 'class Comp1 extends Component' ' render: ->' ' return <span />' 'Comp1.propTypes = {' ' prop1: PropTypes.number' '}' 'Comp2 = createReactClass({' ' propTypes: {' ' prop2: PropTypes.arrayOf(Comp1.propTypes.prop1)' ' },' ' render: ->' ' return <span />' '})' ].join '\n' # parser: 'babel-eslint' errors: [ message: "'prop1' PropType is defined but prop is never used" , message: "'prop2' PropType is defined but prop is never used" , message: "'prop2.*' PropType is defined but prop is never used" ] , # Destructured assignment with Shape propTypes with skipShapeProps off issue #816 code: [ 'export default class NavigationButton extends React.Component' ' @propTypes = {' ' route: PropTypes.shape({' ' getBarTintColor: PropTypes.func.isRequired,' ' }).isRequired,' ' }' ' renderTitle: ->' ' { route } = this.props' ' return <Title tintColor={route.getBarTintColor()}>TITLE</Title>' ].join '\n' # parser: 'babel-eslint' options: [skipShapeProps: no] errors: [ message: "'route.getBarTintColor' PropType is defined but prop is never used" ] , code: [ # issue #1097 'class HelloGraphQL extends Component' ' render: ->' ' return <div>Hello</div>' 'HelloGraphQL.propTypes = {' ' aProp: PropTypes.string.isRequired' '}' 'HellowQueries = graphql(queryDetails, {' ' options: (ownProps) => ({' ' variables: ownProps.aProp' ' }),' '})(HelloGraphQL)' 'export default connect(mapStateToProps, mapDispatchToProps)(HellowQueries)' ].join '\n' # parser: 'babel-eslint' errors: [message: "'aProp' PropType is defined but prop is never used"] , # , # code: """ # type Props = { # firstname: string, # lastname: string, # } # class MyComponent extends React.Component<void, Props, void> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: """ # type Props = { # firstname: string, # lastname: string, # } # class MyComponent extends React.Component<void, Props, void> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # settings: react: flowVersion: '0.52' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: """ # type Props = { # firstname: string, # lastname: string, # } # class MyComponent extends React.Component<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: """ # type Person = string # class Hello extends React.Component<{ person: Person }> { # render : -> # return <div /> # } # } # """ # settings: react: flowVersion: '0.53' # errors: [message: "'person' PropType is defined but prop is never used"] # , # # parser: 'babel-eslint' # code: """ # type Person = string # class Hello extends React.Component<void, { person: Person }, void> { # render : -> # return <div /> # } # } # """ # settings: react: flowVersion: '0.52' # errors: [message: "'person' PropType is defined but prop is never used"] # , # # parser: 'babel-eslint' # code: """ # function higherOrderComponent<P: { foo: string }>: -> # return class extends React.Component<P> { # render: -> # return <div /> # } # } # } # """ # errors: [message: "'foo' PropType is defined but prop is never used"] # parser: 'babel-eslint' # issue #1506 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState(({ doSomething }, props) =>' ' return { doSomething: doSomething + 1 }' ' )' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' errors: [ message: "'doSomething' PropType is defined but prop is never used" ] , # issue #1685 code: [ 'class MyComponent extends React.Component' ' onFoo: ->' ' this.setState((prevState) => ({' ' doSomething: prevState.doSomething + 1,' ' }))' ' render: ->' ' return (' ' <div onClick={this.onFoo}>Test</div>' ' )' 'MyComponent.propTypes = {' ' doSomething: PropTypes.func' '}' ].join '\n' errors: [ message: "'doSomething' PropType is defined but prop is never used" ] , # , # code: """ # type Props = { # firstname: string, # lastname: string, # } # class MyComponent extends React.Component<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # settings: react: flowVersion: '0.53' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] code: [ ''' class Hello extends Component @propTypes = { something: PropTypes.bool } UNSAFE_componentWillReceiveProps: (nextProps) -> {something} = nextProps doSomething(something) ''' ].join '\n' settings: react: version: '16.2.0' # parser: 'babel-eslint' errors: [message: "'something' PropType is defined but prop is never used"] , code: [ ''' class Hello extends Component @propTypes = { something: PropTypes.bool } UNSAFE_componentWillUpdate: (nextProps, nextState) -> {something} = nextProps return something ''' ].join '\n' settings: react: version: '16.2.0' # parser: 'babel-eslint' errors: [message: "'something' PropType is defined but prop is never used"] , code: [ ''' class MyComponent extends React.Component @propTypes = { defaultValue: 'bar' } state = { currentValue: null } @getDerivedStateFromProps: (nextProps, prevState) -> if (prevState.currentValue is null) return { currentValue: nextProps.defaultValue, } return null render: -> return <div>{ this.state.currentValue }</div> ''' ].join '\n' settings: react: version: '16.2.0' # parser: 'babel-eslint' errors: [ message: "'defaultValue' PropType is defined but prop is never used" ] , code: [ ''' class MyComponent extends React.Component @propTypes = { defaultValue: PropTypes.string } getSnapshotBeforeUpdate: (prevProps, prevState) -> if (prevProps.defaultValue is null) return 'snapshot' return null render: -> return <div /> ''' ].join '\n' settings: react: version: '16.2.0' # parser: 'babel-eslint' errors: [ message: "'defaultValue' PropType is defined but prop is never used" ] , # , # # Mixed union and intersection types # code: """ # import React from 'react' # type OtherProps = { # firstname: string, # lastname: string, # } | { # fullname: string # } # type Props = OtherProps & { # age: number # } # class Test extends React.PureComponent<Props> { # render: -> # return <div>Hello {this.props.firstname}</div> # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'age' PropType is defined but prop is never used"] code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello</div>' 'Hello.propTypes = {' ' a: PropTypes.shape({' ' b: PropTypes.shape({' ' })' ' })' '}' 'Hello.propTypes.a.b.c = PropTypes.number' ].join '\n' options: [skipShapeProps: no] errors: [ message: "'a' PropType is defined but prop is never used" , message: "'a.b' PropType is defined but prop is never used" , message: "'a.b.c' PropType is defined but prop is never used" ] , # , # code: """ # type Props = { foo: string } # function higherOrderComponent<Props>: -> # return class extends React.Component<Props> { # render: -> # return <div /> # } # } # } # """ # # parser: 'babel-eslint' # errors: [message: "'foo' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {' # ' ...data,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {|' # ' ...data,' # ' lastname: string' # '|}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {' # ' ...$Exact<data>,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # "import type {Data} from './Data'" # 'type Person = {' # ' ...Data,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.bar}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # "import type {Data} from 'some-libdef-like-flow-typed-provides'" # 'type Person = {' # ' ...Data,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.bar}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {' # ' ...data,' # ' lastname: string' # '}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] # , # code: [ # 'type Person = {|' # ' ...data,' # ' lastname: string' # '|}' # 'class Hello extends React.Component' # ' props: Person' # ' render : ->' # ' return <div>Hello {this.props.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # errors: [message: "'lastname' PropType is defined but prop is never used"] code: [ 'class Hello extends React.Component' ' render : ->' ' return <div>Hello {this.props.firstname}</div>' 'Hello.propTypes = {' ' ...BasePerson,' ' lastname: PropTypes.string' '}' ].join '\n' # parser: 'babel-eslint' errors: [message: "'lastname' PropType is defined but prop is never used"] , # , # code: [ # "import type {BasePerson} from './types'" # 'type Props = {' # ' person: {' # ' ...$Exact<BasePerson>,' # ' lastname: string' # ' }' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.person.firstname}</div>' # ' }' # '}' # ].join '\n' # # parser: 'babel-eslint' # options: [skipShapeProps: no] # errors: [ # message: "'person.lastname' PropType is defined but prop is never used" # ] code: [ "import BasePerson from './types'" 'class Hello extends React.Component' ' render : ->' ' return <div>Hello {this.props.person.firstname}</div>' 'Hello.propTypes = {' ' person: PropTypes.shape({' ' ...BasePerson,' ' lastname: PropTypes.string' ' })' '}' ].join '\n' options: [skipShapeProps: no] errors: [ message: "'person.lastname' PropType is defined but prop is never used" ] ### , { # Enable this when the following issue is fixed # https:#github.com/yannickcr/eslint-plugin-react/issues/296 code: [ 'function Foo(props) ->', ' { bar: { nope } } = props', ' return <div test={nope} />', '}', 'Foo.propTypes = {', ' foo: PropTypes.number,', ' bar: PropTypes.shape({', ' faz: PropTypes.number,', ' qaz: PropTypes.object,', ' }),', '}' ].join('\n'), # parser: 'babel-eslint', errors: [{ message: '\'foo\' PropType is defined but prop is never used' }] }### ]
[ { "context": "###\n# app.coffee\n# @author Sidharth Mishra\n# @description An example implementation of the s", "end": 42, "score": 0.9998809695243835, "start": 27, "tag": "NAME", "value": "Sidharth Mishra" } ]
src/cfs/app.coffee
sidmishraw/cedux
1
### # app.coffee # @author Sidharth Mishra # @description An example implementation of the same # @created Sun Nov 19 2017 23:35:06 GMT-0800 (PST) # @last-modified Sun Nov 19 2017 23:35:06 GMT-0800 (PST) ### import * as cedux from './index' # myReducer myReducer = (state, action) -> if action? and action.type? console.log "Action type: #{action.type}" switch action.type when 'fd' then 100 when 'rt' then 90 else 50 Store = cedux.cedux().createStore myReducer, 0 Store.dispatch {type:'fd'} console.log() console.log Store.getCurrentState() Store.dispatch {type:'rt'} console.log() console.log Store.getCurrentState() Store.dispatch {type:'I dunno Action'} console.log() console.log Store.getCurrentState() console.log("State Tree") console.log Store.getStateTree()
73593
### # app.coffee # @author <NAME> # @description An example implementation of the same # @created Sun Nov 19 2017 23:35:06 GMT-0800 (PST) # @last-modified Sun Nov 19 2017 23:35:06 GMT-0800 (PST) ### import * as cedux from './index' # myReducer myReducer = (state, action) -> if action? and action.type? console.log "Action type: #{action.type}" switch action.type when 'fd' then 100 when 'rt' then 90 else 50 Store = cedux.cedux().createStore myReducer, 0 Store.dispatch {type:'fd'} console.log() console.log Store.getCurrentState() Store.dispatch {type:'rt'} console.log() console.log Store.getCurrentState() Store.dispatch {type:'I dunno Action'} console.log() console.log Store.getCurrentState() console.log("State Tree") console.log Store.getStateTree()
true
### # app.coffee # @author PI:NAME:<NAME>END_PI # @description An example implementation of the same # @created Sun Nov 19 2017 23:35:06 GMT-0800 (PST) # @last-modified Sun Nov 19 2017 23:35:06 GMT-0800 (PST) ### import * as cedux from './index' # myReducer myReducer = (state, action) -> if action? and action.type? console.log "Action type: #{action.type}" switch action.type when 'fd' then 100 when 'rt' then 90 else 50 Store = cedux.cedux().createStore myReducer, 0 Store.dispatch {type:'fd'} console.log() console.log Store.getCurrentState() Store.dispatch {type:'rt'} console.log() console.log Store.getCurrentState() Store.dispatch {type:'I dunno Action'} console.log() console.log Store.getCurrentState() console.log("State Tree") console.log Store.getStateTree()
[ { "context": "ugin port of\n JavaScript Color Picker\n\n @author Honza Odvarko, http:#odvarko.cz\n @copyright Honza Odvarko\n @lic", "end": 78, "score": 0.9998941421508789, "start": 65, "tag": "NAME", "value": "Honza Odvarko" }, { "context": "hor Honza Odvarko, http:#odvarko.cz\n @copyright Honza Odvarko\n @license http://www.gnu.org/copyleft/gpl.html ", "end": 122, "score": 0.9996501207351685, "start": 109, "tag": "NAME", "value": "Honza Odvarko" }, { "context": " 1.0.9\n @link http://jscolor.com\n\n @ported_by Daniel Moore http://strd6.com\n @ported_by Matt Diebolt http://", "end": 274, "score": 0.9821171164512634, "start": 262, "tag": "NAME", "value": "Daniel Moore" }, { "context": "orted_by Daniel Moore http://strd6.com\n @ported_by Matt Diebolt http://pixieengine.com\n###\n\n#= require pixie/edit", "end": 316, "score": 0.999846339225769, "start": 304, "tag": "NAME", "value": "Matt Diebolt" } ]
vendor/assets/javascripts/jqcolor.coffee
PixieEngine/PixelEditor
1
### jQuery Plugin port of JavaScript Color Picker @author Honza Odvarko, http:#odvarko.cz @copyright Honza Odvarko @license http://www.gnu.org/copyleft/gpl.html GNU General Public License @version 1.0.9 @link http://jscolor.com @ported_by Daniel Moore http://strd6.com @ported_by Matt Diebolt http://pixieengine.com ### #= require pixie/editor/pixel/templates/color_picker (($) -> $.fn.colorPicker = (options) -> options ||= {} leadingHash = if options.leadingHash? then options.leadingHash else true dir = options.dir || '/assets/jscolor/' colorOverlaySize = 256 cursorSize = 15 sliderPointerHeight = 11 gradientStep = 2 instanceId = 0 instance = null colorPicker = $(JST["pixie/editor/pixel/templates/color_picker"]()) slider = colorPicker.find '.hue_selector' overlay = colorPicker.find '.color_overlay' gradient = colorPicker.find '.slider' cursorOverlay = colorPicker.find '.cursor_overlay' # TODO remove from window # not sure why I need to attach this to window # to make it work window.color = (hex) -> @hue = 0 @saturation = 1 @value = 0 @red = 0 @green = 0 @blue = 0 @setRGB = (r, g, b) -> @red = r if r? @green = g if g? @blue = b if b? hsv = RGB_HSV(@red, @green, @blue) @hue = hsv[0] @saturation = hsv[1] @value = hsv[2] @setHSV = (h, s, v) -> @hue = h if h? @saturation = s if s? @value = v if v? rgb = HSV_RGB(@hue, @saturation, @value) @red = rgb[0] @green = rgb[1] @blue = rgb[2] RGB_HSV = (r, g, b) -> n = Math.min(r,g,b) v = Math.max(r,g,b) m = v - n if m == 0 return [0, 0, v] if r == n h = 3 + (b - g) / m else if g == n h = 5 + (r - b) / m else h = 1 + (g - r) / m h = h % 6 return [h, m / v, v] HSV_RGB = (h, s, v) -> return [v, v, v] unless h? i = Math.floor(h) f = if i%2 then h-i else 1-(h-i) m = v * (1 - s) n = v * (1 - s*f) switch i when 0, 6 return [v, n, m] when 1 return [n, v, m] when 2 return [m, v, n] when 3 return [m, n, v] when 4 return [n, m, v] when 5 return [v, m, n] @setString = (hex) -> m = hex.match(/^\s*#?([0-9A-F]{3}([0-9A-F]{3})?)\s*$/i) if(m) if (m[1].length==6) @setRGB( parseInt(m[1].substr(0,2),16)/255, parseInt(m[1].substr(2,2),16)/255, parseInt(m[1].substr(4,2),16)/255 ) else @setRGB( parseInt(m[1].charAt(0)+m[1].charAt(0),16)/255, parseInt(m[1].charAt(1)+m[1].charAt(1),16)/255, parseInt(m[1].charAt(2)+m[1].charAt(2),16)/255 ) else @setRGB(0,0,0) return false @toString = -> [r, g, b] = ((color * 255).round().toString(16) for color in [@red, @green, @blue]) return ( (if r.length==1 then '0'+r else r)+ (if g.length==1 then '0'+g else g)+ (if b.length==1 then '0'+b else b) ).toUpperCase() if hex @setString(hex) createDialog = -> colorPicker.get(0).onmousedown = (e) -> instance.preserve = true cursorOverlay.css cursor: 'none' colorPicker.get(0).onmousemove = (e) -> setSV(e) if instance.overlayActive setHue(e) if instance.sliderActive colorPicker.get(0).onselectstart = (e) -> e.preventDefault() colorPicker.get(0).onmouseup = colorPicker.onmouseout = (e) -> cursorOverlay.css cursor: "url(/assets/jscolor/cross.png) 3 4, default" if (instance.overlayActive || instance.sliderActive) instance.overlayActive = instance.sliderActive = false # trigger change handler if we have bound a function instance.input.onchange?() instance.input.focus() setSV = (e) -> p = getMousePos(e) relX = (p.x - instance.cursor.x).clamp(0, colorOverlaySize) relY = (p.y - instance.cursor.y).clamp(0, colorOverlaySize) instance.color.saturation = relX / colorOverlaySize instance.color.value = 1 - (relY / colorOverlaySize) instance.color.setHSV() updateOverlayPosition(relX, relY) updateInput(instance.input, instance.color) overlay.get(0).onmousedown = (e) -> instance.overlayActive = true setSV(e) # saturation gradient's samples for i in [0...colorOverlaySize] by gradientStep g = $ '<div class="hue_gradient" />' g.css backgroundColor: "hsl(#{i}, 1, 0.5)" height: "#{gradientStep}px" $(gradient).append(g) setHue = (e) -> p = getMousePos(e) relY = (p.y - instance.sliderPosition).clamp(0, colorOverlaySize) instance.color.hue = ((relY / colorOverlaySize) * 6).clamp(0, 5.99) instance.color.setHSV() updateSliderPosition(relY) updateInput(instance.input, instance.color) slider.get(0).onmousedown = (e) -> instance.sliderActive = true setHue(e) slider.css cursor: 'none' slider.get(0).onmouseup = -> slider.css cursor: 'pointer' showDialog = (input) -> inputHeight = input.offsetHeight inputWidth = input.offsetWidth colorPickerWidth = 292 ip = getElementPos(input) dp = { x: ip.x + inputWidth - colorPickerWidth y: ip.y + inputHeight } instanceId++ instance = input: input color: new color(input.value) preserve: false overlayActive: false sliderActive: false cursor: {x: dp.x, y: dp.y} sliderPosition: dp.y updateOverlayPosition() updateSliderPosition() generateHueGradient() $(colorPicker).css left: "#{dp.x}px" top: "#{dp.y}px" $('body').append(colorPicker) hideDialog = -> $('body').find(colorPicker).remove() instance = null updateSliderPosition = (y) -> hue = instance.color.hue y ||= ((hue / 6) * colorOverlaySize).round() slider.css backgroundPosition: "0 #{(y - (sliderPointerHeight / 2) + 1).floor()}px" overlay.css backgroundColor: "hsl(#{hue * 60}, 100%, 50%)" updateOverlayPosition = (x, y) -> [hue, saturation, value] = [instance.color.hue, instance.color. saturation, instance.color.value] x ||= (saturation * colorOverlaySize).round() y ||= ((1 - value) * colorOverlaySize).round() cursorOverlay.css backgroundPosition: "#{((x - cursorSize / 2).floor())}px #{((y - cursorSize / 2).floor())}px" generateHueGradient = -> [hue, saturation, value] = [instance.color.hue, instance.color.saturation, instance.color.value] r = g = b = s = c = [value, 0, 0] gr_length = $(gradient).children().length $(gradient).children().each (i, element) -> hue = ((i / gr_length) * 360).round() $(element).css backgroundColor: "hsl(#{hue}, 100%, 50%)" updateInput = (el, color) -> $(el).val((if leadingHash then '#' else '') + color) $(el).css backgroundColor: '#' + color color: if color.value < 0.6 then '#FFF' else '#000' textShadow: if color.value < 0.6 then 'rgba(255, 255, 255, 0.2) 1px 1px' else 'rgba(0, 0, 0, 0.2) 1px 1px' getElementPos = (e) -> return { x: $(e).offset().left y: $(e).offset().top } getMousePos = (e) -> return { x: e.pageX y: e.pageY } focus = -> if instance?.preserve instance.preserve = false else showDialog(this) blur = -> return if instance?.preserve self = this id = instanceId setTimeout -> return if instance?.preserve if (instance && instanceId == id) hideDialog() updateInput(self, new color($(self).val())) , 0 createDialog() return @each -> self = this $(this).css backgroundColor: @value @originalStyle = color: @style.color backgroundColor: @style.backgroundColor $(this).attr('autocomplete', 'off') @onfocus = focus @onblur = blur updateInput(this, new color(this.value)) )(jQuery)
94821
### jQuery Plugin port of JavaScript Color Picker @author <NAME>, http:#odvarko.cz @copyright <NAME> @license http://www.gnu.org/copyleft/gpl.html GNU General Public License @version 1.0.9 @link http://jscolor.com @ported_by <NAME> http://strd6.com @ported_by <NAME> http://pixieengine.com ### #= require pixie/editor/pixel/templates/color_picker (($) -> $.fn.colorPicker = (options) -> options ||= {} leadingHash = if options.leadingHash? then options.leadingHash else true dir = options.dir || '/assets/jscolor/' colorOverlaySize = 256 cursorSize = 15 sliderPointerHeight = 11 gradientStep = 2 instanceId = 0 instance = null colorPicker = $(JST["pixie/editor/pixel/templates/color_picker"]()) slider = colorPicker.find '.hue_selector' overlay = colorPicker.find '.color_overlay' gradient = colorPicker.find '.slider' cursorOverlay = colorPicker.find '.cursor_overlay' # TODO remove from window # not sure why I need to attach this to window # to make it work window.color = (hex) -> @hue = 0 @saturation = 1 @value = 0 @red = 0 @green = 0 @blue = 0 @setRGB = (r, g, b) -> @red = r if r? @green = g if g? @blue = b if b? hsv = RGB_HSV(@red, @green, @blue) @hue = hsv[0] @saturation = hsv[1] @value = hsv[2] @setHSV = (h, s, v) -> @hue = h if h? @saturation = s if s? @value = v if v? rgb = HSV_RGB(@hue, @saturation, @value) @red = rgb[0] @green = rgb[1] @blue = rgb[2] RGB_HSV = (r, g, b) -> n = Math.min(r,g,b) v = Math.max(r,g,b) m = v - n if m == 0 return [0, 0, v] if r == n h = 3 + (b - g) / m else if g == n h = 5 + (r - b) / m else h = 1 + (g - r) / m h = h % 6 return [h, m / v, v] HSV_RGB = (h, s, v) -> return [v, v, v] unless h? i = Math.floor(h) f = if i%2 then h-i else 1-(h-i) m = v * (1 - s) n = v * (1 - s*f) switch i when 0, 6 return [v, n, m] when 1 return [n, v, m] when 2 return [m, v, n] when 3 return [m, n, v] when 4 return [n, m, v] when 5 return [v, m, n] @setString = (hex) -> m = hex.match(/^\s*#?([0-9A-F]{3}([0-9A-F]{3})?)\s*$/i) if(m) if (m[1].length==6) @setRGB( parseInt(m[1].substr(0,2),16)/255, parseInt(m[1].substr(2,2),16)/255, parseInt(m[1].substr(4,2),16)/255 ) else @setRGB( parseInt(m[1].charAt(0)+m[1].charAt(0),16)/255, parseInt(m[1].charAt(1)+m[1].charAt(1),16)/255, parseInt(m[1].charAt(2)+m[1].charAt(2),16)/255 ) else @setRGB(0,0,0) return false @toString = -> [r, g, b] = ((color * 255).round().toString(16) for color in [@red, @green, @blue]) return ( (if r.length==1 then '0'+r else r)+ (if g.length==1 then '0'+g else g)+ (if b.length==1 then '0'+b else b) ).toUpperCase() if hex @setString(hex) createDialog = -> colorPicker.get(0).onmousedown = (e) -> instance.preserve = true cursorOverlay.css cursor: 'none' colorPicker.get(0).onmousemove = (e) -> setSV(e) if instance.overlayActive setHue(e) if instance.sliderActive colorPicker.get(0).onselectstart = (e) -> e.preventDefault() colorPicker.get(0).onmouseup = colorPicker.onmouseout = (e) -> cursorOverlay.css cursor: "url(/assets/jscolor/cross.png) 3 4, default" if (instance.overlayActive || instance.sliderActive) instance.overlayActive = instance.sliderActive = false # trigger change handler if we have bound a function instance.input.onchange?() instance.input.focus() setSV = (e) -> p = getMousePos(e) relX = (p.x - instance.cursor.x).clamp(0, colorOverlaySize) relY = (p.y - instance.cursor.y).clamp(0, colorOverlaySize) instance.color.saturation = relX / colorOverlaySize instance.color.value = 1 - (relY / colorOverlaySize) instance.color.setHSV() updateOverlayPosition(relX, relY) updateInput(instance.input, instance.color) overlay.get(0).onmousedown = (e) -> instance.overlayActive = true setSV(e) # saturation gradient's samples for i in [0...colorOverlaySize] by gradientStep g = $ '<div class="hue_gradient" />' g.css backgroundColor: "hsl(#{i}, 1, 0.5)" height: "#{gradientStep}px" $(gradient).append(g) setHue = (e) -> p = getMousePos(e) relY = (p.y - instance.sliderPosition).clamp(0, colorOverlaySize) instance.color.hue = ((relY / colorOverlaySize) * 6).clamp(0, 5.99) instance.color.setHSV() updateSliderPosition(relY) updateInput(instance.input, instance.color) slider.get(0).onmousedown = (e) -> instance.sliderActive = true setHue(e) slider.css cursor: 'none' slider.get(0).onmouseup = -> slider.css cursor: 'pointer' showDialog = (input) -> inputHeight = input.offsetHeight inputWidth = input.offsetWidth colorPickerWidth = 292 ip = getElementPos(input) dp = { x: ip.x + inputWidth - colorPickerWidth y: ip.y + inputHeight } instanceId++ instance = input: input color: new color(input.value) preserve: false overlayActive: false sliderActive: false cursor: {x: dp.x, y: dp.y} sliderPosition: dp.y updateOverlayPosition() updateSliderPosition() generateHueGradient() $(colorPicker).css left: "#{dp.x}px" top: "#{dp.y}px" $('body').append(colorPicker) hideDialog = -> $('body').find(colorPicker).remove() instance = null updateSliderPosition = (y) -> hue = instance.color.hue y ||= ((hue / 6) * colorOverlaySize).round() slider.css backgroundPosition: "0 #{(y - (sliderPointerHeight / 2) + 1).floor()}px" overlay.css backgroundColor: "hsl(#{hue * 60}, 100%, 50%)" updateOverlayPosition = (x, y) -> [hue, saturation, value] = [instance.color.hue, instance.color. saturation, instance.color.value] x ||= (saturation * colorOverlaySize).round() y ||= ((1 - value) * colorOverlaySize).round() cursorOverlay.css backgroundPosition: "#{((x - cursorSize / 2).floor())}px #{((y - cursorSize / 2).floor())}px" generateHueGradient = -> [hue, saturation, value] = [instance.color.hue, instance.color.saturation, instance.color.value] r = g = b = s = c = [value, 0, 0] gr_length = $(gradient).children().length $(gradient).children().each (i, element) -> hue = ((i / gr_length) * 360).round() $(element).css backgroundColor: "hsl(#{hue}, 100%, 50%)" updateInput = (el, color) -> $(el).val((if leadingHash then '#' else '') + color) $(el).css backgroundColor: '#' + color color: if color.value < 0.6 then '#FFF' else '#000' textShadow: if color.value < 0.6 then 'rgba(255, 255, 255, 0.2) 1px 1px' else 'rgba(0, 0, 0, 0.2) 1px 1px' getElementPos = (e) -> return { x: $(e).offset().left y: $(e).offset().top } getMousePos = (e) -> return { x: e.pageX y: e.pageY } focus = -> if instance?.preserve instance.preserve = false else showDialog(this) blur = -> return if instance?.preserve self = this id = instanceId setTimeout -> return if instance?.preserve if (instance && instanceId == id) hideDialog() updateInput(self, new color($(self).val())) , 0 createDialog() return @each -> self = this $(this).css backgroundColor: @value @originalStyle = color: @style.color backgroundColor: @style.backgroundColor $(this).attr('autocomplete', 'off') @onfocus = focus @onblur = blur updateInput(this, new color(this.value)) )(jQuery)
true
### jQuery Plugin port of JavaScript Color Picker @author PI:NAME:<NAME>END_PI, http:#odvarko.cz @copyright PI:NAME:<NAME>END_PI @license http://www.gnu.org/copyleft/gpl.html GNU General Public License @version 1.0.9 @link http://jscolor.com @ported_by PI:NAME:<NAME>END_PI http://strd6.com @ported_by PI:NAME:<NAME>END_PI http://pixieengine.com ### #= require pixie/editor/pixel/templates/color_picker (($) -> $.fn.colorPicker = (options) -> options ||= {} leadingHash = if options.leadingHash? then options.leadingHash else true dir = options.dir || '/assets/jscolor/' colorOverlaySize = 256 cursorSize = 15 sliderPointerHeight = 11 gradientStep = 2 instanceId = 0 instance = null colorPicker = $(JST["pixie/editor/pixel/templates/color_picker"]()) slider = colorPicker.find '.hue_selector' overlay = colorPicker.find '.color_overlay' gradient = colorPicker.find '.slider' cursorOverlay = colorPicker.find '.cursor_overlay' # TODO remove from window # not sure why I need to attach this to window # to make it work window.color = (hex) -> @hue = 0 @saturation = 1 @value = 0 @red = 0 @green = 0 @blue = 0 @setRGB = (r, g, b) -> @red = r if r? @green = g if g? @blue = b if b? hsv = RGB_HSV(@red, @green, @blue) @hue = hsv[0] @saturation = hsv[1] @value = hsv[2] @setHSV = (h, s, v) -> @hue = h if h? @saturation = s if s? @value = v if v? rgb = HSV_RGB(@hue, @saturation, @value) @red = rgb[0] @green = rgb[1] @blue = rgb[2] RGB_HSV = (r, g, b) -> n = Math.min(r,g,b) v = Math.max(r,g,b) m = v - n if m == 0 return [0, 0, v] if r == n h = 3 + (b - g) / m else if g == n h = 5 + (r - b) / m else h = 1 + (g - r) / m h = h % 6 return [h, m / v, v] HSV_RGB = (h, s, v) -> return [v, v, v] unless h? i = Math.floor(h) f = if i%2 then h-i else 1-(h-i) m = v * (1 - s) n = v * (1 - s*f) switch i when 0, 6 return [v, n, m] when 1 return [n, v, m] when 2 return [m, v, n] when 3 return [m, n, v] when 4 return [n, m, v] when 5 return [v, m, n] @setString = (hex) -> m = hex.match(/^\s*#?([0-9A-F]{3}([0-9A-F]{3})?)\s*$/i) if(m) if (m[1].length==6) @setRGB( parseInt(m[1].substr(0,2),16)/255, parseInt(m[1].substr(2,2),16)/255, parseInt(m[1].substr(4,2),16)/255 ) else @setRGB( parseInt(m[1].charAt(0)+m[1].charAt(0),16)/255, parseInt(m[1].charAt(1)+m[1].charAt(1),16)/255, parseInt(m[1].charAt(2)+m[1].charAt(2),16)/255 ) else @setRGB(0,0,0) return false @toString = -> [r, g, b] = ((color * 255).round().toString(16) for color in [@red, @green, @blue]) return ( (if r.length==1 then '0'+r else r)+ (if g.length==1 then '0'+g else g)+ (if b.length==1 then '0'+b else b) ).toUpperCase() if hex @setString(hex) createDialog = -> colorPicker.get(0).onmousedown = (e) -> instance.preserve = true cursorOverlay.css cursor: 'none' colorPicker.get(0).onmousemove = (e) -> setSV(e) if instance.overlayActive setHue(e) if instance.sliderActive colorPicker.get(0).onselectstart = (e) -> e.preventDefault() colorPicker.get(0).onmouseup = colorPicker.onmouseout = (e) -> cursorOverlay.css cursor: "url(/assets/jscolor/cross.png) 3 4, default" if (instance.overlayActive || instance.sliderActive) instance.overlayActive = instance.sliderActive = false # trigger change handler if we have bound a function instance.input.onchange?() instance.input.focus() setSV = (e) -> p = getMousePos(e) relX = (p.x - instance.cursor.x).clamp(0, colorOverlaySize) relY = (p.y - instance.cursor.y).clamp(0, colorOverlaySize) instance.color.saturation = relX / colorOverlaySize instance.color.value = 1 - (relY / colorOverlaySize) instance.color.setHSV() updateOverlayPosition(relX, relY) updateInput(instance.input, instance.color) overlay.get(0).onmousedown = (e) -> instance.overlayActive = true setSV(e) # saturation gradient's samples for i in [0...colorOverlaySize] by gradientStep g = $ '<div class="hue_gradient" />' g.css backgroundColor: "hsl(#{i}, 1, 0.5)" height: "#{gradientStep}px" $(gradient).append(g) setHue = (e) -> p = getMousePos(e) relY = (p.y - instance.sliderPosition).clamp(0, colorOverlaySize) instance.color.hue = ((relY / colorOverlaySize) * 6).clamp(0, 5.99) instance.color.setHSV() updateSliderPosition(relY) updateInput(instance.input, instance.color) slider.get(0).onmousedown = (e) -> instance.sliderActive = true setHue(e) slider.css cursor: 'none' slider.get(0).onmouseup = -> slider.css cursor: 'pointer' showDialog = (input) -> inputHeight = input.offsetHeight inputWidth = input.offsetWidth colorPickerWidth = 292 ip = getElementPos(input) dp = { x: ip.x + inputWidth - colorPickerWidth y: ip.y + inputHeight } instanceId++ instance = input: input color: new color(input.value) preserve: false overlayActive: false sliderActive: false cursor: {x: dp.x, y: dp.y} sliderPosition: dp.y updateOverlayPosition() updateSliderPosition() generateHueGradient() $(colorPicker).css left: "#{dp.x}px" top: "#{dp.y}px" $('body').append(colorPicker) hideDialog = -> $('body').find(colorPicker).remove() instance = null updateSliderPosition = (y) -> hue = instance.color.hue y ||= ((hue / 6) * colorOverlaySize).round() slider.css backgroundPosition: "0 #{(y - (sliderPointerHeight / 2) + 1).floor()}px" overlay.css backgroundColor: "hsl(#{hue * 60}, 100%, 50%)" updateOverlayPosition = (x, y) -> [hue, saturation, value] = [instance.color.hue, instance.color. saturation, instance.color.value] x ||= (saturation * colorOverlaySize).round() y ||= ((1 - value) * colorOverlaySize).round() cursorOverlay.css backgroundPosition: "#{((x - cursorSize / 2).floor())}px #{((y - cursorSize / 2).floor())}px" generateHueGradient = -> [hue, saturation, value] = [instance.color.hue, instance.color.saturation, instance.color.value] r = g = b = s = c = [value, 0, 0] gr_length = $(gradient).children().length $(gradient).children().each (i, element) -> hue = ((i / gr_length) * 360).round() $(element).css backgroundColor: "hsl(#{hue}, 100%, 50%)" updateInput = (el, color) -> $(el).val((if leadingHash then '#' else '') + color) $(el).css backgroundColor: '#' + color color: if color.value < 0.6 then '#FFF' else '#000' textShadow: if color.value < 0.6 then 'rgba(255, 255, 255, 0.2) 1px 1px' else 'rgba(0, 0, 0, 0.2) 1px 1px' getElementPos = (e) -> return { x: $(e).offset().left y: $(e).offset().top } getMousePos = (e) -> return { x: e.pageX y: e.pageY } focus = -> if instance?.preserve instance.preserve = false else showDialog(this) blur = -> return if instance?.preserve self = this id = instanceId setTimeout -> return if instance?.preserve if (instance && instanceId == id) hideDialog() updateInput(self, new color($(self).val())) , 0 createDialog() return @each -> self = this $(this).css backgroundColor: @value @originalStyle = color: @style.color backgroundColor: @style.backgroundColor $(this).attr('autocomplete', 'off') @onfocus = focus @onblur = blur updateInput(this, new color(this.value)) )(jQuery)
[ { "context": "sel = 0\nsc_api_key='?client_id=0557caec313ae36a9d6a21841293da11'\n\nhttpGet = (theU", "end": 31, "score": 0.9768458604812622, "start": 21, "tag": "KEY", "value": "client_id=" }, { "context": "sel = 0\nsc_api_key='?client_id=0557caec313ae36a9d6a21841293da11'\n\nhttpGet = (theUrl)->\n\txmlHttp = null\n\txmlHttp =", "end": 63, "score": 0.9885454177856445, "start": 31, "tag": "KEY", "value": "0557caec313ae36a9d6a21841293da11" }, { "context": "ethod=artist.getcorrection&artist='+str+'&api_key=a75bd15e529625f1fcc5eff85ddb2c05&format=json'\n\tjsonArr = JSON.parse(httpGet(url))\n", "end": 843, "score": 0.9997655749320984, "start": 811, "tag": "KEY", "value": "a75bd15e529625f1fcc5eff85ddb2c05" } ]
helper.coffee
ChipaKraken/angular-music
2
sel = 0 sc_api_key='?client_id=0557caec313ae36a9d6a21841293da11' httpGet = (theUrl)-> xmlHttp = null xmlHttp = new XMLHttpRequest() xmlHttp.open('GET', theUrl, false) xmlHttp.send(null) xmlHttp.responseText squerify = (img)-> img.replace('/252/','/126s/') get_sim_name = (sim)-> arts = [] arts.push(sim[0].name) arts.push(sim[1].name) arts.push(sim[2].name) arts.push(sim[3].name) arts.push(sim[4].name) arts get_imgs = (sim)-> imgs= [] imgs.push(squerify(sim[0].image[3]['#text'])) imgs.push(squerify(sim[1].image[3]['#text'])) imgs.push(squerify(sim[2].image[3]['#text'])) imgs.push(squerify(sim[3].image[3]['#text'])) imgs.push(squerify(sim[4].image[3]['#text'])) imgs corrector = (str)-> url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getcorrection&artist='+str+'&api_key=a75bd15e529625f1fcc5eff85ddb2c05&format=json' jsonArr = JSON.parse(httpGet(url)) try ans = jsonArr.corrections.correction.artist.name catch e ans = str ans
112925
sel = 0 sc_api_key='?<KEY> <KEY>' httpGet = (theUrl)-> xmlHttp = null xmlHttp = new XMLHttpRequest() xmlHttp.open('GET', theUrl, false) xmlHttp.send(null) xmlHttp.responseText squerify = (img)-> img.replace('/252/','/126s/') get_sim_name = (sim)-> arts = [] arts.push(sim[0].name) arts.push(sim[1].name) arts.push(sim[2].name) arts.push(sim[3].name) arts.push(sim[4].name) arts get_imgs = (sim)-> imgs= [] imgs.push(squerify(sim[0].image[3]['#text'])) imgs.push(squerify(sim[1].image[3]['#text'])) imgs.push(squerify(sim[2].image[3]['#text'])) imgs.push(squerify(sim[3].image[3]['#text'])) imgs.push(squerify(sim[4].image[3]['#text'])) imgs corrector = (str)-> url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getcorrection&artist='+str+'&api_key=<KEY>&format=json' jsonArr = JSON.parse(httpGet(url)) try ans = jsonArr.corrections.correction.artist.name catch e ans = str ans
true
sel = 0 sc_api_key='?PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI' httpGet = (theUrl)-> xmlHttp = null xmlHttp = new XMLHttpRequest() xmlHttp.open('GET', theUrl, false) xmlHttp.send(null) xmlHttp.responseText squerify = (img)-> img.replace('/252/','/126s/') get_sim_name = (sim)-> arts = [] arts.push(sim[0].name) arts.push(sim[1].name) arts.push(sim[2].name) arts.push(sim[3].name) arts.push(sim[4].name) arts get_imgs = (sim)-> imgs= [] imgs.push(squerify(sim[0].image[3]['#text'])) imgs.push(squerify(sim[1].image[3]['#text'])) imgs.push(squerify(sim[2].image[3]['#text'])) imgs.push(squerify(sim[3].image[3]['#text'])) imgs.push(squerify(sim[4].image[3]['#text'])) imgs corrector = (str)-> url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getcorrection&artist='+str+'&api_key=PI:KEY:<KEY>END_PI&format=json' jsonArr = JSON.parse(httpGet(url)) try ans = jsonArr.corrections.correction.artist.name catch e ans = str ans
[ { "context": "###\n# grunt/watch.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# Define our wat", "end": 47, "score": 0.9996291995048523, "start": 36, "tag": "NAME", "value": "Dan Nichols" } ]
grunt/watch.coffee
dlnichols/h_media
0
### # grunt/watch.coffee # # © 2014 Dan Nichols # See LICENSE for more details # # Define our watch configuration block for grunt ### 'use strict' module.exports = # Watch settings # TODO: These need to be updated, they kinda work, but not entirely js: files: [ 'app/scripts/**/*.js' ] tasks: [ 'newer:jshint:serve' ] options: livereload: true coffee: files: [ 'app/scripts/**/*.coffee' ] tasks: [ 'newer:coffee:serve' ] options: livereload: true compass: files: [ 'app/styles/**/*.scss' ] tasks: [ 'compass:serve' ] options: livereload: true less: files: [ 'app/styles/{,*/}*.less' ] tasks: [ 'newer:less:serve' ] options: livereload: true gruntfile: files: [ 'Gruntfile.js' ] express: files: [ 'server.coffee' 'lib/**/*.coffee' ] tasks: [ 'express:dev' 'wait' ] options: livereload: true nospawn: true
60002
### # grunt/watch.coffee # # © 2014 <NAME> # See LICENSE for more details # # Define our watch configuration block for grunt ### 'use strict' module.exports = # Watch settings # TODO: These need to be updated, they kinda work, but not entirely js: files: [ 'app/scripts/**/*.js' ] tasks: [ 'newer:jshint:serve' ] options: livereload: true coffee: files: [ 'app/scripts/**/*.coffee' ] tasks: [ 'newer:coffee:serve' ] options: livereload: true compass: files: [ 'app/styles/**/*.scss' ] tasks: [ 'compass:serve' ] options: livereload: true less: files: [ 'app/styles/{,*/}*.less' ] tasks: [ 'newer:less:serve' ] options: livereload: true gruntfile: files: [ 'Gruntfile.js' ] express: files: [ 'server.coffee' 'lib/**/*.coffee' ] tasks: [ 'express:dev' 'wait' ] options: livereload: true nospawn: true
true
### # grunt/watch.coffee # # © 2014 PI:NAME:<NAME>END_PI # See LICENSE for more details # # Define our watch configuration block for grunt ### 'use strict' module.exports = # Watch settings # TODO: These need to be updated, they kinda work, but not entirely js: files: [ 'app/scripts/**/*.js' ] tasks: [ 'newer:jshint:serve' ] options: livereload: true coffee: files: [ 'app/scripts/**/*.coffee' ] tasks: [ 'newer:coffee:serve' ] options: livereload: true compass: files: [ 'app/styles/**/*.scss' ] tasks: [ 'compass:serve' ] options: livereload: true less: files: [ 'app/styles/{,*/}*.less' ] tasks: [ 'newer:less:serve' ] options: livereload: true gruntfile: files: [ 'Gruntfile.js' ] express: files: [ 'server.coffee' 'lib/**/*.coffee' ] tasks: [ 'express:dev' 'wait' ] options: livereload: true nospawn: true
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9758449196815491, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "make the process\n# * hang. See https://github.com/joyent/node/issues/8065 and\n# * https://github.com/joyen", "end": 1234, "score": 0.9995604753494263, "start": 1228, "tag": "USERNAME", "value": "joyent" }, { "context": "oyent/node/issues/8065 and\n# * https://github.com/joyent/node/issues/8068 which have been fixed by\n# * htt", "end": 1285, "score": 0.9995594024658203, "start": 1279, "tag": "USERNAME", "value": "joyent" }, { "context": "8 which have been fixed by\n# * https://github.com/joyent/node/pull/8073.\n# *\n# * If the process hangs, thi", "end": 1357, "score": 0.9995474815368652, "start": 1351, "tag": "USERNAME", "value": "joyent" } ]
test/simple/test-timers-non-integer-delay.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. # # * This test makes sure that non-integer timer delays do not make the process # * hang. See https://github.com/joyent/node/issues/8065 and # * https://github.com/joyent/node/issues/8068 which have been fixed by # * https://github.com/joyent/node/pull/8073. # * # * If the process hangs, this test will make the tests suite timeout, # * otherwise it will exit very quickly (after 50 timers with a short delay # * fire). # * # * We have to set at least several timers with a non-integer delay to # * reproduce the issue. Sometimes, a timer with a non-integer delay will # * expire correctly. 50 timers has always been more than enough to reproduce # * it 100%. # assert = require("assert") TIMEOUT_DELAY = 1.1 NB_TIMEOUTS_FIRED = 50 nbTimeoutFired = 0 interval = setInterval(-> ++nbTimeoutFired if nbTimeoutFired is NB_TIMEOUTS_FIRED clearInterval interval process.exit 0 return , TIMEOUT_DELAY)
89342
# 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. # # * This test makes sure that non-integer timer delays do not make the process # * hang. See https://github.com/joyent/node/issues/8065 and # * https://github.com/joyent/node/issues/8068 which have been fixed by # * https://github.com/joyent/node/pull/8073. # * # * If the process hangs, this test will make the tests suite timeout, # * otherwise it will exit very quickly (after 50 timers with a short delay # * fire). # * # * We have to set at least several timers with a non-integer delay to # * reproduce the issue. Sometimes, a timer with a non-integer delay will # * expire correctly. 50 timers has always been more than enough to reproduce # * it 100%. # assert = require("assert") TIMEOUT_DELAY = 1.1 NB_TIMEOUTS_FIRED = 50 nbTimeoutFired = 0 interval = setInterval(-> ++nbTimeoutFired if nbTimeoutFired is NB_TIMEOUTS_FIRED clearInterval interval process.exit 0 return , TIMEOUT_DELAY)
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. # # * This test makes sure that non-integer timer delays do not make the process # * hang. See https://github.com/joyent/node/issues/8065 and # * https://github.com/joyent/node/issues/8068 which have been fixed by # * https://github.com/joyent/node/pull/8073. # * # * If the process hangs, this test will make the tests suite timeout, # * otherwise it will exit very quickly (after 50 timers with a short delay # * fire). # * # * We have to set at least several timers with a non-integer delay to # * reproduce the issue. Sometimes, a timer with a non-integer delay will # * expire correctly. 50 timers has always been more than enough to reproduce # * it 100%. # assert = require("assert") TIMEOUT_DELAY = 1.1 NB_TIMEOUTS_FIRED = 50 nbTimeoutFired = 0 interval = setInterval(-> ++nbTimeoutFired if nbTimeoutFired is NB_TIMEOUTS_FIRED clearInterval interval process.exit 0 return , TIMEOUT_DELAY)
[ { "context": "_home_ethernet]\n\t\tType = ethernet\n\t\tNameservers = 8.8.8.8,8.8.4.4\n\n\t\t[service_home_wifi]\n\t\tType = wifi\n\t\tNa", "end": 738, "score": 0.9996111989021301, "start": 731, "tag": "IP_ADDRESS", "value": "8.8.8.8" }, { "context": "hernet]\n\t\tType = ethernet\n\t\tNameservers = 8.8.8.8,8.8.4.4\n\n\t\t[service_home_wifi]\n\t\tType = wifi\n\t\tName = #{r", "end": 746, "score": 0.9980185627937317, "start": 739, "tag": "IP_ADDRESS", "value": "8.8.4.4" }, { "context": "= wifi\n\t\tName = #{req.body.ssid}\n\t\tPassphrase = #{req.body.passphrase}\n\t\tNameservers = 8.8.8.8,8.8.4.4\n\n\t\"\"\"\n\n\tPromise.", "end": 846, "score": 0.9766886830329895, "start": 827, "tag": "PASSWORD", "value": "req.body.passphrase" }, { "context": "ssphrase = #{req.body.passphrase}\n\t\tNameservers = 8.8.8.8,8.8.4.4\n\n\t\"\"\"\n\n\tPromise.all [\n\t\tutils.durableWrit", "end": 871, "score": 0.9995294809341431, "start": 864, "tag": "IP_ADDRESS", "value": "8.8.8.8" }, { "context": " = #{req.body.passphrase}\n\t\tNameservers = 8.8.8.8,8.8.4.4\n\n\t\"\"\"\n\n\tPromise.all [\n\t\tutils.durableWriteFile(co", "end": 879, "score": 0.9899100065231323, "start": 872, "tag": "IP_ADDRESS", "value": "8.8.4.4" } ]
app/src/app.coffee
resin-io-playground/resin-kitracom-web
1
Promise = require 'bluebird' fs = Promise.promisifyAll(require('fs')) express = require 'express' bodyParser = require 'body-parser' config = require './config' utils = require './utils' connman = require './connman' hotspot = require './hotspot' wifiScan = require './wifi-scan' app = express() app.use(bodyParser.json()) app.use(bodyParser.urlencoded(extended: true)) app.use(express.static(__dirname + '/public')) ssids = [] app.get '/ssids', (req, res) -> res.json(ssids) app.post '/connect', (req, res) -> if not (req.body.ssid? and req.body.passphrase?) return res.sendStatus(400) console.log('Selected ' + req.body.ssid) res.send('OK') data = """ [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 [service_home_wifi] Type = wifi Name = #{req.body.ssid} Passphrase = #{req.body.passphrase} Nameservers = 8.8.8.8,8.8.4.4 """ Promise.all [ utils.durableWriteFile(config.connmanConfig, data) hotspot.stop() ] # XXX: make it so this delay isn't needed .delay(1000) .then -> connman.waitForConnection(15000) .then -> utils.durableWriteFile(config.persistentConfig, data) .then -> process.exit() .catch (e) -> hotspot.start() app.use (req, res) -> res.redirect('/') wifiScan.scanAsync() .then (results) -> ssids = results hotspot.start() app.listen(80)
166495
Promise = require 'bluebird' fs = Promise.promisifyAll(require('fs')) express = require 'express' bodyParser = require 'body-parser' config = require './config' utils = require './utils' connman = require './connman' hotspot = require './hotspot' wifiScan = require './wifi-scan' app = express() app.use(bodyParser.json()) app.use(bodyParser.urlencoded(extended: true)) app.use(express.static(__dirname + '/public')) ssids = [] app.get '/ssids', (req, res) -> res.json(ssids) app.post '/connect', (req, res) -> if not (req.body.ssid? and req.body.passphrase?) return res.sendStatus(400) console.log('Selected ' + req.body.ssid) res.send('OK') data = """ [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 [service_home_wifi] Type = wifi Name = #{req.body.ssid} Passphrase = #{<PASSWORD>} Nameservers = 8.8.8.8,8.8.4.4 """ Promise.all [ utils.durableWriteFile(config.connmanConfig, data) hotspot.stop() ] # XXX: make it so this delay isn't needed .delay(1000) .then -> connman.waitForConnection(15000) .then -> utils.durableWriteFile(config.persistentConfig, data) .then -> process.exit() .catch (e) -> hotspot.start() app.use (req, res) -> res.redirect('/') wifiScan.scanAsync() .then (results) -> ssids = results hotspot.start() app.listen(80)
true
Promise = require 'bluebird' fs = Promise.promisifyAll(require('fs')) express = require 'express' bodyParser = require 'body-parser' config = require './config' utils = require './utils' connman = require './connman' hotspot = require './hotspot' wifiScan = require './wifi-scan' app = express() app.use(bodyParser.json()) app.use(bodyParser.urlencoded(extended: true)) app.use(express.static(__dirname + '/public')) ssids = [] app.get '/ssids', (req, res) -> res.json(ssids) app.post '/connect', (req, res) -> if not (req.body.ssid? and req.body.passphrase?) return res.sendStatus(400) console.log('Selected ' + req.body.ssid) res.send('OK') data = """ [service_home_ethernet] Type = ethernet Nameservers = 8.8.8.8,8.8.4.4 [service_home_wifi] Type = wifi Name = #{req.body.ssid} Passphrase = #{PI:PASSWORD:<PASSWORD>END_PI} Nameservers = 8.8.8.8,8.8.4.4 """ Promise.all [ utils.durableWriteFile(config.connmanConfig, data) hotspot.stop() ] # XXX: make it so this delay isn't needed .delay(1000) .then -> connman.waitForConnection(15000) .then -> utils.durableWriteFile(config.persistentConfig, data) .then -> process.exit() .catch (e) -> hotspot.start() app.use (req, res) -> res.redirect('/') wifiScan.scanAsync() .then (results) -> ssids = results hotspot.start() app.listen(80)
[ { "context": "nly\"\n input: [\n token: \"testStatementB\"\n starts: 25\n ", "end": 2582, "score": 0.6273769736289978, "start": 2578, "tag": "KEY", "value": "test" }, { "context": " input: [\n token: \"testStatementB\"\n starts: 25\n ends:", "end": 2592, "score": 0.5452215075492859, "start": 2591, "tag": "KEY", "value": "B" }, { "context": " statement:\n token: \"testStatementB\"\n starts: 25\n ", "end": 2767, "score": 0.5369329452514648, "start": 2763, "tag": "KEY", "value": "test" } ]
src/coffee/expression/parse/statement/findNext.spec.coffee
jameswilddev/influx7
1
describe "expression", -> describe "parse", -> describe "statement", -> describe "findNext", -> rewire = require "rewire" describe "imports", -> expressionParseStatementFindNext = rewire "./findNext" it "expressionParseStatementFunctions", -> (expect expressionParseStatementFindNext.__get__ "expressionParseStatementFunctions").toBe require "./functions" describe "on calling", -> expressionParseStatementFindNext = rewire "./findNext" expressionParseStatementFunctions = testStatementA: -> fail "unexpected call to testStatementA" testStatementB: -> fail "unexpected call to testStatementB" testStatementC: -> fail "unexpected call to testStatementC" testStatementD: -> fail "unexpected call to testStatementD" run = (config) -> describe config.description, -> inputCopy = expressionParseStatementFunctionsCopy = undefined beforeEach -> expressionParseStatementFunctionsCopy = {} for key, value of expressionParseStatementFunctions expressionParseStatementFunctionsCopy[key] = value expressionParseStatementFindNext.__set__ "expressionParseStatementFunctions", expressionParseStatementFunctionsCopy inputCopy = JSON.parse JSON.stringify config.input if config.throws it "throws the expected object", -> (expect -> expressionParseStatementFindNext inputCopy).toThrow config.throws else it "returns the expected object", -> (expect expressionParseStatementFindNext inputCopy).toEqual config.output describe "then", -> beforeEach -> try expressionParseStatementFindNext inputCopy catch ex it "does not modify the input", -> (expect inputCopy).toEqual config.input it "does not modify expressionParseStatementFunctions", -> (expect expressionParseStatementFunctionsCopy).toEqual expressionParseStatementFunctions run description: "nothing" input: [] output: null run description: "non-statement only" input: [ token: "test non-statement a" starts: 25 ends: 37 ] output: null run description: "statement only" input: [ token: "testStatementB" starts: 25 ends: 37 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [] run description: "non-statement then statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "testStatementB" starts: 64 ends: 78 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 ] statement: token: "testStatementB" starts: 64 ends: 78 statementFunction: expressionParseStatementFunctions.testStatementB after: [] run description: "statement then non-statement" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "test non-statement a" starts: 64 ends: 78 ] run description: "non-statement then non-statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 ] output: null run description: "statement then same statement" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "testStatementB" starts: 64 ends: 78 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementB" starts: 64 ends: 78 ] run description: "statement then different statement" input: [ token: "testStatementC" starts: 25 ends: 37 , token: "testStatementB" starts: 64 ends: 78 ] output: before: [] statement: token: "testStatementC" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "testStatementB" starts: 64 ends: 78 ] run description: "multiple non-statements then statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "testStatementB" starts: 89 ends: 103 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 ] statement: token: "testStatementB" starts: 89 ends: 103 statementFunction: expressionParseStatementFunctions.testStatementB after: [] run description: "statement then multiple non-statements" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 ] run description: "multiple non-statements then statement then different statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "testStatementB" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 ] statement: token: "testStatementB" starts: 89 ends: 103 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementC" starts: 143 ends: 156 ] run description: "statement then different statement then multiple non-statements" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "testStatementC" starts: 64 ends: 78 , token: "test non-statement a" starts: 89 ends: 103 , token: "test non-statement b" starts: 143 ends: 156 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementC" starts: 64 ends: 78 , token: "test non-statement a" starts: 89 ends: 103 , token: "test non-statement b" starts: 143 ends: 156 ] run description: "multiple non-statements then statement then same statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "testStatementB" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 ] statement: token: "testStatementB" starts: 89 ends: 103 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementB" starts: 143 ends: 156 ] run description: "statement then same statement then multiple non-statements" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "testStatementB" starts: 64 ends: 78 , token: "test non-statement a" starts: 89 ends: 103 , token: "test non-statement b" starts: 143 ends: 156 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementB" starts: 64 ends: 78 , token: "test non-statement a" starts: 89 ends: 103 , token: "test non-statement b" starts: 143 ends: 156 ] run description: "statement then multiple non-statements then same statement" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 ] run description: "statement then multiple non-statements then different statement" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 ] run description: "multiple non-statements then statement then multiple non-statements then different statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementB" starts: 259 ends: 274 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 ] statement: token: "testStatementC" starts: 143 ends: 156 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementB" starts: 259 ends: 274 ] run description: "statement then multiple non-statements then different statement then multiple non-statements" input: [ token: "testStatementC" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 , token: "test non-statement c" starts: 184 ends: 206 , token: "test non-statement d" starts: 212 ends: 235 , token: "test non-statement e" starts: 259 ends: 274 ] output: before: [] statement: token: "testStatementC" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 , token: "test non-statement c" starts: 184 ends: 206 , token: "test non-statement d" starts: 212 ends: 235 , token: "test non-statement e" starts: 259 ends: 274 ] run description: "multiple non-statements then statement then multiple non-statements then same statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 ] statement: token: "testStatementC" starts: 143 ends: 156 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 ] run description: "statement then multiple non-statements then same statement then multiple non-statements" input: [ token: "testStatementC" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement c" starts: 184 ends: 206 , token: "test non-statement d" starts: 212 ends: 235 , token: "test non-statement e" starts: 259 ends: 274 ] output: before: [] statement: token: "testStatementC" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement c" starts: 184 ends: 206 , token: "test non-statement d" starts: 212 ends: 235 , token: "test non-statement e" starts: 259 ends: 274 ] run description: "multiple non-statements then statement then multiple non-statements then same statement then multiple non-statements" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 ] statement: token: "testStatementC" starts: 143 ends: 156 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] run description: "multiple non-statements then statement then multiple non-statements then different statement then multiple non-statements" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementB" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 ] statement: token: "testStatementC" starts: 143 ends: 156 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementB" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] run description: "inherited properties are ignored" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "constructor" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "constructor" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 ] statement: token: "testStatementC" starts: 259 ends: 274 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ]
196161
describe "expression", -> describe "parse", -> describe "statement", -> describe "findNext", -> rewire = require "rewire" describe "imports", -> expressionParseStatementFindNext = rewire "./findNext" it "expressionParseStatementFunctions", -> (expect expressionParseStatementFindNext.__get__ "expressionParseStatementFunctions").toBe require "./functions" describe "on calling", -> expressionParseStatementFindNext = rewire "./findNext" expressionParseStatementFunctions = testStatementA: -> fail "unexpected call to testStatementA" testStatementB: -> fail "unexpected call to testStatementB" testStatementC: -> fail "unexpected call to testStatementC" testStatementD: -> fail "unexpected call to testStatementD" run = (config) -> describe config.description, -> inputCopy = expressionParseStatementFunctionsCopy = undefined beforeEach -> expressionParseStatementFunctionsCopy = {} for key, value of expressionParseStatementFunctions expressionParseStatementFunctionsCopy[key] = value expressionParseStatementFindNext.__set__ "expressionParseStatementFunctions", expressionParseStatementFunctionsCopy inputCopy = JSON.parse JSON.stringify config.input if config.throws it "throws the expected object", -> (expect -> expressionParseStatementFindNext inputCopy).toThrow config.throws else it "returns the expected object", -> (expect expressionParseStatementFindNext inputCopy).toEqual config.output describe "then", -> beforeEach -> try expressionParseStatementFindNext inputCopy catch ex it "does not modify the input", -> (expect inputCopy).toEqual config.input it "does not modify expressionParseStatementFunctions", -> (expect expressionParseStatementFunctionsCopy).toEqual expressionParseStatementFunctions run description: "nothing" input: [] output: null run description: "non-statement only" input: [ token: "test non-statement a" starts: 25 ends: 37 ] output: null run description: "statement only" input: [ token: "<KEY>Statement<KEY>" starts: 25 ends: 37 ] output: before: [] statement: token: "<KEY>StatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [] run description: "non-statement then statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "testStatementB" starts: 64 ends: 78 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 ] statement: token: "testStatementB" starts: 64 ends: 78 statementFunction: expressionParseStatementFunctions.testStatementB after: [] run description: "statement then non-statement" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "test non-statement a" starts: 64 ends: 78 ] run description: "non-statement then non-statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 ] output: null run description: "statement then same statement" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "testStatementB" starts: 64 ends: 78 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementB" starts: 64 ends: 78 ] run description: "statement then different statement" input: [ token: "testStatementC" starts: 25 ends: 37 , token: "testStatementB" starts: 64 ends: 78 ] output: before: [] statement: token: "testStatementC" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "testStatementB" starts: 64 ends: 78 ] run description: "multiple non-statements then statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "testStatementB" starts: 89 ends: 103 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 ] statement: token: "testStatementB" starts: 89 ends: 103 statementFunction: expressionParseStatementFunctions.testStatementB after: [] run description: "statement then multiple non-statements" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 ] run description: "multiple non-statements then statement then different statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "testStatementB" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 ] statement: token: "testStatementB" starts: 89 ends: 103 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementC" starts: 143 ends: 156 ] run description: "statement then different statement then multiple non-statements" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "testStatementC" starts: 64 ends: 78 , token: "test non-statement a" starts: 89 ends: 103 , token: "test non-statement b" starts: 143 ends: 156 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementC" starts: 64 ends: 78 , token: "test non-statement a" starts: 89 ends: 103 , token: "test non-statement b" starts: 143 ends: 156 ] run description: "multiple non-statements then statement then same statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "testStatementB" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 ] statement: token: "testStatementB" starts: 89 ends: 103 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementB" starts: 143 ends: 156 ] run description: "statement then same statement then multiple non-statements" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "testStatementB" starts: 64 ends: 78 , token: "test non-statement a" starts: 89 ends: 103 , token: "test non-statement b" starts: 143 ends: 156 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementB" starts: 64 ends: 78 , token: "test non-statement a" starts: 89 ends: 103 , token: "test non-statement b" starts: 143 ends: 156 ] run description: "statement then multiple non-statements then same statement" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 ] run description: "statement then multiple non-statements then different statement" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 ] run description: "multiple non-statements then statement then multiple non-statements then different statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementB" starts: 259 ends: 274 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 ] statement: token: "testStatementC" starts: 143 ends: 156 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementB" starts: 259 ends: 274 ] run description: "statement then multiple non-statements then different statement then multiple non-statements" input: [ token: "testStatementC" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 , token: "test non-statement c" starts: 184 ends: 206 , token: "test non-statement d" starts: 212 ends: 235 , token: "test non-statement e" starts: 259 ends: 274 ] output: before: [] statement: token: "testStatementC" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 , token: "test non-statement c" starts: 184 ends: 206 , token: "test non-statement d" starts: 212 ends: 235 , token: "test non-statement e" starts: 259 ends: 274 ] run description: "multiple non-statements then statement then multiple non-statements then same statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 ] statement: token: "testStatementC" starts: 143 ends: 156 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 ] run description: "statement then multiple non-statements then same statement then multiple non-statements" input: [ token: "testStatementC" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement c" starts: 184 ends: 206 , token: "test non-statement d" starts: 212 ends: 235 , token: "test non-statement e" starts: 259 ends: 274 ] output: before: [] statement: token: "testStatementC" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement c" starts: 184 ends: 206 , token: "test non-statement d" starts: 212 ends: 235 , token: "test non-statement e" starts: 259 ends: 274 ] run description: "multiple non-statements then statement then multiple non-statements then same statement then multiple non-statements" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 ] statement: token: "testStatementC" starts: 143 ends: 156 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] run description: "multiple non-statements then statement then multiple non-statements then different statement then multiple non-statements" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementB" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 ] statement: token: "testStatementC" starts: 143 ends: 156 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementB" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] run description: "inherited properties are ignored" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "constructor" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "constructor" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 ] statement: token: "testStatementC" starts: 259 ends: 274 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ]
true
describe "expression", -> describe "parse", -> describe "statement", -> describe "findNext", -> rewire = require "rewire" describe "imports", -> expressionParseStatementFindNext = rewire "./findNext" it "expressionParseStatementFunctions", -> (expect expressionParseStatementFindNext.__get__ "expressionParseStatementFunctions").toBe require "./functions" describe "on calling", -> expressionParseStatementFindNext = rewire "./findNext" expressionParseStatementFunctions = testStatementA: -> fail "unexpected call to testStatementA" testStatementB: -> fail "unexpected call to testStatementB" testStatementC: -> fail "unexpected call to testStatementC" testStatementD: -> fail "unexpected call to testStatementD" run = (config) -> describe config.description, -> inputCopy = expressionParseStatementFunctionsCopy = undefined beforeEach -> expressionParseStatementFunctionsCopy = {} for key, value of expressionParseStatementFunctions expressionParseStatementFunctionsCopy[key] = value expressionParseStatementFindNext.__set__ "expressionParseStatementFunctions", expressionParseStatementFunctionsCopy inputCopy = JSON.parse JSON.stringify config.input if config.throws it "throws the expected object", -> (expect -> expressionParseStatementFindNext inputCopy).toThrow config.throws else it "returns the expected object", -> (expect expressionParseStatementFindNext inputCopy).toEqual config.output describe "then", -> beforeEach -> try expressionParseStatementFindNext inputCopy catch ex it "does not modify the input", -> (expect inputCopy).toEqual config.input it "does not modify expressionParseStatementFunctions", -> (expect expressionParseStatementFunctionsCopy).toEqual expressionParseStatementFunctions run description: "nothing" input: [] output: null run description: "non-statement only" input: [ token: "test non-statement a" starts: 25 ends: 37 ] output: null run description: "statement only" input: [ token: "PI:KEY:<KEY>END_PIStatementPI:KEY:<KEY>END_PI" starts: 25 ends: 37 ] output: before: [] statement: token: "PI:KEY:<KEY>END_PIStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [] run description: "non-statement then statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "testStatementB" starts: 64 ends: 78 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 ] statement: token: "testStatementB" starts: 64 ends: 78 statementFunction: expressionParseStatementFunctions.testStatementB after: [] run description: "statement then non-statement" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "test non-statement a" starts: 64 ends: 78 ] run description: "non-statement then non-statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 ] output: null run description: "statement then same statement" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "testStatementB" starts: 64 ends: 78 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementB" starts: 64 ends: 78 ] run description: "statement then different statement" input: [ token: "testStatementC" starts: 25 ends: 37 , token: "testStatementB" starts: 64 ends: 78 ] output: before: [] statement: token: "testStatementC" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "testStatementB" starts: 64 ends: 78 ] run description: "multiple non-statements then statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "testStatementB" starts: 89 ends: 103 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 ] statement: token: "testStatementB" starts: 89 ends: 103 statementFunction: expressionParseStatementFunctions.testStatementB after: [] run description: "statement then multiple non-statements" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 ] run description: "multiple non-statements then statement then different statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "testStatementB" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 ] statement: token: "testStatementB" starts: 89 ends: 103 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementC" starts: 143 ends: 156 ] run description: "statement then different statement then multiple non-statements" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "testStatementC" starts: 64 ends: 78 , token: "test non-statement a" starts: 89 ends: 103 , token: "test non-statement b" starts: 143 ends: 156 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementC" starts: 64 ends: 78 , token: "test non-statement a" starts: 89 ends: 103 , token: "test non-statement b" starts: 143 ends: 156 ] run description: "multiple non-statements then statement then same statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "testStatementB" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 ] statement: token: "testStatementB" starts: 89 ends: 103 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementB" starts: 143 ends: 156 ] run description: "statement then same statement then multiple non-statements" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "testStatementB" starts: 64 ends: 78 , token: "test non-statement a" starts: 89 ends: 103 , token: "test non-statement b" starts: 143 ends: 156 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "testStatementB" starts: 64 ends: 78 , token: "test non-statement a" starts: 89 ends: 103 , token: "test non-statement b" starts: 143 ends: 156 ] run description: "statement then multiple non-statements then same statement" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 ] run description: "statement then multiple non-statements then different statement" input: [ token: "testStatementB" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 ] output: before: [] statement: token: "testStatementB" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementB after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 ] run description: "multiple non-statements then statement then multiple non-statements then different statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementB" starts: 259 ends: 274 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 ] statement: token: "testStatementC" starts: 143 ends: 156 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementB" starts: 259 ends: 274 ] run description: "statement then multiple non-statements then different statement then multiple non-statements" input: [ token: "testStatementC" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 , token: "test non-statement c" starts: 184 ends: 206 , token: "test non-statement d" starts: 212 ends: 235 , token: "test non-statement e" starts: 259 ends: 274 ] output: before: [] statement: token: "testStatementC" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementB" starts: 143 ends: 156 , token: "test non-statement c" starts: 184 ends: 206 , token: "test non-statement d" starts: 212 ends: 235 , token: "test non-statement e" starts: 259 ends: 274 ] run description: "multiple non-statements then statement then multiple non-statements then same statement" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 ] statement: token: "testStatementC" starts: 143 ends: 156 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 ] run description: "statement then multiple non-statements then same statement then multiple non-statements" input: [ token: "testStatementC" starts: 25 ends: 37 , token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement c" starts: 184 ends: 206 , token: "test non-statement d" starts: 212 ends: 235 , token: "test non-statement e" starts: 259 ends: 274 ] output: before: [] statement: token: "testStatementC" starts: 25 ends: 37 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement a" starts: 64 ends: 78 , token: "test non-statement b" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement c" starts: 184 ends: 206 , token: "test non-statement d" starts: 212 ends: 235 , token: "test non-statement e" starts: 259 ends: 274 ] run description: "multiple non-statements then statement then multiple non-statements then same statement then multiple non-statements" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 ] statement: token: "testStatementC" starts: 143 ends: 156 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] run description: "multiple non-statements then statement then multiple non-statements then different statement then multiple non-statements" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "testStatementC" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementB" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 ] statement: token: "testStatementC" starts: 143 ends: 156 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementB" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] run description: "inherited properties are ignored" input: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "constructor" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 , token: "testStatementC" starts: 259 ends: 274 , token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ] output: before: [ token: "test non-statement a" starts: 25 ends: 37 , token: "test non-statement b" starts: 64 ends: 78 , token: "test non-statement c" starts: 89 ends: 103 , token: "constructor" starts: 143 ends: 156 , token: "test non-statement d" starts: 184 ends: 206 , token: "test non-statement e" starts: 212 ends: 235 ] statement: token: "testStatementC" starts: 259 ends: 274 statementFunction: expressionParseStatementFunctions.testStatementC after: [ token: "test non-statement f" starts: 298 ends: 304 , token: "test non-statement g" starts: 335 ends: 374 , token: "test non-statement h" starts: 437 ends: 475 ]
[ { "context": "f.createUser\n email: vm.email\n password: vm.password\n , (error, authData) ->\n if error\n ", "end": 316, "score": 0.9754844307899475, "start": 305, "tag": "PASSWORD", "value": "vm.password" }, { "context": "assword\n \"email\": vm.email,\n \"password\": vm.password\n , (error, authData) ->\n if (error)\n ", "end": 1002, "score": 0.9865081906318665, "start": 991, "tag": "PASSWORD", "value": "vm.password" } ]
js/navctrl.coffee
AlexStory/thundurus
0
angular.module "thundurus" .controller "NavController", (fbFactory, $scope, $rootScope) -> vm = @ vm.showLog = -> $ '.logform' .toggleClass 'show' return ref = new Firebase 'https://thundurus.firebaseio.com/' vm.register = -> ref.createUser email: vm.email password: vm.password , (error, authData) -> if error switch error.code when "EMAIL_TAKEN" console.log "The new user account cannot be created because the email is already in use." when "INVALID_EMAIL" console.log "The specified email is not a valid email." else console.log "Error creating user:", error else console.log "User account created successfully!" ref.child 'users' .child authData.uid .child 'authData' .set authData vm.login() vm.login = -> ref.authWithPassword "email": vm.email, "password": vm.password , (error, authData) -> if (error) console.log "Login Failed!", error else console.log "Authenticated successfully with payload:", authData $rootScope.user = ref.getAuth() ref.child 'users' .child authData.uid .child 'authData' .set authData $scope.$apply() vm.showLog() vm.findTeams() return vm.getAuth = -> authData = ref.getAuth() if authData $rootScope.user = authData $rootScope.teams = [] return return vm.unauth = -> ref.unauth() $rootScope.user = null vm.showLog() vm.findTeams = -> fbFactory.getTeams() vm.getAuth() return
76877
angular.module "thundurus" .controller "NavController", (fbFactory, $scope, $rootScope) -> vm = @ vm.showLog = -> $ '.logform' .toggleClass 'show' return ref = new Firebase 'https://thundurus.firebaseio.com/' vm.register = -> ref.createUser email: vm.email password: <PASSWORD> , (error, authData) -> if error switch error.code when "EMAIL_TAKEN" console.log "The new user account cannot be created because the email is already in use." when "INVALID_EMAIL" console.log "The specified email is not a valid email." else console.log "Error creating user:", error else console.log "User account created successfully!" ref.child 'users' .child authData.uid .child 'authData' .set authData vm.login() vm.login = -> ref.authWithPassword "email": vm.email, "password": <PASSWORD> , (error, authData) -> if (error) console.log "Login Failed!", error else console.log "Authenticated successfully with payload:", authData $rootScope.user = ref.getAuth() ref.child 'users' .child authData.uid .child 'authData' .set authData $scope.$apply() vm.showLog() vm.findTeams() return vm.getAuth = -> authData = ref.getAuth() if authData $rootScope.user = authData $rootScope.teams = [] return return vm.unauth = -> ref.unauth() $rootScope.user = null vm.showLog() vm.findTeams = -> fbFactory.getTeams() vm.getAuth() return
true
angular.module "thundurus" .controller "NavController", (fbFactory, $scope, $rootScope) -> vm = @ vm.showLog = -> $ '.logform' .toggleClass 'show' return ref = new Firebase 'https://thundurus.firebaseio.com/' vm.register = -> ref.createUser email: vm.email password: PI:PASSWORD:<PASSWORD>END_PI , (error, authData) -> if error switch error.code when "EMAIL_TAKEN" console.log "The new user account cannot be created because the email is already in use." when "INVALID_EMAIL" console.log "The specified email is not a valid email." else console.log "Error creating user:", error else console.log "User account created successfully!" ref.child 'users' .child authData.uid .child 'authData' .set authData vm.login() vm.login = -> ref.authWithPassword "email": vm.email, "password": PI:PASSWORD:<PASSWORD>END_PI , (error, authData) -> if (error) console.log "Login Failed!", error else console.log "Authenticated successfully with payload:", authData $rootScope.user = ref.getAuth() ref.child 'users' .child authData.uid .child 'authData' .set authData $scope.$apply() vm.showLog() vm.findTeams() return vm.getAuth = -> authData = ref.getAuth() if authData $rootScope.user = authData $rootScope.teams = [] return return vm.unauth = -> ref.unauth() $rootScope.user = null vm.showLog() vm.findTeams = -> fbFactory.getTeams() vm.getAuth() return
[ { "context": "\nnikita = require '@nikitajs/core'\n{tags, ssh, scratch, ruby} = require '../te", "end": 28, "score": 0.8301543593406677, "start": 26, "tag": "USERNAME", "value": "js" }, { "context": "}/folder/id_rsa\"\n bits: 2048\n comment: 'nikita'\n , (err, {status}) ->\n status.should.be.", "end": 346, "score": 0.7440185546875, "start": 340, "tag": "NAME", "value": "nikita" }, { "context": "}/folder/id_rsa\"\n bits: 2048\n comment: 'nikita'\n , (err, {status}) ->\n status.should.be.", "end": 516, "score": 0.7592025995254517, "start": 510, "tag": "NAME", "value": "nikita" } ]
packages/tools/test/ssh/keygen.coffee
DanielJohnHarty/node-nikita
1
nikita = require '@nikitajs/core' {tags, ssh, scratch, ruby} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.posix describe 'tools.ssh.keygen', -> they 'a new key', ({ssh}) -> nikita ssh: ssh .tools.ssh.keygen target: "#{scratch}/folder/id_rsa" bits: 2048 comment: 'nikita' , (err, {status}) -> status.should.be.true() unless err .tools.ssh.keygen target: "#{scratch}/folder/id_rsa" bits: 2048 comment: 'nikita' , (err, {status}) -> status.should.be.false() unless err .promise()
108753
nikita = require '@nikitajs/core' {tags, ssh, scratch, ruby} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.posix describe 'tools.ssh.keygen', -> they 'a new key', ({ssh}) -> nikita ssh: ssh .tools.ssh.keygen target: "#{scratch}/folder/id_rsa" bits: 2048 comment: '<NAME>' , (err, {status}) -> status.should.be.true() unless err .tools.ssh.keygen target: "#{scratch}/folder/id_rsa" bits: 2048 comment: '<NAME>' , (err, {status}) -> status.should.be.false() unless err .promise()
true
nikita = require '@nikitajs/core' {tags, ssh, scratch, ruby} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.posix describe 'tools.ssh.keygen', -> they 'a new key', ({ssh}) -> nikita ssh: ssh .tools.ssh.keygen target: "#{scratch}/folder/id_rsa" bits: 2048 comment: 'PI:NAME:<NAME>END_PI' , (err, {status}) -> status.should.be.true() unless err .tools.ssh.keygen target: "#{scratch}/folder/id_rsa" bits: 2048 comment: 'PI:NAME:<NAME>END_PI' , (err, {status}) -> status.should.be.false() unless err .promise()
[ { "context": "en 100 else 100 + lumn\n\n rooms.push\n nome: nome\n larg: larg\n comp: comp\n area: are", "end": 2382, "score": 0.8363430500030518, "start": 2378, "tag": "NAME", "value": "nome" } ]
senai-calculeirar/script.coffee
FelixLuciano/arquivo
0
$ -> $ "input[ type='text' ]" .each -> $ this .attr onKeyup: "this.setAttribute('value', this.value )" value: "" .after "<label for='#{$( this ).attr('id')}' >\ #{$( this ).attr 'floatPlaceholder'}\ </label>" rooms = [] textFile = "Nome | Largura | Comprimento | Area | Perimetro | TUGs | Iluminação\n" tableReload = -> $ "#table .tableLine" .not("#tableHeader") .remove() textFile = "Nome | Largura | Comprimento | &Aacute;rea | Perimetro | TUGs | Iluminação\n" for room in rooms source = " <div class='tableLine'> <div class='tableCell col-xs-3'>#{room.nome}</div> <div class='tableCell col-xs-2'>#{room.area.toFixed(2)}m²</div> <div class='tableCell col-xs-2'>#{room.peri.toFixed(2)}m</div> <div class='tableCell col-xs-2'>#{room.tugs}</div> <div class='tableCell col-xs-2'>#{room.lumn}va</div> <div class='tableCell col-xs-1'><div class='listItem-remove'></div></div> </div>" sufix = "\n" if rooms.indexOf( room ) == rooms.length - 1 sufix = "" textFile += "#{room.nome} | #{room.larg} | #{room.comp} | #{room.area} | #{room.peri} | #{room.tugs} | #{room.lumn + sufix}" $ "#table" .append source console.log textFile read = ( data ) -> data = data.split /\n/ data.splice( 0, 1 ) rooms = [] for index in data room = index.split " | " rooms.push nome: room[0] larg: Number room[1] comp: Number room[2] area: Number room[3] peri: Number room[4] tugs: Number room[5] lumn: Number room[6] $("#mainContent #createMode .actionButton").on "click", -> getNameVal = $("#mainContent.createMode #nome").val() nome = if getNameVal then getNameVal else "Indefinido" larg = Number $("#mainContent.createMode #largura").val().replace ",", "." comp = Number $("#mainContent.createMode #comprimento").val().replace ",", "." area = larg * comp peri = larg * 2 + comp * 2 tugs = 1 + Math.floor( ( area - 6 ) / 5 ) tugs = if tugs < 1 then 1 else 1 + tugs lumn = Math.floor( ( area - 6 ) / 4 ) * 60 lumn = if lumn <= 1 then 100 else 100 + lumn rooms.push nome: nome larg: larg comp: comp area: area peri: peri tugs: tugs lumn: lumn tableReload() $ "#mainContent.createMode #nome, #mainContent.createMode #largura, #mainContent.createMode #comprimento" .val "" .attr value: "" $("body").on "click", ".listItem-remove", -> rooms.splice $( this ).parent().parent().index() - 1, 1 tableReload() if rooms.length == 0 $ "#table" .append " <div class='tableLine'> <div class='tableCell col-xs-12 empty'>Nenhum item para mostrar</div> </div>" $("#tabMenuOpen").on "click", -> $ ".icon", this .toggleClass "opened" exportFile = URL.createObjectURL new Blob [textFile], type: "text/plain" $ "a#save", this .attr "href", exportFile $("#tabMenuOpen #load").on "click", -> $("#tabMenuOpen .icon").trigger "click" $ this .one "change", -> $.ajax type: "GET" url: URL.createObjectURL this.files[0] success: ( data ) -> read data tableReload() $ "#mainContent" .removeClass "editMode" .addClass "createMode" $("#tabMenuOpen #edit").on "click", -> $ "#mainContent" .removeClass "createMode" .addClass "editMode" $ "#mainContent #editMode #textFile" .empty() .prepend textFile $("#mainContent #editMode .actionButton").on "click", -> $ "#mainContent" .removeClass "editMode" .addClass "createMode" read $("#mainContent #editMode #textFile").val() tableReload()
200126
$ -> $ "input[ type='text' ]" .each -> $ this .attr onKeyup: "this.setAttribute('value', this.value )" value: "" .after "<label for='#{$( this ).attr('id')}' >\ #{$( this ).attr 'floatPlaceholder'}\ </label>" rooms = [] textFile = "Nome | Largura | Comprimento | Area | Perimetro | TUGs | Iluminação\n" tableReload = -> $ "#table .tableLine" .not("#tableHeader") .remove() textFile = "Nome | Largura | Comprimento | &Aacute;rea | Perimetro | TUGs | Iluminação\n" for room in rooms source = " <div class='tableLine'> <div class='tableCell col-xs-3'>#{room.nome}</div> <div class='tableCell col-xs-2'>#{room.area.toFixed(2)}m²</div> <div class='tableCell col-xs-2'>#{room.peri.toFixed(2)}m</div> <div class='tableCell col-xs-2'>#{room.tugs}</div> <div class='tableCell col-xs-2'>#{room.lumn}va</div> <div class='tableCell col-xs-1'><div class='listItem-remove'></div></div> </div>" sufix = "\n" if rooms.indexOf( room ) == rooms.length - 1 sufix = "" textFile += "#{room.nome} | #{room.larg} | #{room.comp} | #{room.area} | #{room.peri} | #{room.tugs} | #{room.lumn + sufix}" $ "#table" .append source console.log textFile read = ( data ) -> data = data.split /\n/ data.splice( 0, 1 ) rooms = [] for index in data room = index.split " | " rooms.push nome: room[0] larg: Number room[1] comp: Number room[2] area: Number room[3] peri: Number room[4] tugs: Number room[5] lumn: Number room[6] $("#mainContent #createMode .actionButton").on "click", -> getNameVal = $("#mainContent.createMode #nome").val() nome = if getNameVal then getNameVal else "Indefinido" larg = Number $("#mainContent.createMode #largura").val().replace ",", "." comp = Number $("#mainContent.createMode #comprimento").val().replace ",", "." area = larg * comp peri = larg * 2 + comp * 2 tugs = 1 + Math.floor( ( area - 6 ) / 5 ) tugs = if tugs < 1 then 1 else 1 + tugs lumn = Math.floor( ( area - 6 ) / 4 ) * 60 lumn = if lumn <= 1 then 100 else 100 + lumn rooms.push nome: <NAME> larg: larg comp: comp area: area peri: peri tugs: tugs lumn: lumn tableReload() $ "#mainContent.createMode #nome, #mainContent.createMode #largura, #mainContent.createMode #comprimento" .val "" .attr value: "" $("body").on "click", ".listItem-remove", -> rooms.splice $( this ).parent().parent().index() - 1, 1 tableReload() if rooms.length == 0 $ "#table" .append " <div class='tableLine'> <div class='tableCell col-xs-12 empty'>Nenhum item para mostrar</div> </div>" $("#tabMenuOpen").on "click", -> $ ".icon", this .toggleClass "opened" exportFile = URL.createObjectURL new Blob [textFile], type: "text/plain" $ "a#save", this .attr "href", exportFile $("#tabMenuOpen #load").on "click", -> $("#tabMenuOpen .icon").trigger "click" $ this .one "change", -> $.ajax type: "GET" url: URL.createObjectURL this.files[0] success: ( data ) -> read data tableReload() $ "#mainContent" .removeClass "editMode" .addClass "createMode" $("#tabMenuOpen #edit").on "click", -> $ "#mainContent" .removeClass "createMode" .addClass "editMode" $ "#mainContent #editMode #textFile" .empty() .prepend textFile $("#mainContent #editMode .actionButton").on "click", -> $ "#mainContent" .removeClass "editMode" .addClass "createMode" read $("#mainContent #editMode #textFile").val() tableReload()
true
$ -> $ "input[ type='text' ]" .each -> $ this .attr onKeyup: "this.setAttribute('value', this.value )" value: "" .after "<label for='#{$( this ).attr('id')}' >\ #{$( this ).attr 'floatPlaceholder'}\ </label>" rooms = [] textFile = "Nome | Largura | Comprimento | Area | Perimetro | TUGs | Iluminação\n" tableReload = -> $ "#table .tableLine" .not("#tableHeader") .remove() textFile = "Nome | Largura | Comprimento | &Aacute;rea | Perimetro | TUGs | Iluminação\n" for room in rooms source = " <div class='tableLine'> <div class='tableCell col-xs-3'>#{room.nome}</div> <div class='tableCell col-xs-2'>#{room.area.toFixed(2)}m²</div> <div class='tableCell col-xs-2'>#{room.peri.toFixed(2)}m</div> <div class='tableCell col-xs-2'>#{room.tugs}</div> <div class='tableCell col-xs-2'>#{room.lumn}va</div> <div class='tableCell col-xs-1'><div class='listItem-remove'></div></div> </div>" sufix = "\n" if rooms.indexOf( room ) == rooms.length - 1 sufix = "" textFile += "#{room.nome} | #{room.larg} | #{room.comp} | #{room.area} | #{room.peri} | #{room.tugs} | #{room.lumn + sufix}" $ "#table" .append source console.log textFile read = ( data ) -> data = data.split /\n/ data.splice( 0, 1 ) rooms = [] for index in data room = index.split " | " rooms.push nome: room[0] larg: Number room[1] comp: Number room[2] area: Number room[3] peri: Number room[4] tugs: Number room[5] lumn: Number room[6] $("#mainContent #createMode .actionButton").on "click", -> getNameVal = $("#mainContent.createMode #nome").val() nome = if getNameVal then getNameVal else "Indefinido" larg = Number $("#mainContent.createMode #largura").val().replace ",", "." comp = Number $("#mainContent.createMode #comprimento").val().replace ",", "." area = larg * comp peri = larg * 2 + comp * 2 tugs = 1 + Math.floor( ( area - 6 ) / 5 ) tugs = if tugs < 1 then 1 else 1 + tugs lumn = Math.floor( ( area - 6 ) / 4 ) * 60 lumn = if lumn <= 1 then 100 else 100 + lumn rooms.push nome: PI:NAME:<NAME>END_PI larg: larg comp: comp area: area peri: peri tugs: tugs lumn: lumn tableReload() $ "#mainContent.createMode #nome, #mainContent.createMode #largura, #mainContent.createMode #comprimento" .val "" .attr value: "" $("body").on "click", ".listItem-remove", -> rooms.splice $( this ).parent().parent().index() - 1, 1 tableReload() if rooms.length == 0 $ "#table" .append " <div class='tableLine'> <div class='tableCell col-xs-12 empty'>Nenhum item para mostrar</div> </div>" $("#tabMenuOpen").on "click", -> $ ".icon", this .toggleClass "opened" exportFile = URL.createObjectURL new Blob [textFile], type: "text/plain" $ "a#save", this .attr "href", exportFile $("#tabMenuOpen #load").on "click", -> $("#tabMenuOpen .icon").trigger "click" $ this .one "change", -> $.ajax type: "GET" url: URL.createObjectURL this.files[0] success: ( data ) -> read data tableReload() $ "#mainContent" .removeClass "editMode" .addClass "createMode" $("#tabMenuOpen #edit").on "click", -> $ "#mainContent" .removeClass "createMode" .addClass "editMode" $ "#mainContent #editMode #textFile" .empty() .prepend textFile $("#mainContent #editMode .actionButton").on "click", -> $ "#mainContent" .removeClass "editMode" .addClass "createMode" read $("#mainContent #editMode #textFile").val() tableReload()
[ { "context": "me format, format should be in the form of email : user@sample.com'\n\n\n LANG\n },{\n init:(elem, o", "end": 2058, "score": 0.9999216794967651, "start": 2043, "tag": "EMAIL", "value": "user@sample.com" } ]
modules/config_edit_item/config_edit_item.coffee
signonsridhar/sridhar_hbs
0
define(['bases/control', '_', 'modules/dt_dialog/dt_dialog', 'modules/unassigned_bundle_selector/unassigned_bundle_selector', 'modules/config_edit_item/group/config_edit_item_group' 'modules/config_edit_item/line/config_edit_item_line' 'modules/add_to_call_group/add_to_call_group', 'models/user/user', 'models/bundle/bundle', 'css! modules/config_edit_item/config_edit_item' ], (BaseControl,_, DTDialog, UnassignedBundleSelector, ConfigEditItemGroup, ConfigEditItemLine, AddToCallGroup, User, Bundle)-> BaseControl.extend({ LANG: (controller)-> LANG = { errors:{ first_name:{} last_name:{} email:{} } } LANG.errors.first_name[VALID.ERROR.SIZE] = 'first name must be 2 to 40 characters' LANG.errors.first_name[VALID.ERROR.REQUIRED] = 'first name is required' LANG.errors.first_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.last_name[VALID.ERROR.SIZE] = 'last name must be 2 to 40 characters' LANG.errors.last_name[VALID.ERROR.REQUIRED] = 'last name is required' LANG.errors.last_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.email[VALID.ERROR.REQUIRED] = 'email is required' LANG.errors.email[VALID.ERROR.SIZE] = 'must be a valid email address with 3 to 70 characters' LANG.errors.email[VALID.ERROR.FORMAT] = 'must be alphanumeric, must have @ and period, must be 3 to 70 chars, and may contain following special chars: - . _ +' LANG.errors.email[VALID.ERROR.UNIQUE] = 'this email already exists' LANG.errors.email[VALID.ERROR.INVALID] = 'Invalid user name format, format should be in the form of email : user@sample.com' LANG },{ init:(elem, options)-> this.item = item = this.options.item ###this.setup_viewmodel({ first_name: '' last_name: '' email: '' })### if item instanceof User console.log('rendering user', item) directory = this.options.directory this.unassigned_bundles = unassigned_bundles = directory.get_unassigned_bundles() if (unassigned_bundles and unassigned_bundles.length) options.item.attr('show_add_line', true) #TODO HACK to avoid email validation on render, add email on platform changes to API options.item.set_validated_attrs(['first_name', 'last_name']) this.render('config_edit_item/config_edit_item_user', { item: options.item, renderer:(elem, index, bundle_elem)=> new ConfigEditItemLine(elem, {item: bundle_elem, directory: this.options.directory, tenant_id: this.options.tenant_id}) }) this.bind_view(options.item) this.set_validity(false) else if item instanceof Bundle directory = this.options.directory options.item.attr('show_add_line', false) options.item.attr('show_unassign_line', false) user = options.user = new User() this.render('config_edit_item/config_edit_item_bundle', {user: user}) this.bind_view(user) new ConfigEditItemLine(this.element.find('.bundle_js'), {item: this.options.item, directory: this.options.directory, tenant_id: this.options.tenant_id}) this.set_validity(false) else new ConfigEditItemGroup(this.element, {item: options.item}) #this.render('config_edit_item/config_edit_item_group', {item: options.item}) #user attribute changes '{item} first_name change':()-> this.element.find('.save_user_info_js').show() '{item} last_name change':()-> this.element.find('.save_user_info_js').show() '{item} email change':()-> this.element.find('.save_user_info_js').show() #unassign user bundle 'li.bundle_js .unassign_js click':($el)-> idx = $el.closest('.bundle_js').data('idx') this.viewmodel.attr('unassign', idx + '_' + _.uniqueId()) '{viewmodel} unassign change':()-> unassign_idx = this.viewmodel.attr('unassign').split('_')[0] this.show_warning(unassign_idx) this.disable_other_items_except(unassign_idx) #remove bundle '.item_warning .confirm_warning_js click':($el)-> idx = $el.data('idx') spliced = this.options.item.bundles.splice(idx, 1) if (spliced and spliced[0]) this.options.item.remove_bundle_for_user(spliced[0].bundle_id).done(()=> console.log(' unassigned item') this.options.directory.load_all(this.options.tenant_id) ).fail(()=> #TODO remove this.options.directory.load_all(this.options.tenant_id) ) '.warning_container .reject_warning_js click':(e)-> this.remove_warning() show_warning:(idx)-> $warning_div = this.get_raw_html('config_edit_item/warning', {idx:idx}) this.get_item_elements().eq(idx).find('.row_js').append($warning_div) get_item_elements:()-> # user's line elements this.element.find('li') remove_warning:()-> this.get_item_elements().find('.list_item_overlay').remove() disable_other_items_except:(except)-> #put an invisible overlay this._overlay_disable_class = _.uniqueId('overlay_') overlay_html = "<div class='#{this._overlay_disable_class} list_item_overlay item_disabled'></div>" elements = this.get_item_elements() $do_not_overlay = $([]) except =[except] $.each(except,(index, each_except)-> $do_not_elem = elements.eq(parseInt(each_except)) $do_not_overlay = $do_not_overlay.add($do_not_elem) ) elements = elements.not($do_not_overlay).find('.row_js').append(overlay_html) '.save_user_info_js click':($el,e)-> e.stopPropagation() this.item.set_name() this.item.set_email() '.add_user_to_bundle_js click':($el,e)-> e.stopPropagation() user_request = { first_name: this.options.user.attr('first_name') last_name: this.options.user.attr('last_name') email: this.options.user.attr('email') } this.item.add_user_to_bundle(user_request).done(()=> this.options.directory.load_all(this.options.tenant_id) ).fail(()=> this.options.directory.load_all(this.options.tenant_id) ) '.assign_js click':($el)-> unless this.assign_bundle this.assign_bundle = new UnassignedBundleSelector($('<div class="unassigned_bundle_selector_container_js"></div>'), {'bundles':this.unassigned_bundles}) this.assign_bundle_dialog = new DTDialog(this.element.find('.unassign_bundle_container_js'), { content: this.assign_bundle.element, settings: { height: 237, width: 400, autoOpen: false, modal: true, buttons:{ "Select Bundle": => this.select_bundle_button() Cancel: => this.cancel_button() }, open: ()-> $(this).parent().find('button:contains("Select Bundle")').addClass("select_bundle") $(this).parent().find('button:contains("Cancel")').addClass("cancel_select_bundle") } }) this.assign_bundle_dialog.show_hide_title(true) this.assign_bundle_dialog.open_dialog() this.assign_bundle.refresh() select_bundle_button:()-> bundle = this.assign_bundle.get_selected() bundle_ids = [] bundle_ids.push(bundle.bundle_id) this.item.add_bundle_for_user(bundle_ids).done(()=> this.options.directory.load_all(this.options.tenant_id) ).fail(()=> #TODO remove this.options.directory.load_all(this.options.tenant_id) ) this.assign_bundle_dialog.close_dialog() cancel_button:() -> this.assign_bundle_dialog.close_dialog() '{item.valid} change':()-> this.set_validity(this.options.item.valid()) validate: ()-> this.options.item.validate() }) )
72118
define(['bases/control', '_', 'modules/dt_dialog/dt_dialog', 'modules/unassigned_bundle_selector/unassigned_bundle_selector', 'modules/config_edit_item/group/config_edit_item_group' 'modules/config_edit_item/line/config_edit_item_line' 'modules/add_to_call_group/add_to_call_group', 'models/user/user', 'models/bundle/bundle', 'css! modules/config_edit_item/config_edit_item' ], (BaseControl,_, DTDialog, UnassignedBundleSelector, ConfigEditItemGroup, ConfigEditItemLine, AddToCallGroup, User, Bundle)-> BaseControl.extend({ LANG: (controller)-> LANG = { errors:{ first_name:{} last_name:{} email:{} } } LANG.errors.first_name[VALID.ERROR.SIZE] = 'first name must be 2 to 40 characters' LANG.errors.first_name[VALID.ERROR.REQUIRED] = 'first name is required' LANG.errors.first_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.last_name[VALID.ERROR.SIZE] = 'last name must be 2 to 40 characters' LANG.errors.last_name[VALID.ERROR.REQUIRED] = 'last name is required' LANG.errors.last_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.email[VALID.ERROR.REQUIRED] = 'email is required' LANG.errors.email[VALID.ERROR.SIZE] = 'must be a valid email address with 3 to 70 characters' LANG.errors.email[VALID.ERROR.FORMAT] = 'must be alphanumeric, must have @ and period, must be 3 to 70 chars, and may contain following special chars: - . _ +' LANG.errors.email[VALID.ERROR.UNIQUE] = 'this email already exists' LANG.errors.email[VALID.ERROR.INVALID] = 'Invalid user name format, format should be in the form of email : <EMAIL>' LANG },{ init:(elem, options)-> this.item = item = this.options.item ###this.setup_viewmodel({ first_name: '' last_name: '' email: '' })### if item instanceof User console.log('rendering user', item) directory = this.options.directory this.unassigned_bundles = unassigned_bundles = directory.get_unassigned_bundles() if (unassigned_bundles and unassigned_bundles.length) options.item.attr('show_add_line', true) #TODO HACK to avoid email validation on render, add email on platform changes to API options.item.set_validated_attrs(['first_name', 'last_name']) this.render('config_edit_item/config_edit_item_user', { item: options.item, renderer:(elem, index, bundle_elem)=> new ConfigEditItemLine(elem, {item: bundle_elem, directory: this.options.directory, tenant_id: this.options.tenant_id}) }) this.bind_view(options.item) this.set_validity(false) else if item instanceof Bundle directory = this.options.directory options.item.attr('show_add_line', false) options.item.attr('show_unassign_line', false) user = options.user = new User() this.render('config_edit_item/config_edit_item_bundle', {user: user}) this.bind_view(user) new ConfigEditItemLine(this.element.find('.bundle_js'), {item: this.options.item, directory: this.options.directory, tenant_id: this.options.tenant_id}) this.set_validity(false) else new ConfigEditItemGroup(this.element, {item: options.item}) #this.render('config_edit_item/config_edit_item_group', {item: options.item}) #user attribute changes '{item} first_name change':()-> this.element.find('.save_user_info_js').show() '{item} last_name change':()-> this.element.find('.save_user_info_js').show() '{item} email change':()-> this.element.find('.save_user_info_js').show() #unassign user bundle 'li.bundle_js .unassign_js click':($el)-> idx = $el.closest('.bundle_js').data('idx') this.viewmodel.attr('unassign', idx + '_' + _.uniqueId()) '{viewmodel} unassign change':()-> unassign_idx = this.viewmodel.attr('unassign').split('_')[0] this.show_warning(unassign_idx) this.disable_other_items_except(unassign_idx) #remove bundle '.item_warning .confirm_warning_js click':($el)-> idx = $el.data('idx') spliced = this.options.item.bundles.splice(idx, 1) if (spliced and spliced[0]) this.options.item.remove_bundle_for_user(spliced[0].bundle_id).done(()=> console.log(' unassigned item') this.options.directory.load_all(this.options.tenant_id) ).fail(()=> #TODO remove this.options.directory.load_all(this.options.tenant_id) ) '.warning_container .reject_warning_js click':(e)-> this.remove_warning() show_warning:(idx)-> $warning_div = this.get_raw_html('config_edit_item/warning', {idx:idx}) this.get_item_elements().eq(idx).find('.row_js').append($warning_div) get_item_elements:()-> # user's line elements this.element.find('li') remove_warning:()-> this.get_item_elements().find('.list_item_overlay').remove() disable_other_items_except:(except)-> #put an invisible overlay this._overlay_disable_class = _.uniqueId('overlay_') overlay_html = "<div class='#{this._overlay_disable_class} list_item_overlay item_disabled'></div>" elements = this.get_item_elements() $do_not_overlay = $([]) except =[except] $.each(except,(index, each_except)-> $do_not_elem = elements.eq(parseInt(each_except)) $do_not_overlay = $do_not_overlay.add($do_not_elem) ) elements = elements.not($do_not_overlay).find('.row_js').append(overlay_html) '.save_user_info_js click':($el,e)-> e.stopPropagation() this.item.set_name() this.item.set_email() '.add_user_to_bundle_js click':($el,e)-> e.stopPropagation() user_request = { first_name: this.options.user.attr('first_name') last_name: this.options.user.attr('last_name') email: this.options.user.attr('email') } this.item.add_user_to_bundle(user_request).done(()=> this.options.directory.load_all(this.options.tenant_id) ).fail(()=> this.options.directory.load_all(this.options.tenant_id) ) '.assign_js click':($el)-> unless this.assign_bundle this.assign_bundle = new UnassignedBundleSelector($('<div class="unassigned_bundle_selector_container_js"></div>'), {'bundles':this.unassigned_bundles}) this.assign_bundle_dialog = new DTDialog(this.element.find('.unassign_bundle_container_js'), { content: this.assign_bundle.element, settings: { height: 237, width: 400, autoOpen: false, modal: true, buttons:{ "Select Bundle": => this.select_bundle_button() Cancel: => this.cancel_button() }, open: ()-> $(this).parent().find('button:contains("Select Bundle")').addClass("select_bundle") $(this).parent().find('button:contains("Cancel")').addClass("cancel_select_bundle") } }) this.assign_bundle_dialog.show_hide_title(true) this.assign_bundle_dialog.open_dialog() this.assign_bundle.refresh() select_bundle_button:()-> bundle = this.assign_bundle.get_selected() bundle_ids = [] bundle_ids.push(bundle.bundle_id) this.item.add_bundle_for_user(bundle_ids).done(()=> this.options.directory.load_all(this.options.tenant_id) ).fail(()=> #TODO remove this.options.directory.load_all(this.options.tenant_id) ) this.assign_bundle_dialog.close_dialog() cancel_button:() -> this.assign_bundle_dialog.close_dialog() '{item.valid} change':()-> this.set_validity(this.options.item.valid()) validate: ()-> this.options.item.validate() }) )
true
define(['bases/control', '_', 'modules/dt_dialog/dt_dialog', 'modules/unassigned_bundle_selector/unassigned_bundle_selector', 'modules/config_edit_item/group/config_edit_item_group' 'modules/config_edit_item/line/config_edit_item_line' 'modules/add_to_call_group/add_to_call_group', 'models/user/user', 'models/bundle/bundle', 'css! modules/config_edit_item/config_edit_item' ], (BaseControl,_, DTDialog, UnassignedBundleSelector, ConfigEditItemGroup, ConfigEditItemLine, AddToCallGroup, User, Bundle)-> BaseControl.extend({ LANG: (controller)-> LANG = { errors:{ first_name:{} last_name:{} email:{} } } LANG.errors.first_name[VALID.ERROR.SIZE] = 'first name must be 2 to 40 characters' LANG.errors.first_name[VALID.ERROR.REQUIRED] = 'first name is required' LANG.errors.first_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.last_name[VALID.ERROR.SIZE] = 'last name must be 2 to 40 characters' LANG.errors.last_name[VALID.ERROR.REQUIRED] = 'last name is required' LANG.errors.last_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.email[VALID.ERROR.REQUIRED] = 'email is required' LANG.errors.email[VALID.ERROR.SIZE] = 'must be a valid email address with 3 to 70 characters' LANG.errors.email[VALID.ERROR.FORMAT] = 'must be alphanumeric, must have @ and period, must be 3 to 70 chars, and may contain following special chars: - . _ +' LANG.errors.email[VALID.ERROR.UNIQUE] = 'this email already exists' LANG.errors.email[VALID.ERROR.INVALID] = 'Invalid user name format, format should be in the form of email : PI:EMAIL:<EMAIL>END_PI' LANG },{ init:(elem, options)-> this.item = item = this.options.item ###this.setup_viewmodel({ first_name: '' last_name: '' email: '' })### if item instanceof User console.log('rendering user', item) directory = this.options.directory this.unassigned_bundles = unassigned_bundles = directory.get_unassigned_bundles() if (unassigned_bundles and unassigned_bundles.length) options.item.attr('show_add_line', true) #TODO HACK to avoid email validation on render, add email on platform changes to API options.item.set_validated_attrs(['first_name', 'last_name']) this.render('config_edit_item/config_edit_item_user', { item: options.item, renderer:(elem, index, bundle_elem)=> new ConfigEditItemLine(elem, {item: bundle_elem, directory: this.options.directory, tenant_id: this.options.tenant_id}) }) this.bind_view(options.item) this.set_validity(false) else if item instanceof Bundle directory = this.options.directory options.item.attr('show_add_line', false) options.item.attr('show_unassign_line', false) user = options.user = new User() this.render('config_edit_item/config_edit_item_bundle', {user: user}) this.bind_view(user) new ConfigEditItemLine(this.element.find('.bundle_js'), {item: this.options.item, directory: this.options.directory, tenant_id: this.options.tenant_id}) this.set_validity(false) else new ConfigEditItemGroup(this.element, {item: options.item}) #this.render('config_edit_item/config_edit_item_group', {item: options.item}) #user attribute changes '{item} first_name change':()-> this.element.find('.save_user_info_js').show() '{item} last_name change':()-> this.element.find('.save_user_info_js').show() '{item} email change':()-> this.element.find('.save_user_info_js').show() #unassign user bundle 'li.bundle_js .unassign_js click':($el)-> idx = $el.closest('.bundle_js').data('idx') this.viewmodel.attr('unassign', idx + '_' + _.uniqueId()) '{viewmodel} unassign change':()-> unassign_idx = this.viewmodel.attr('unassign').split('_')[0] this.show_warning(unassign_idx) this.disable_other_items_except(unassign_idx) #remove bundle '.item_warning .confirm_warning_js click':($el)-> idx = $el.data('idx') spliced = this.options.item.bundles.splice(idx, 1) if (spliced and spliced[0]) this.options.item.remove_bundle_for_user(spliced[0].bundle_id).done(()=> console.log(' unassigned item') this.options.directory.load_all(this.options.tenant_id) ).fail(()=> #TODO remove this.options.directory.load_all(this.options.tenant_id) ) '.warning_container .reject_warning_js click':(e)-> this.remove_warning() show_warning:(idx)-> $warning_div = this.get_raw_html('config_edit_item/warning', {idx:idx}) this.get_item_elements().eq(idx).find('.row_js').append($warning_div) get_item_elements:()-> # user's line elements this.element.find('li') remove_warning:()-> this.get_item_elements().find('.list_item_overlay').remove() disable_other_items_except:(except)-> #put an invisible overlay this._overlay_disable_class = _.uniqueId('overlay_') overlay_html = "<div class='#{this._overlay_disable_class} list_item_overlay item_disabled'></div>" elements = this.get_item_elements() $do_not_overlay = $([]) except =[except] $.each(except,(index, each_except)-> $do_not_elem = elements.eq(parseInt(each_except)) $do_not_overlay = $do_not_overlay.add($do_not_elem) ) elements = elements.not($do_not_overlay).find('.row_js').append(overlay_html) '.save_user_info_js click':($el,e)-> e.stopPropagation() this.item.set_name() this.item.set_email() '.add_user_to_bundle_js click':($el,e)-> e.stopPropagation() user_request = { first_name: this.options.user.attr('first_name') last_name: this.options.user.attr('last_name') email: this.options.user.attr('email') } this.item.add_user_to_bundle(user_request).done(()=> this.options.directory.load_all(this.options.tenant_id) ).fail(()=> this.options.directory.load_all(this.options.tenant_id) ) '.assign_js click':($el)-> unless this.assign_bundle this.assign_bundle = new UnassignedBundleSelector($('<div class="unassigned_bundle_selector_container_js"></div>'), {'bundles':this.unassigned_bundles}) this.assign_bundle_dialog = new DTDialog(this.element.find('.unassign_bundle_container_js'), { content: this.assign_bundle.element, settings: { height: 237, width: 400, autoOpen: false, modal: true, buttons:{ "Select Bundle": => this.select_bundle_button() Cancel: => this.cancel_button() }, open: ()-> $(this).parent().find('button:contains("Select Bundle")').addClass("select_bundle") $(this).parent().find('button:contains("Cancel")').addClass("cancel_select_bundle") } }) this.assign_bundle_dialog.show_hide_title(true) this.assign_bundle_dialog.open_dialog() this.assign_bundle.refresh() select_bundle_button:()-> bundle = this.assign_bundle.get_selected() bundle_ids = [] bundle_ids.push(bundle.bundle_id) this.item.add_bundle_for_user(bundle_ids).done(()=> this.options.directory.load_all(this.options.tenant_id) ).fail(()=> #TODO remove this.options.directory.load_all(this.options.tenant_id) ) this.assign_bundle_dialog.close_dialog() cancel_button:() -> this.assign_bundle_dialog.close_dialog() '{item.valid} change':()-> this.set_validity(this.options.item.valid()) validate: ()-> this.options.item.validate() }) )
[ { "context": "ttp://ralphcrisostomo.net\n *\n * Copyright (c) 2014 Ralph Crisostomo\n * Licensed under the MIT license.\n###\n\n'use stri", "end": 100, "score": 0.9998898506164551, "start": 84, "tag": "NAME", "value": "Ralph Crisostomo" } ]
template.coffee
ralphcrisostomo/grunt-init-simple-web
0
### * grunt-init-simple-web * http://ralphcrisostomo.net * * Copyright (c) 2014 Ralph Crisostomo * Licensed under the MIT license. ### 'use strict' # Basic template description. exports.description = 'Create a Node.js module including Nodeunit unit tests.' # Template-specific notes to be displayed before question prompts. exports.notes = '_Project name_ shouldn\'t contain "node" or "js" and should ' + 'be a unique ID not already in use at search.npmjs.org.' # Template-specific notes to be displayed after question prompts. exports.after = 'You should now install project dependencies with _npm ' + 'install_. After that you may execute project tasks with _grunt_. For ' + 'more information about installing and configuring Grunt please see ' + 'the Getting Started guide:' + '\n\n' + 'http:#gruntjs.com/getting-started' # Any existing file or directory matching this wildcard will cause a warning. exports.warnOn = '*' # The actual init template. exports.template = (grunt, init, done) -> # Underscore utilities _ = grunt.util._ init.process {type: 'node'}, [ # Prompt for these values. init.prompt('name') init.prompt('description') init.prompt('version') init.prompt('repository') init.prompt('homepage') init.prompt('bugs') init.prompt('licenses') init.prompt('author_name') init.prompt('author_email') init.prompt('author_url') init.prompt('node_version', '>= 0.12.0') ], (err, props) -> props.keywords = [] props.preferGlobal = true props.devDependencies = "browser-sync": "^2.7.1" "browserify": "^10.2.0" "coffee-script": "^1.9.2" "coffeeify": "^1.1.0" "gulp": "^3.8.11" "gulp-buster": "^1.0.0" "gulp-clean": "^0.3.1" "gulp-compass": "^2.0.4" "gulp-minify-css": "^1.1.1" "gulp-rename": "^1.2.2" "gulp-sourcemaps": "^1.5.2" "gulp-uglify": "^1.2.0" "handlebars": "^3.0.3" "hbsfy": "^2.2.1" "require-dir": "^0.3.0" "run-sequence": "^1.1.0" "vinyl-buffer": "^1.0.0" "vinyl-source-stream": "^1.1.0" # Files to copy (and process). files = init.filesToCopy(props) # Add properly-named license files. init.addLicenseFiles(files, props.licenses) # Actually copy (and process) files. init.copyAndProcess(files, props) # Generate package.json file. init.writePackageJSON 'package.json', props, (pkg, props) -> pkg['browserify'] = transform : ['coffeeify','hbsfy'] pkg['scripts'] = test : 'gulp test' pkg # All done! done()
50508
### * grunt-init-simple-web * http://ralphcrisostomo.net * * Copyright (c) 2014 <NAME> * Licensed under the MIT license. ### 'use strict' # Basic template description. exports.description = 'Create a Node.js module including Nodeunit unit tests.' # Template-specific notes to be displayed before question prompts. exports.notes = '_Project name_ shouldn\'t contain "node" or "js" and should ' + 'be a unique ID not already in use at search.npmjs.org.' # Template-specific notes to be displayed after question prompts. exports.after = 'You should now install project dependencies with _npm ' + 'install_. After that you may execute project tasks with _grunt_. For ' + 'more information about installing and configuring Grunt please see ' + 'the Getting Started guide:' + '\n\n' + 'http:#gruntjs.com/getting-started' # Any existing file or directory matching this wildcard will cause a warning. exports.warnOn = '*' # The actual init template. exports.template = (grunt, init, done) -> # Underscore utilities _ = grunt.util._ init.process {type: 'node'}, [ # Prompt for these values. init.prompt('name') init.prompt('description') init.prompt('version') init.prompt('repository') init.prompt('homepage') init.prompt('bugs') init.prompt('licenses') init.prompt('author_name') init.prompt('author_email') init.prompt('author_url') init.prompt('node_version', '>= 0.12.0') ], (err, props) -> props.keywords = [] props.preferGlobal = true props.devDependencies = "browser-sync": "^2.7.1" "browserify": "^10.2.0" "coffee-script": "^1.9.2" "coffeeify": "^1.1.0" "gulp": "^3.8.11" "gulp-buster": "^1.0.0" "gulp-clean": "^0.3.1" "gulp-compass": "^2.0.4" "gulp-minify-css": "^1.1.1" "gulp-rename": "^1.2.2" "gulp-sourcemaps": "^1.5.2" "gulp-uglify": "^1.2.0" "handlebars": "^3.0.3" "hbsfy": "^2.2.1" "require-dir": "^0.3.0" "run-sequence": "^1.1.0" "vinyl-buffer": "^1.0.0" "vinyl-source-stream": "^1.1.0" # Files to copy (and process). files = init.filesToCopy(props) # Add properly-named license files. init.addLicenseFiles(files, props.licenses) # Actually copy (and process) files. init.copyAndProcess(files, props) # Generate package.json file. init.writePackageJSON 'package.json', props, (pkg, props) -> pkg['browserify'] = transform : ['coffeeify','hbsfy'] pkg['scripts'] = test : 'gulp test' pkg # All done! done()
true
### * grunt-init-simple-web * http://ralphcrisostomo.net * * Copyright (c) 2014 PI:NAME:<NAME>END_PI * Licensed under the MIT license. ### 'use strict' # Basic template description. exports.description = 'Create a Node.js module including Nodeunit unit tests.' # Template-specific notes to be displayed before question prompts. exports.notes = '_Project name_ shouldn\'t contain "node" or "js" and should ' + 'be a unique ID not already in use at search.npmjs.org.' # Template-specific notes to be displayed after question prompts. exports.after = 'You should now install project dependencies with _npm ' + 'install_. After that you may execute project tasks with _grunt_. For ' + 'more information about installing and configuring Grunt please see ' + 'the Getting Started guide:' + '\n\n' + 'http:#gruntjs.com/getting-started' # Any existing file or directory matching this wildcard will cause a warning. exports.warnOn = '*' # The actual init template. exports.template = (grunt, init, done) -> # Underscore utilities _ = grunt.util._ init.process {type: 'node'}, [ # Prompt for these values. init.prompt('name') init.prompt('description') init.prompt('version') init.prompt('repository') init.prompt('homepage') init.prompt('bugs') init.prompt('licenses') init.prompt('author_name') init.prompt('author_email') init.prompt('author_url') init.prompt('node_version', '>= 0.12.0') ], (err, props) -> props.keywords = [] props.preferGlobal = true props.devDependencies = "browser-sync": "^2.7.1" "browserify": "^10.2.0" "coffee-script": "^1.9.2" "coffeeify": "^1.1.0" "gulp": "^3.8.11" "gulp-buster": "^1.0.0" "gulp-clean": "^0.3.1" "gulp-compass": "^2.0.4" "gulp-minify-css": "^1.1.1" "gulp-rename": "^1.2.2" "gulp-sourcemaps": "^1.5.2" "gulp-uglify": "^1.2.0" "handlebars": "^3.0.3" "hbsfy": "^2.2.1" "require-dir": "^0.3.0" "run-sequence": "^1.1.0" "vinyl-buffer": "^1.0.0" "vinyl-source-stream": "^1.1.0" # Files to copy (and process). files = init.filesToCopy(props) # Add properly-named license files. init.addLicenseFiles(files, props.licenses) # Actually copy (and process) files. init.copyAndProcess(files, props) # Generate package.json file. init.writePackageJSON 'package.json', props, (pkg, props) -> pkg['browserify'] = transform : ['coffeeify','hbsfy'] pkg['scripts'] = test : 'gulp test' pkg # All done! done()
[ { "context": "lback', (done) ->\n flat = new Flat({name: 'Bob'})\n flat.save null, {\n success: (", "end": 1891, "score": 0.9992088675498962, "start": 1888, "tag": "NAME", "value": "Bob" }, { "context": "l')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n done()\n ", "end": 2257, "score": 0.9997788667678833, "start": 2254, "tag": "NAME", "value": "Bob" }, { "context": "lback', (done) ->\n flat = new Flat({name: 'Bob'})\n flat.save {}, {\n success: (mo", "end": 2478, "score": 0.9998067021369934, "start": 2475, "tag": "NAME", "value": "Bob" }, { "context": "l')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n done()\n ", "end": 2842, "score": 0.9997773766517639, "start": 2839, "tag": "NAME", "value": "Bob" }, { "context": " flat = new Flat()\n flat.save 'name', 'Bob', {\n success: (model) ->\n ass", "end": 3089, "score": 0.9998098015785217, "start": 3086, "tag": "NAME", "value": "Bob" }, { "context": "l')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n done()\n ", "end": 3430, "score": 0.9998194575309753, "start": 3427, "tag": "NAME", "value": "Bob" }, { "context": "lback', (done) ->\n flat = new Flat({name: 'Bob'})\n flat.save (err, model) ->\n as", "end": 3647, "score": 0.9997827410697937, "start": 3644, "tag": "NAME", "value": "Bob" }, { "context": "del')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n\n flat.destroy {\n ", "end": 4037, "score": 0.9998243451118469, "start": 4034, "tag": "NAME", "value": "Bob" }, { "context": "lback', (done) ->\n flat = new Flat({name: 'Bob'})\n flat.save (err, model) ->\n as", "end": 4468, "score": 0.9997959733009338, "start": 4465, "tag": "NAME", "value": "Bob" }, { "context": "l')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n done()\n ", "end": 4820, "score": 0.9998223185539246, "start": 4817, "tag": "NAME", "value": "Bob" }, { "context": "lback', (done) ->\n flat = new Flat({name: 'Bob'})\n flat.save (err, model) ->\n as", "end": 5047, "score": 0.9998012185096741, "start": 5044, "tag": "NAME", "value": "Bob" }, { "context": "l')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n done()\n ", "end": 5427, "score": 0.9998247027397156, "start": 5424, "tag": "NAME", "value": "Bob" }, { "context": "back)', (done) ->\n flat = new Flat({name: 'Bob'})\n flat.save (err, model) ->\n as", "end": 5750, "score": 0.9998006820678711, "start": 5747, "tag": "NAME", "value": "Bob" }, { "context": "del')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n done()\n\n it 'M", "end": 6129, "score": 0.9997708797454834, "start": 6126, "tag": "NAME", "value": "Bob" }, { "context": " flat = new Flat()\n flat.save {name: 'Bob'}, (err, model) ->\n assert.ok(!err, \"No ", "end": 6274, "score": 0.9998061656951904, "start": 6271, "tag": "NAME", "value": "Bob" }, { "context": "del')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n done()\n\n it 'M", "end": 6635, "score": 0.9997914433479309, "start": 6632, "tag": "NAME", "value": "Bob" }, { "context": " flat = new Flat()\n flat.save {name: 'Bob'}, {}, (err, model) ->\n assert.ok(!err, ", "end": 6789, "score": 0.9998189210891724, "start": 6786, "tag": "NAME", "value": "Bob" }, { "context": "del')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n done()\n\n it 'M", "end": 7154, "score": 0.9997876286506653, "start": 7151, "tag": "NAME", "value": "Bob" }, { "context": " flat = new Flat()\n flat.save 'name', 'Bob', {}, (err, model) ->\n assert.ok(!err, \"", "end": 7314, "score": 0.9998244643211365, "start": 7311, "tag": "NAME", "value": "Bob" }, { "context": "del')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n done()\n\n it 'M", "end": 7678, "score": 0.9997910857200623, "start": 7675, "tag": "NAME", "value": "Bob" }, { "context": "ions)', (done) ->\n flat = new Flat({name: 'Bob'})\n flat.save (err, model) ->\n as", "end": 7801, "score": 0.9997853636741638, "start": 7798, "tag": "NAME", "value": "Bob" }, { "context": "del')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n\n flat.destroy (err)", "end": 8191, "score": 0.9998083710670471, "start": 8188, "tag": "NAME", "value": "Bob" }, { "context": "ions)', (done) ->\n flat = new Flat({name: 'Bob'})\n flat.save (err, model) ->\n as", "end": 8546, "score": 0.9998186826705933, "start": 8543, "tag": "NAME", "value": "Bob" }, { "context": "del')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n\n flat.destroy {}, (", "end": 8936, "score": 0.99981290102005, "start": 8933, "tag": "NAME", "value": "Bob" }, { "context": "ions)', (done) ->\n flat = new Flat({name: 'Bob'})\n flat.save (err, model) ->\n as", "end": 9291, "score": 0.9998125433921814, "start": 9288, "tag": "NAME", "value": "Bob" }, { "context": "del')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n done()\n\n it 'M", "end": 9670, "score": 0.9998312592506409, "start": 9667, "tag": "NAME", "value": "Bob" }, { "context": "ions)', (done) ->\n flat = new Flat({name: 'Bob'})\n flat.save (err, model) ->\n as", "end": 9793, "score": 0.9998041987419128, "start": 9790, "tag": "NAME", "value": "Bob" }, { "context": "del')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n done()\n\n it 'C", "end": 10176, "score": 0.9998099207878113, "start": 10173, "tag": "NAME", "value": "Bob" }, { "context": "ions)', (done) ->\n flat = new Flat({name: 'Bob'})\n flat.save (err, model) ->\n as", "end": 10302, "score": 0.9997966885566711, "start": 10299, "tag": "NAME", "value": "Bob" }, { "context": "del')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n done()\n\n it 'C", "end": 10708, "score": 0.9998019933700562, "start": 10705, "tag": "NAME", "value": "Bob" }, { "context": "ions)', (done) ->\n flat = new Flat({name: 'Bob'})\n flat.save (err, model) ->\n as", "end": 10836, "score": 0.9998188018798828, "start": 10833, "tag": "NAME", "value": "Bob" }, { "context": "del')\n assert.equal(flat.get('name'), 'Bob', 'name matches')\n done()\n", "end": 11246, "score": 0.999816358089447, "start": 11243, "tag": "NAME", "value": "Bob" } ]
test/generators/conventions/callbacks.coffee
michaelBenin/backbone-orm
1
util = require 'util' assert = require 'assert' _ = require 'underscore' Backbone = require 'backbone' Queue = require '../../../lib/queue' ModelCache = require('../../../lib/cache/singletons').ModelCache QueryCache = require('../../../lib/cache/singletons').QueryCache Fabricator = require '../../fabricator' module.exports = (options, callback) -> DATABASE_URL = options.database_url or '' BASE_SCHEMA = options.schema or {} SYNC = options.sync BASE_COUNT = 5 ModelCache.configure({enabled: !!options.cache, max: 100}).hardReset() # configure model cache class Flat extends Backbone.Model urlRoot: "#{DATABASE_URL}/flats" schema: BASE_SCHEMA sync: SYNC(Flat) class Flats extends Backbone.Collection url: "#{DATABASE_URL}/flats" model: Flat sync: SYNC(Flats) describe "Callbacks (cache: #{options.cache}, query_cache: #{options.query_cache})", -> before (done) -> return done() unless options.before; options.before([Flat], done) after (done) -> callback(); done() beforeEach (done) -> queue = new Queue(1) # reset caches queue.defer (callback) -> ModelCache.configure({enabled: !!options.cache, max: 100}).reset(callback) # configure model cache queue.defer (callback) -> QueryCache.configure({enabled: !!options.query_cache, verbose: false}).reset(callback) # configure query cache queue.defer (callback) -> Flat.resetSchema(callback) queue.defer (callback) -> Fabricator.create(Flat, BASE_COUNT, { name: Fabricator.uniqueId('flat_') created_at: Fabricator.date updated_at: Fabricator.date }, callback) queue.await done ############################## # No Callbacks (Options) ############################## describe "No callbacks", -> it 'Model.save (null, options) - non callback', (done) -> flat = new Flat({name: 'Bob'}) flat.save null, { success: (model) -> assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } it 'Model.save (attrs, options) - non callback', (done) -> flat = new Flat({name: 'Bob'}) flat.save {}, { success: (model) -> assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } it 'Model.save (key, value, options) - non callback', (done) -> flat = new Flat() flat.save 'name', 'Bob', { success: (model) -> assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } it 'Model.destroy (options) - non callback', (done) -> flat = new Flat({name: 'Bob'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: model_id = flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') flat.destroy { success: -> model = new Flat({id: model_id}) model.fetch (err) -> assert.ok(err, "Model not found: #{err}") done() error: -> assert.ok(false, "No errors: #{err}") } it 'Model.fetch (options) - non callback', (done) -> flat = new Flat({name: 'Bob'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) flat.fetch { success: (model) -> assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } it 'Collection.fetch (options) - non callback', (done) -> flat = new Flat({name: 'Bob'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') flats = new Flats() flats.fetch { success: -> model = flats.get(flat.id) assert.equal(flat.id, model.id, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } ############################## # Callbacks ############################## describe "Callbacks", -> it 'Model.save (callback)', (done) -> flat = new Flat({name: 'Bob'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') done() it 'Model.save (attrs, callback)', (done) -> flat = new Flat() flat.save {name: 'Bob'}, (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') done() it 'Model.save (attrs, options, callback)', (done) -> flat = new Flat() flat.save {name: 'Bob'}, {}, (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') done() it 'Model.save (key, value, options, callback)', (done) -> flat = new Flat() flat.save 'name', 'Bob', {}, (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') done() it 'Model.destroy (no options)', (done) -> flat = new Flat({name: 'Bob'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: model_id = flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') flat.destroy (err) -> assert.ok(!err, "No errors: #{err}") model = new Flat({id: model_id}) model.fetch (err) -> assert.ok(err, "Model not found: #{err}") done() it 'Model.destroy (with options)', (done) -> flat = new Flat({name: 'Bob'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: model_id = flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') flat.destroy {}, (err) -> assert.ok(!err, "No errors: #{err}") model = new Flat({id: model_id}) model.fetch (err) -> assert.ok(err, "Model not found: #{err}") done() it 'Model.fetch (no options)', (done) -> flat = new Flat({name: 'Bob'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') done() it 'Model.fetch (with options)', (done) -> flat = new Flat({name: 'Bob'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch {}, (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') done() it 'Collection.fetch (no options)', (done) -> flat = new Flat({name: 'Bob'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') flats = new Flats() flats.fetch (err) -> assert.ok(!err, "No errors: #{err}") model = flats.get(flat.id) assert.equal(flat.id, model.id, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') done() it 'Collection.fetch (with options)', (done) -> flat = new Flat({name: 'Bob'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') flats = new Flats() flats.fetch {}, (err) -> assert.ok(!err, "No errors: #{err}") model = flats.get(flat.id) assert.equal(flat.id, model.id, 'returned the model') assert.equal(flat.get('name'), 'Bob', 'name matches') done()
206013
util = require 'util' assert = require 'assert' _ = require 'underscore' Backbone = require 'backbone' Queue = require '../../../lib/queue' ModelCache = require('../../../lib/cache/singletons').ModelCache QueryCache = require('../../../lib/cache/singletons').QueryCache Fabricator = require '../../fabricator' module.exports = (options, callback) -> DATABASE_URL = options.database_url or '' BASE_SCHEMA = options.schema or {} SYNC = options.sync BASE_COUNT = 5 ModelCache.configure({enabled: !!options.cache, max: 100}).hardReset() # configure model cache class Flat extends Backbone.Model urlRoot: "#{DATABASE_URL}/flats" schema: BASE_SCHEMA sync: SYNC(Flat) class Flats extends Backbone.Collection url: "#{DATABASE_URL}/flats" model: Flat sync: SYNC(Flats) describe "Callbacks (cache: #{options.cache}, query_cache: #{options.query_cache})", -> before (done) -> return done() unless options.before; options.before([Flat], done) after (done) -> callback(); done() beforeEach (done) -> queue = new Queue(1) # reset caches queue.defer (callback) -> ModelCache.configure({enabled: !!options.cache, max: 100}).reset(callback) # configure model cache queue.defer (callback) -> QueryCache.configure({enabled: !!options.query_cache, verbose: false}).reset(callback) # configure query cache queue.defer (callback) -> Flat.resetSchema(callback) queue.defer (callback) -> Fabricator.create(Flat, BASE_COUNT, { name: Fabricator.uniqueId('flat_') created_at: Fabricator.date updated_at: Fabricator.date }, callback) queue.await done ############################## # No Callbacks (Options) ############################## describe "No callbacks", -> it 'Model.save (null, options) - non callback', (done) -> flat = new Flat({name: '<NAME>'}) flat.save null, { success: (model) -> assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } it 'Model.save (attrs, options) - non callback', (done) -> flat = new Flat({name: '<NAME>'}) flat.save {}, { success: (model) -> assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } it 'Model.save (key, value, options) - non callback', (done) -> flat = new Flat() flat.save 'name', '<NAME>', { success: (model) -> assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } it 'Model.destroy (options) - non callback', (done) -> flat = new Flat({name: '<NAME>'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: model_id = flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') flat.destroy { success: -> model = new Flat({id: model_id}) model.fetch (err) -> assert.ok(err, "Model not found: #{err}") done() error: -> assert.ok(false, "No errors: #{err}") } it 'Model.fetch (options) - non callback', (done) -> flat = new Flat({name: '<NAME>'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) flat.fetch { success: (model) -> assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } it 'Collection.fetch (options) - non callback', (done) -> flat = new Flat({name: '<NAME>'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') flats = new Flats() flats.fetch { success: -> model = flats.get(flat.id) assert.equal(flat.id, model.id, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } ############################## # Callbacks ############################## describe "Callbacks", -> it 'Model.save (callback)', (done) -> flat = new Flat({name: '<NAME>'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') done() it 'Model.save (attrs, callback)', (done) -> flat = new Flat() flat.save {name: '<NAME>'}, (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') done() it 'Model.save (attrs, options, callback)', (done) -> flat = new Flat() flat.save {name: '<NAME>'}, {}, (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') done() it 'Model.save (key, value, options, callback)', (done) -> flat = new Flat() flat.save 'name', '<NAME>', {}, (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') done() it 'Model.destroy (no options)', (done) -> flat = new Flat({name: '<NAME>'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: model_id = flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') flat.destroy (err) -> assert.ok(!err, "No errors: #{err}") model = new Flat({id: model_id}) model.fetch (err) -> assert.ok(err, "Model not found: #{err}") done() it 'Model.destroy (with options)', (done) -> flat = new Flat({name: '<NAME>'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: model_id = flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') flat.destroy {}, (err) -> assert.ok(!err, "No errors: #{err}") model = new Flat({id: model_id}) model.fetch (err) -> assert.ok(err, "Model not found: #{err}") done() it 'Model.fetch (no options)', (done) -> flat = new Flat({name: '<NAME>'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') done() it 'Model.fetch (with options)', (done) -> flat = new Flat({name: '<NAME>'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch {}, (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') done() it 'Collection.fetch (no options)', (done) -> flat = new Flat({name: '<NAME>'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') flats = new Flats() flats.fetch (err) -> assert.ok(!err, "No errors: #{err}") model = flats.get(flat.id) assert.equal(flat.id, model.id, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') done() it 'Collection.fetch (with options)', (done) -> flat = new Flat({name: '<NAME>'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') flats = new Flats() flats.fetch {}, (err) -> assert.ok(!err, "No errors: #{err}") model = flats.get(flat.id) assert.equal(flat.id, model.id, 'returned the model') assert.equal(flat.get('name'), '<NAME>', 'name matches') done()
true
util = require 'util' assert = require 'assert' _ = require 'underscore' Backbone = require 'backbone' Queue = require '../../../lib/queue' ModelCache = require('../../../lib/cache/singletons').ModelCache QueryCache = require('../../../lib/cache/singletons').QueryCache Fabricator = require '../../fabricator' module.exports = (options, callback) -> DATABASE_URL = options.database_url or '' BASE_SCHEMA = options.schema or {} SYNC = options.sync BASE_COUNT = 5 ModelCache.configure({enabled: !!options.cache, max: 100}).hardReset() # configure model cache class Flat extends Backbone.Model urlRoot: "#{DATABASE_URL}/flats" schema: BASE_SCHEMA sync: SYNC(Flat) class Flats extends Backbone.Collection url: "#{DATABASE_URL}/flats" model: Flat sync: SYNC(Flats) describe "Callbacks (cache: #{options.cache}, query_cache: #{options.query_cache})", -> before (done) -> return done() unless options.before; options.before([Flat], done) after (done) -> callback(); done() beforeEach (done) -> queue = new Queue(1) # reset caches queue.defer (callback) -> ModelCache.configure({enabled: !!options.cache, max: 100}).reset(callback) # configure model cache queue.defer (callback) -> QueryCache.configure({enabled: !!options.query_cache, verbose: false}).reset(callback) # configure query cache queue.defer (callback) -> Flat.resetSchema(callback) queue.defer (callback) -> Fabricator.create(Flat, BASE_COUNT, { name: Fabricator.uniqueId('flat_') created_at: Fabricator.date updated_at: Fabricator.date }, callback) queue.await done ############################## # No Callbacks (Options) ############################## describe "No callbacks", -> it 'Model.save (null, options) - non callback', (done) -> flat = new Flat({name: 'PI:NAME:<NAME>END_PI'}) flat.save null, { success: (model) -> assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } it 'Model.save (attrs, options) - non callback', (done) -> flat = new Flat({name: 'PI:NAME:<NAME>END_PI'}) flat.save {}, { success: (model) -> assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } it 'Model.save (key, value, options) - non callback', (done) -> flat = new Flat() flat.save 'name', 'PI:NAME:<NAME>END_PI', { success: (model) -> assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } it 'Model.destroy (options) - non callback', (done) -> flat = new Flat({name: 'PI:NAME:<NAME>END_PI'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: model_id = flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') flat.destroy { success: -> model = new Flat({id: model_id}) model.fetch (err) -> assert.ok(err, "Model not found: #{err}") done() error: -> assert.ok(false, "No errors: #{err}") } it 'Model.fetch (options) - non callback', (done) -> flat = new Flat({name: 'PI:NAME:<NAME>END_PI'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) flat.fetch { success: (model) -> assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } it 'Collection.fetch (options) - non callback', (done) -> flat = new Flat({name: 'PI:NAME:<NAME>END_PI'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') flats = new Flats() flats.fetch { success: -> model = flats.get(flat.id) assert.equal(flat.id, model.id, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') done() error: -> assert.ok(false, "No errors: #{err}") } ############################## # Callbacks ############################## describe "Callbacks", -> it 'Model.save (callback)', (done) -> flat = new Flat({name: 'PI:NAME:<NAME>END_PI'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') done() it 'Model.save (attrs, callback)', (done) -> flat = new Flat() flat.save {name: 'PI:NAME:<NAME>END_PI'}, (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') done() it 'Model.save (attrs, options, callback)', (done) -> flat = new Flat() flat.save {name: 'PI:NAME:<NAME>END_PI'}, {}, (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') done() it 'Model.save (key, value, options, callback)', (done) -> flat = new Flat() flat.save 'name', 'PI:NAME:<NAME>END_PI', {}, (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') done() it 'Model.destroy (no options)', (done) -> flat = new Flat({name: 'PI:NAME:<NAME>END_PI'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: model_id = flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') flat.destroy (err) -> assert.ok(!err, "No errors: #{err}") model = new Flat({id: model_id}) model.fetch (err) -> assert.ok(err, "Model not found: #{err}") done() it 'Model.destroy (with options)', (done) -> flat = new Flat({name: 'PI:NAME:<NAME>END_PI'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: model_id = flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') flat.destroy {}, (err) -> assert.ok(!err, "No errors: #{err}") model = new Flat({id: model_id}) model.fetch (err) -> assert.ok(err, "Model not found: #{err}") done() it 'Model.fetch (no options)', (done) -> flat = new Flat({name: 'PI:NAME:<NAME>END_PI'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') done() it 'Model.fetch (with options)', (done) -> flat = new Flat({name: 'PI:NAME:<NAME>END_PI'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') model = new Flat({id: flat.id}) model.fetch {}, (err, flat) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') done() it 'Collection.fetch (no options)', (done) -> flat = new Flat({name: 'PI:NAME:<NAME>END_PI'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') flats = new Flats() flats.fetch (err) -> assert.ok(!err, "No errors: #{err}") model = flats.get(flat.id) assert.equal(flat.id, model.id, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') done() it 'Collection.fetch (with options)', (done) -> flat = new Flat({name: 'PI:NAME:<NAME>END_PI'}) flat.save (err, model) -> assert.ok(!err, "No errors: #{err}") assert.equal(flat, model, 'returned the model') flats = new Flats() flats.fetch {}, (err) -> assert.ok(!err, "No errors: #{err}") model = flats.get(flat.id) assert.equal(flat.id, model.id, 'returned the model') assert.equal(flat.get('name'), 'PI:NAME:<NAME>END_PI', 'name matches') done()
[ { "context": "turers'\n level_creator: 'Artisans'\n developer: 'Archmages'\n article_editor: 'Scribes'\n translator: 'Diplo", "end": 2407, "score": 0.8400089740753174, "start": 2398, "tag": "NAME", "value": "Archmages" }, { "context": "sans'\n developer: 'Archmages'\n article_editor: 'Scribes'\n translator: 'Diplomats'\n support: 'Ambassador", "end": 2435, "score": 0.9957308173179626, "start": 2428, "tag": "NAME", "value": "Scribes" }, { "context": ".statics.hashPassword = (password) ->\n password = password.toLowerCase()\n shasum = crypto.createHash('sha51", "end": 2634, "score": 0.8836666345596313, "start": 2626, "tag": "PASSWORD", "value": "password" }, { "context": "ashPassword = (password) ->\n password = password.toLowerCase()\n shasum = crypto.createHash('sha512')\n shasum", "end": 2646, "score": 0.9349424839019775, "start": 2635, "tag": "PASSWORD", "value": "toLowerCase" } ]
server/models/User.coffee
cochee/codecombat
1
mongoose = require('mongoose') jsonschema = require('../schemas/user') crypto = require('crypto') {salt, isProduction} = require('../../server_config') UserSchema = new mongoose.Schema({ dateCreated: type: Date 'default': Date.now }, {strict: false}) UserSchema.pre('init', (next) -> return next() unless jsonschema.properties? for prop, sch of jsonschema.properties @set(prop, sch.default) if sch.default? next() ) UserSchema.post('init', -> @set('anonymous', false) if @get('email') @currentSubscriptions = JSON.stringify(@get('emailSubscriptions')) ) UserSchema.methods.isAdmin = -> p = @get('permissions') return p and 'admin' in p UserSchema.statics.updateMailChimp = (doc, callback) -> return callback?() unless isProduction return callback?() if doc.updatedMailChimp return callback?() unless doc.get('email') existingProps = doc.get('mailChimp') emailChanged = (not existingProps) or existingProps?.email isnt doc.get('email') emailSubs = doc.get('emailSubscriptions') newGroups = (groupingMap[name] for name in emailSubs) if (not existingProps) and newGroups.length is 0 return callback?() # don't add totally unsubscribed people to the list subsChanged = doc.currentSubscriptions isnt JSON.stringify(emailSubs) return callback?() unless emailChanged or subsChanged params = {} params.id = MAILCHIMP_LIST_ID params.email = if existingProps then {leid:existingProps.leid} else {email:doc.get('email')} params.merge_vars = { groupings: [ {id: MAILCHIMP_GROUP_ID, groups: newGroups} ] } params.update_existing = true onSuccess = (data) -> doc.set('mailChimp', data) doc.updatedMailChimp = true doc.save() callback?() onFailure = (error) -> console.error 'failed to subscribe', error, callback? doc.updatedMailChimp = true callback?() mc.lists.subscribe params, onSuccess, onFailure UserSchema.pre('save', (next) -> @set('emailLower', @get('email')?.toLowerCase()) @set('nameLower', @get('name')?.toLowerCase()) pwd = @get('password') if @get('password') @set('passwordHash', User.hashPassword(pwd)) @set('password', undefined) @set('anonymous', false) if @get('email') next() ) MAILCHIMP_LIST_ID = 'e9851239eb' MAILCHIMP_GROUP_ID = '4529' groupingMap = announcement: 'Announcements' tester: 'Adventurers' level_creator: 'Artisans' developer: 'Archmages' article_editor: 'Scribes' translator: 'Diplomats' support: 'Ambassadors' UserSchema.post 'save', (doc) -> UserSchema.statics.updateMailChimp(doc) UserSchema.statics.hashPassword = (password) -> password = password.toLowerCase() shasum = crypto.createHash('sha512') shasum.update(salt + password) shasum.digest('hex') module.exports = User = mongoose.model('User', UserSchema)
136626
mongoose = require('mongoose') jsonschema = require('../schemas/user') crypto = require('crypto') {salt, isProduction} = require('../../server_config') UserSchema = new mongoose.Schema({ dateCreated: type: Date 'default': Date.now }, {strict: false}) UserSchema.pre('init', (next) -> return next() unless jsonschema.properties? for prop, sch of jsonschema.properties @set(prop, sch.default) if sch.default? next() ) UserSchema.post('init', -> @set('anonymous', false) if @get('email') @currentSubscriptions = JSON.stringify(@get('emailSubscriptions')) ) UserSchema.methods.isAdmin = -> p = @get('permissions') return p and 'admin' in p UserSchema.statics.updateMailChimp = (doc, callback) -> return callback?() unless isProduction return callback?() if doc.updatedMailChimp return callback?() unless doc.get('email') existingProps = doc.get('mailChimp') emailChanged = (not existingProps) or existingProps?.email isnt doc.get('email') emailSubs = doc.get('emailSubscriptions') newGroups = (groupingMap[name] for name in emailSubs) if (not existingProps) and newGroups.length is 0 return callback?() # don't add totally unsubscribed people to the list subsChanged = doc.currentSubscriptions isnt JSON.stringify(emailSubs) return callback?() unless emailChanged or subsChanged params = {} params.id = MAILCHIMP_LIST_ID params.email = if existingProps then {leid:existingProps.leid} else {email:doc.get('email')} params.merge_vars = { groupings: [ {id: MAILCHIMP_GROUP_ID, groups: newGroups} ] } params.update_existing = true onSuccess = (data) -> doc.set('mailChimp', data) doc.updatedMailChimp = true doc.save() callback?() onFailure = (error) -> console.error 'failed to subscribe', error, callback? doc.updatedMailChimp = true callback?() mc.lists.subscribe params, onSuccess, onFailure UserSchema.pre('save', (next) -> @set('emailLower', @get('email')?.toLowerCase()) @set('nameLower', @get('name')?.toLowerCase()) pwd = @get('password') if @get('password') @set('passwordHash', User.hashPassword(pwd)) @set('password', undefined) @set('anonymous', false) if @get('email') next() ) MAILCHIMP_LIST_ID = 'e9851239eb' MAILCHIMP_GROUP_ID = '4529' groupingMap = announcement: 'Announcements' tester: 'Adventurers' level_creator: 'Artisans' developer: '<NAME>' article_editor: '<NAME>' translator: 'Diplomats' support: 'Ambassadors' UserSchema.post 'save', (doc) -> UserSchema.statics.updateMailChimp(doc) UserSchema.statics.hashPassword = (password) -> password = <PASSWORD>.<PASSWORD>() shasum = crypto.createHash('sha512') shasum.update(salt + password) shasum.digest('hex') module.exports = User = mongoose.model('User', UserSchema)
true
mongoose = require('mongoose') jsonschema = require('../schemas/user') crypto = require('crypto') {salt, isProduction} = require('../../server_config') UserSchema = new mongoose.Schema({ dateCreated: type: Date 'default': Date.now }, {strict: false}) UserSchema.pre('init', (next) -> return next() unless jsonschema.properties? for prop, sch of jsonschema.properties @set(prop, sch.default) if sch.default? next() ) UserSchema.post('init', -> @set('anonymous', false) if @get('email') @currentSubscriptions = JSON.stringify(@get('emailSubscriptions')) ) UserSchema.methods.isAdmin = -> p = @get('permissions') return p and 'admin' in p UserSchema.statics.updateMailChimp = (doc, callback) -> return callback?() unless isProduction return callback?() if doc.updatedMailChimp return callback?() unless doc.get('email') existingProps = doc.get('mailChimp') emailChanged = (not existingProps) or existingProps?.email isnt doc.get('email') emailSubs = doc.get('emailSubscriptions') newGroups = (groupingMap[name] for name in emailSubs) if (not existingProps) and newGroups.length is 0 return callback?() # don't add totally unsubscribed people to the list subsChanged = doc.currentSubscriptions isnt JSON.stringify(emailSubs) return callback?() unless emailChanged or subsChanged params = {} params.id = MAILCHIMP_LIST_ID params.email = if existingProps then {leid:existingProps.leid} else {email:doc.get('email')} params.merge_vars = { groupings: [ {id: MAILCHIMP_GROUP_ID, groups: newGroups} ] } params.update_existing = true onSuccess = (data) -> doc.set('mailChimp', data) doc.updatedMailChimp = true doc.save() callback?() onFailure = (error) -> console.error 'failed to subscribe', error, callback? doc.updatedMailChimp = true callback?() mc.lists.subscribe params, onSuccess, onFailure UserSchema.pre('save', (next) -> @set('emailLower', @get('email')?.toLowerCase()) @set('nameLower', @get('name')?.toLowerCase()) pwd = @get('password') if @get('password') @set('passwordHash', User.hashPassword(pwd)) @set('password', undefined) @set('anonymous', false) if @get('email') next() ) MAILCHIMP_LIST_ID = 'e9851239eb' MAILCHIMP_GROUP_ID = '4529' groupingMap = announcement: 'Announcements' tester: 'Adventurers' level_creator: 'Artisans' developer: 'PI:NAME:<NAME>END_PI' article_editor: 'PI:NAME:<NAME>END_PI' translator: 'Diplomats' support: 'Ambassadors' UserSchema.post 'save', (doc) -> UserSchema.statics.updateMailChimp(doc) UserSchema.statics.hashPassword = (password) -> password = PI:PASSWORD:<PASSWORD>END_PI.PI:PASSWORD:<PASSWORD>END_PI() shasum = crypto.createHash('sha512') shasum.update(salt + password) shasum.digest('hex') module.exports = User = mongoose.model('User', UserSchema)
[ { "context": "1, 2, 3, 4 ]\ndataB = [ 1.5, 1.3, 3.2 ]\ndataC = [ \"正一郎\", \"清次郎\", \"誠三郎\", \"征史郎\" ]\n\n# 偶数\ndataA_F = new Linq(", "end": 103, "score": 0.9990911483764648, "start": 100, "tag": "NAME", "value": "正一郎" }, { "context": ", 4 ]\ndataB = [ 1.5, 1.3, 3.2 ]\ndataC = [ \"正一郎\", \"清次郎\", \"誠三郎\", \"征史郎\" ]\n\n# 偶数\ndataA_F = new Linq(dataA).", "end": 110, "score": 0.9996875524520874, "start": 107, "tag": "NAME", "value": "清次郎" }, { "context": "ataB = [ 1.5, 1.3, 3.2 ]\ndataC = [ \"正一郎\", \"清次郎\", \"誠三郎\", \"征史郎\" ]\n\n# 偶数\ndataA_F = new Linq(dataA).Where( ", "end": 117, "score": 0.9990653991699219, "start": 114, "tag": "NAME", "value": "誠三郎" }, { "context": "[ 1.5, 1.3, 3.2 ]\ndataC = [ \"正一郎\", \"清次郎\", \"誠三郎\", \"征史郎\" ]\n\n# 偶数\ndataA_F = new Linq(dataA).Where( (value)", "end": 124, "score": 0.9972531199455261, "start": 121, "tag": "NAME", "value": "征史郎" } ]
test/coffee/where.coffee
Lxsbw/linqjs
0
Linq = require('../../src/coffee') dataA = [ 0, 1, 2, 3, 4 ] dataB = [ 1.5, 1.3, 3.2 ] dataC = [ "正一郎", "清次郎", "誠三郎", "征史郎" ] # 偶数 dataA_F = new Linq(dataA).Where( (value) -> value % 2 == 0 ).ToArray() # 小于2 dataB_F = new Linq(dataB).Where( (value) -> value < 2.0 ).ToArray() # 长度小于5 dataC_F = new Linq(dataC).Where( (value) -> value.length < 5 ).ToArray() console.log 'dataA_F:', dataA_F console.log 'dataB_F:', dataB_F console.log 'dataC_F:', dataC_F
78541
Linq = require('../../src/coffee') dataA = [ 0, 1, 2, 3, 4 ] dataB = [ 1.5, 1.3, 3.2 ] dataC = [ "<NAME>", "<NAME>", "<NAME>", "<NAME>" ] # 偶数 dataA_F = new Linq(dataA).Where( (value) -> value % 2 == 0 ).ToArray() # 小于2 dataB_F = new Linq(dataB).Where( (value) -> value < 2.0 ).ToArray() # 长度小于5 dataC_F = new Linq(dataC).Where( (value) -> value.length < 5 ).ToArray() console.log 'dataA_F:', dataA_F console.log 'dataB_F:', dataB_F console.log 'dataC_F:', dataC_F
true
Linq = require('../../src/coffee') dataA = [ 0, 1, 2, 3, 4 ] dataB = [ 1.5, 1.3, 3.2 ] dataC = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] # 偶数 dataA_F = new Linq(dataA).Where( (value) -> value % 2 == 0 ).ToArray() # 小于2 dataB_F = new Linq(dataB).Where( (value) -> value < 2.0 ).ToArray() # 长度小于5 dataC_F = new Linq(dataC).Where( (value) -> value.length < 5 ).ToArray() console.log 'dataA_F:', dataA_F console.log 'dataB_F:', dataB_F console.log 'dataC_F:', dataC_F
[ { "context": "\nnikita = require '@nikitajs/core'\n{tags, ssh, scratch} = require '../test'\nth", "end": 28, "score": 0.8359941244125366, "start": 23, "tag": "USERNAME", "value": "itajs" }, { "context": "1'\n config:\n 'environment.MY_KEY_1': 'my value 1'\n 'environment.MY_KEY_2': 'my value 2'\n ", "end": 457, "score": 0.9901157021522522, "start": 447, "tag": "KEY", "value": "my value 1" }, { "context": "1': 'my value 1'\n 'environment.MY_KEY_2': 'my value 2'\n .lxd.start\n container: 'c1'\n .system", "end": 502, "score": 0.9864871501922607, "start": 492, "tag": "KEY", "value": "my value 2" } ]
packages/lxd/test/config/set.coffee
chibanemourad/node-nikita
0
nikita = require '@nikitajs/core' {tags, ssh, scratch} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.lxd describe 'lxd.config.set', -> they 'multiple keys', ({ssh}) -> nikita ssh: ssh .lxd.delete container: 'c1' force: true .lxd.init image: 'ubuntu:18.04' container: 'c1' .lxd.config.set container: 'c1' config: 'environment.MY_KEY_1': 'my value 1' 'environment.MY_KEY_2': 'my value 2' .lxd.start container: 'c1' .system.execute cmd: "lxc exec c1 -- env | grep MY_KEY_1" trim: true , (err, {stdout}) -> stdout.should.eql 'MY_KEY_1=my value 1' .system.execute cmd: "lxc exec c1 -- env | grep MY_KEY_2" trim: true , (err, {stdout}) -> stdout.should.eql 'MY_KEY_2=my value 2' .promise()
165952
nikita = require '@nikitajs/core' {tags, ssh, scratch} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.lxd describe 'lxd.config.set', -> they 'multiple keys', ({ssh}) -> nikita ssh: ssh .lxd.delete container: 'c1' force: true .lxd.init image: 'ubuntu:18.04' container: 'c1' .lxd.config.set container: 'c1' config: 'environment.MY_KEY_1': '<KEY>' 'environment.MY_KEY_2': '<KEY>' .lxd.start container: 'c1' .system.execute cmd: "lxc exec c1 -- env | grep MY_KEY_1" trim: true , (err, {stdout}) -> stdout.should.eql 'MY_KEY_1=my value 1' .system.execute cmd: "lxc exec c1 -- env | grep MY_KEY_2" trim: true , (err, {stdout}) -> stdout.should.eql 'MY_KEY_2=my value 2' .promise()
true
nikita = require '@nikitajs/core' {tags, ssh, scratch} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.lxd describe 'lxd.config.set', -> they 'multiple keys', ({ssh}) -> nikita ssh: ssh .lxd.delete container: 'c1' force: true .lxd.init image: 'ubuntu:18.04' container: 'c1' .lxd.config.set container: 'c1' config: 'environment.MY_KEY_1': 'PI:KEY:<KEY>END_PI' 'environment.MY_KEY_2': 'PI:KEY:<KEY>END_PI' .lxd.start container: 'c1' .system.execute cmd: "lxc exec c1 -- env | grep MY_KEY_1" trim: true , (err, {stdout}) -> stdout.should.eql 'MY_KEY_1=my value 1' .system.execute cmd: "lxc exec c1 -- env | grep MY_KEY_2" trim: true , (err, {stdout}) -> stdout.should.eql 'MY_KEY_2=my value 2' .promise()
[ { "context": "or-in loops without if statements inside\n# @author Nicholas C. Zakas\n###\n\n'use strict'\n\nisIf = (node) ->\n return node", "end": 103, "score": 0.9998432397842407, "start": 86, "tag": "NAME", "value": "Nicholas C. Zakas" } ]
src/rules/guard-for-in.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Rule to flag for-in loops without if statements inside # @author Nicholas C. Zakas ### 'use strict' isIf = (node) -> return node if node.type is 'IfStatement' return node.expression if ( node.type is 'ExpressionStatement' and node.expression.type is 'ConditionalExpression' ) no #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'require `for-in` loops to include an `if` statement' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/guard-for-in' schema: [] create: (context) -> For: (node) -> {body, style, own} = node # only for-of return unless style is 'of' # `own` filters the prototype return if own # empty statement return if body.type is 'EmptyStatement' # if statement return if isIf body # empty block return if body.type is 'BlockStatement' and body.body.length is 0 # block with just if statement return if ( body.type is 'BlockStatement' and body.body.length is 1 and isIf body.body[0] ) # block that starts with if statement if ( body.type is 'BlockStatement' and body.body.length >= 1 and (ifNode = isIf body.body[0]) ) # ... whose consequent is a continue return if ifNode.consequent.type is 'ContinueStatement' # ... whose consequent is a block that contains only a continue return if ( ifNode.consequent.type is 'BlockStatement' and ifNode.consequent.body.length is 1 and ifNode.consequent.body[0].type is 'ContinueStatement' ) context.report { node message: 'The body of a for-of should use "own" or be wrapped in an if statement to filter unwanted properties from the prototype.' }
164752
###* # @fileoverview Rule to flag for-in loops without if statements inside # @author <NAME> ### 'use strict' isIf = (node) -> return node if node.type is 'IfStatement' return node.expression if ( node.type is 'ExpressionStatement' and node.expression.type is 'ConditionalExpression' ) no #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'require `for-in` loops to include an `if` statement' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/guard-for-in' schema: [] create: (context) -> For: (node) -> {body, style, own} = node # only for-of return unless style is 'of' # `own` filters the prototype return if own # empty statement return if body.type is 'EmptyStatement' # if statement return if isIf body # empty block return if body.type is 'BlockStatement' and body.body.length is 0 # block with just if statement return if ( body.type is 'BlockStatement' and body.body.length is 1 and isIf body.body[0] ) # block that starts with if statement if ( body.type is 'BlockStatement' and body.body.length >= 1 and (ifNode = isIf body.body[0]) ) # ... whose consequent is a continue return if ifNode.consequent.type is 'ContinueStatement' # ... whose consequent is a block that contains only a continue return if ( ifNode.consequent.type is 'BlockStatement' and ifNode.consequent.body.length is 1 and ifNode.consequent.body[0].type is 'ContinueStatement' ) context.report { node message: 'The body of a for-of should use "own" or be wrapped in an if statement to filter unwanted properties from the prototype.' }
true
###* # @fileoverview Rule to flag for-in loops without if statements inside # @author PI:NAME:<NAME>END_PI ### 'use strict' isIf = (node) -> return node if node.type is 'IfStatement' return node.expression if ( node.type is 'ExpressionStatement' and node.expression.type is 'ConditionalExpression' ) no #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'require `for-in` loops to include an `if` statement' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/guard-for-in' schema: [] create: (context) -> For: (node) -> {body, style, own} = node # only for-of return unless style is 'of' # `own` filters the prototype return if own # empty statement return if body.type is 'EmptyStatement' # if statement return if isIf body # empty block return if body.type is 'BlockStatement' and body.body.length is 0 # block with just if statement return if ( body.type is 'BlockStatement' and body.body.length is 1 and isIf body.body[0] ) # block that starts with if statement if ( body.type is 'BlockStatement' and body.body.length >= 1 and (ifNode = isIf body.body[0]) ) # ... whose consequent is a continue return if ifNode.consequent.type is 'ContinueStatement' # ... whose consequent is a block that contains only a continue return if ( ifNode.consequent.type is 'BlockStatement' and ifNode.consequent.body.length is 1 and ifNode.consequent.body[0].type is 'ContinueStatement' ) context.report { node message: 'The body of a for-of should use "own" or be wrapped in an if statement to filter unwanted properties from the prototype.' }
[ { "context": " #\n # Possible calls:\n #\n # @attribute \"firstname\"\n #\n # # Setting the type\n # @attribute ", "end": 131, "score": 0.597775936126709, "start": 122, "tag": "NAME", "value": "firstname" }, { "context": "\n #\n # # Setting the type\n # @attribute \"firstname\", type: \"String\"\n attribute: (name, options) -", "end": 191, "score": 0.7082453370094299, "start": 182, "tag": "NAME", "value": "firstname" } ]
src/server/models/mixins/attributes.coffee
komola/salad
2
module.exports = ClassMethods: # Add an attribute to this model # # Possible calls: # # @attribute "firstname" # # # Setting the type # @attribute "firstname", type: "String" attribute: (name, options) -> @metadata().attributes or= {} defaultOptions = name: name type: "String" options = _.extend defaultOptions, options @metadata().attributes[name] = options InstanceMethods: setAttributes: (attributes) -> for key, val of attributes if @hasAttribute key @set key, val else if @hasAssociation key @setAssociation key, val getDefaultValues: -> defaultValues = {} for key, options of @getAttributeDefinitions() when options.default isnt undefined defaultValues[key] = options.default defaultValues # initialize default values initDefaultValues: -> return if @attributeValues @attributeValues = @getDefaultValues() # do not register the default values as changes @takeSnapshot() # check if a model has an attribute hasAttribute: (key) -> @metadata().attributes[key]? getAttributes: -> @initDefaultValues() return _.clone @attributeValues, true getAttributeDefinitions: -> @metadata().attributes set: (key, value) -> @_checkIfKeyExists key @initDefaultValues() @attributeValues[key] = value get: (key) -> @_checkIfKeyExists key @initDefaultValues() value = @attributeValues[key] if value is undefined value = @getAttributeDefinitions()[key]?.defaultValue value _checkIfKeyExists: (key) -> unless key of @metadata().attributes throw new Error "#{key} not existent in #{@}"
224195
module.exports = ClassMethods: # Add an attribute to this model # # Possible calls: # # @attribute "<NAME>" # # # Setting the type # @attribute "<NAME>", type: "String" attribute: (name, options) -> @metadata().attributes or= {} defaultOptions = name: name type: "String" options = _.extend defaultOptions, options @metadata().attributes[name] = options InstanceMethods: setAttributes: (attributes) -> for key, val of attributes if @hasAttribute key @set key, val else if @hasAssociation key @setAssociation key, val getDefaultValues: -> defaultValues = {} for key, options of @getAttributeDefinitions() when options.default isnt undefined defaultValues[key] = options.default defaultValues # initialize default values initDefaultValues: -> return if @attributeValues @attributeValues = @getDefaultValues() # do not register the default values as changes @takeSnapshot() # check if a model has an attribute hasAttribute: (key) -> @metadata().attributes[key]? getAttributes: -> @initDefaultValues() return _.clone @attributeValues, true getAttributeDefinitions: -> @metadata().attributes set: (key, value) -> @_checkIfKeyExists key @initDefaultValues() @attributeValues[key] = value get: (key) -> @_checkIfKeyExists key @initDefaultValues() value = @attributeValues[key] if value is undefined value = @getAttributeDefinitions()[key]?.defaultValue value _checkIfKeyExists: (key) -> unless key of @metadata().attributes throw new Error "#{key} not existent in #{@}"
true
module.exports = ClassMethods: # Add an attribute to this model # # Possible calls: # # @attribute "PI:NAME:<NAME>END_PI" # # # Setting the type # @attribute "PI:NAME:<NAME>END_PI", type: "String" attribute: (name, options) -> @metadata().attributes or= {} defaultOptions = name: name type: "String" options = _.extend defaultOptions, options @metadata().attributes[name] = options InstanceMethods: setAttributes: (attributes) -> for key, val of attributes if @hasAttribute key @set key, val else if @hasAssociation key @setAssociation key, val getDefaultValues: -> defaultValues = {} for key, options of @getAttributeDefinitions() when options.default isnt undefined defaultValues[key] = options.default defaultValues # initialize default values initDefaultValues: -> return if @attributeValues @attributeValues = @getDefaultValues() # do not register the default values as changes @takeSnapshot() # check if a model has an attribute hasAttribute: (key) -> @metadata().attributes[key]? getAttributes: -> @initDefaultValues() return _.clone @attributeValues, true getAttributeDefinitions: -> @metadata().attributes set: (key, value) -> @_checkIfKeyExists key @initDefaultValues() @attributeValues[key] = value get: (key) -> @_checkIfKeyExists key @initDefaultValues() value = @attributeValues[key] if value is undefined value = @getAttributeDefinitions()[key]?.defaultValue value _checkIfKeyExists: (key) -> unless key of @metadata().attributes throw new Error "#{key} not existent in #{@}"
[ { "context": "shed_at: new Date().toISOString(), author: name: 'Kana'),\n new Article(title: 'World', published_", "end": 1027, "score": 0.9994888305664062, "start": 1023, "tag": "NAME", "value": "Kana" }, { "context": "shed_at: new Date().toISOString(), author: name: 'Kana')\n ]\n rendered = iasTemplate(sd: sd, ar", "end": 1126, "score": 0.999719500541687, "start": 1122, "tag": "NAME", "value": "Kana" }, { "context": " contributing_authors: [{\n name: 'James'\n profile_id: 'foo'\n }],\n ", "end": 1788, "score": 0.9997519254684448, "start": 1783, "tag": "NAME", "value": "James" }, { "context": "o'\n }],\n author: {\n name: 'Artsy Editorial'\n profile_id: '5086df078523e60002000009'", "end": 1880, "score": 0.9997619390487671, "start": 1865, "tag": "NAME", "value": "Artsy Editorial" }, { "context": "ticle)\n rendered.should.containEql '<address>James</address>'\n rendered.should.containEql '<add", "end": 2051, "score": 0.913081705570221, "start": 2046, "tag": "NAME", "value": "James" }, { "context": "ibuting_authors: [\n {\n name: 'James'\n profile_id: 'foo'\n },\n ", "end": 2301, "score": 0.9997739791870117, "start": 2296, "tag": "NAME", "value": "James" }, { "context": "'foo'\n },\n {\n name: 'Plato'\n profile_id: 'bar'\n },\n ", "end": 2382, "score": 0.9998136758804321, "start": 2377, "tag": "NAME", "value": "Plato" }, { "context": "'bar'\n },\n {\n name: 'Aeschylus'\n profile_id: 'baz'\n }\n ", "end": 2467, "score": 0.999767005443573, "start": 2458, "tag": "NAME", "value": "Aeschylus" }, { "context": " }\n ],\n author: {\n name: 'Artsy Editorial'\n profile_id: '5086df078523e60002000009'", "end": 2572, "score": 0.9998348951339722, "start": 2557, "tag": "NAME", "value": "Artsy Editorial" }, { "context": "ticle)\n rendered.should.containEql '<address>James</address>'\n rendered.should.containEql '<add", "end": 2743, "score": 0.9809008836746216, "start": 2738, "tag": "NAME", "value": "James" }, { "context": " article = new Article(\n lead_paragraph: 'Andy Foobar never wanted fame.'\n )\n rendered = iaTe", "end": 3055, "score": 0.9497064352035522, "start": 3044, "tag": "NAME", "value": "Andy Foobar" }, { "context": "e: article)\n rendered.should.containEql '<h3>Andy Foobar never wanted fame.</h3>'\n\n it 'renders section", "end": 3187, "score": 0.9685531854629517, "start": 3176, "tag": "NAME", "value": "Andy Foobar" }, { "context": "tion><p>Sterling Ruby, Los Angeles, 2013. Photo by CG Watkins. Courtesy Sterling Ruby Studio and Gagosian Galle", "end": 3597, "score": 0.9996391534805298, "start": 3587, "tag": "NAME", "value": "CG Watkins" } ]
apps/rss/test/instant_articles.coffee
l2succes/force
1
_ = require 'underscore' fs = require 'fs' iasTemplate = require('jade').compileFile(require.resolve '../templates/instant_articles.jade') iaTemplate = require('jade').compileFile(require.resolve '../templates/instant_article.jade') sd = APP_URL: 'http://localhost' { fabricate } = require 'antigravity' Article = require '../../../models/article' Articles = require '../../../collections/articles' moment = require 'moment' describe '/instant_articles', -> describe 'instant articles', -> it 'renders no instant articles', -> rendered = iasTemplate(sd: sd, articles: new Articles) rendered.should.containEql '<title>Artsy</title>' rendered.should.containEql '<atom:link href="http://localhost/rss/instant-articles" rel="self" type="application/rss+xml">' rendered.should.containEql '<description>Featured Artsy articles</description>' it 'renders articles', -> articles = new Articles [ new Article(title: 'Hello', published_at: new Date().toISOString(), author: name: 'Kana'), new Article(title: 'World', published_at: new Date().toISOString(), author: name: 'Kana') ] rendered = iasTemplate(sd: sd, articles: articles, moment: moment) rendered.should.containEql '<title>Artsy</title>' rendered.should.containEql '<atom:link href="http://localhost/rss/instant-articles" rel="self" type="application/rss+xml">' rendered.should.containEql '<description>Featured Artsy articles</description>' rendered.should.containEql '<item><title>Hello</title>' rendered.should.containEql '<item><title>World</title>' describe 'article', -> it 'renders contributing authors and their profiles by default', -> article = new Article( contributing_authors: [{ name: 'James' profile_id: 'foo' }], author: { name: 'Artsy Editorial' profile_id: '5086df078523e60002000009' } ) rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql '<address>James</address>' rendered.should.containEql '<address>Artsy Editorial</address>' it 'renders multiple contributing authors and their profiles', -> article = new Article( contributing_authors: [ { name: 'James' profile_id: 'foo' }, { name: 'Plato' profile_id: 'bar' }, { name: 'Aeschylus' profile_id: 'baz' } ], author: { name: 'Artsy Editorial' profile_id: '5086df078523e60002000009' } ) rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql '<address>James</address>' rendered.should.containEql '<address>Artsy Editorial</address>' rendered.should.containEql '<address>Plato</address>' rendered.should.containEql '<address>Aeschylus</address>' it 'renders the lead paragraph', -> article = new Article( lead_paragraph: 'Andy Foobar never wanted fame.' ) rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql '<h3>Andy Foobar never wanted fame.</h3>' it 'renders sections', -> article = new Article fabricate 'article' rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql '<img src="https://artsy-media-uploads.s3.amazonaws.com/9-vuUwfMbo9-dibbqjZQHQ%2FSterling_Ruby_2013_%282%29.jpg"/>' rendered.should.containEql '<figcaption><p>Sterling Ruby, Los Angeles, 2013. Photo by CG Watkins. Courtesy Sterling Ruby Studio and Gagosian Gallery</p></figcaption>' rendered.should.containEql '<p>Installation view of&nbsp;“The Los Angeles Project” at Ullens Center for Contemporary Art, Beijing. Courtesy UCCA</p>' rendered.should.containEql '<a href="https://artsy.net/ucca">' it 'renders a signup embed for every article', -> article = new Article fabricate 'article' rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql 'link.artsy.net/join/sign-up-editorial-facebook' it 'renders the description', -> articles = new Articles [ new Article _.extend fabricate 'article', description: 'A piece about the Whitney.' ] rendered = iasTemplate(sd: sd, articles: articles) rendered.should.containEql '<description>A piece about the Whitney.</description>'
126329
_ = require 'underscore' fs = require 'fs' iasTemplate = require('jade').compileFile(require.resolve '../templates/instant_articles.jade') iaTemplate = require('jade').compileFile(require.resolve '../templates/instant_article.jade') sd = APP_URL: 'http://localhost' { fabricate } = require 'antigravity' Article = require '../../../models/article' Articles = require '../../../collections/articles' moment = require 'moment' describe '/instant_articles', -> describe 'instant articles', -> it 'renders no instant articles', -> rendered = iasTemplate(sd: sd, articles: new Articles) rendered.should.containEql '<title>Artsy</title>' rendered.should.containEql '<atom:link href="http://localhost/rss/instant-articles" rel="self" type="application/rss+xml">' rendered.should.containEql '<description>Featured Artsy articles</description>' it 'renders articles', -> articles = new Articles [ new Article(title: 'Hello', published_at: new Date().toISOString(), author: name: '<NAME>'), new Article(title: 'World', published_at: new Date().toISOString(), author: name: '<NAME>') ] rendered = iasTemplate(sd: sd, articles: articles, moment: moment) rendered.should.containEql '<title>Artsy</title>' rendered.should.containEql '<atom:link href="http://localhost/rss/instant-articles" rel="self" type="application/rss+xml">' rendered.should.containEql '<description>Featured Artsy articles</description>' rendered.should.containEql '<item><title>Hello</title>' rendered.should.containEql '<item><title>World</title>' describe 'article', -> it 'renders contributing authors and their profiles by default', -> article = new Article( contributing_authors: [{ name: '<NAME>' profile_id: 'foo' }], author: { name: '<NAME>' profile_id: '5086df078523e60002000009' } ) rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql '<address><NAME></address>' rendered.should.containEql '<address>Artsy Editorial</address>' it 'renders multiple contributing authors and their profiles', -> article = new Article( contributing_authors: [ { name: '<NAME>' profile_id: 'foo' }, { name: '<NAME>' profile_id: 'bar' }, { name: '<NAME>' profile_id: 'baz' } ], author: { name: '<NAME>' profile_id: '5086df078523e60002000009' } ) rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql '<address><NAME></address>' rendered.should.containEql '<address>Artsy Editorial</address>' rendered.should.containEql '<address>Plato</address>' rendered.should.containEql '<address>Aeschylus</address>' it 'renders the lead paragraph', -> article = new Article( lead_paragraph: '<NAME> never wanted fame.' ) rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql '<h3><NAME> never wanted fame.</h3>' it 'renders sections', -> article = new Article fabricate 'article' rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql '<img src="https://artsy-media-uploads.s3.amazonaws.com/9-vuUwfMbo9-dibbqjZQHQ%2FSterling_Ruby_2013_%282%29.jpg"/>' rendered.should.containEql '<figcaption><p>Sterling Ruby, Los Angeles, 2013. Photo by <NAME>. Courtesy Sterling Ruby Studio and Gagosian Gallery</p></figcaption>' rendered.should.containEql '<p>Installation view of&nbsp;“The Los Angeles Project” at Ullens Center for Contemporary Art, Beijing. Courtesy UCCA</p>' rendered.should.containEql '<a href="https://artsy.net/ucca">' it 'renders a signup embed for every article', -> article = new Article fabricate 'article' rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql 'link.artsy.net/join/sign-up-editorial-facebook' it 'renders the description', -> articles = new Articles [ new Article _.extend fabricate 'article', description: 'A piece about the Whitney.' ] rendered = iasTemplate(sd: sd, articles: articles) rendered.should.containEql '<description>A piece about the Whitney.</description>'
true
_ = require 'underscore' fs = require 'fs' iasTemplate = require('jade').compileFile(require.resolve '../templates/instant_articles.jade') iaTemplate = require('jade').compileFile(require.resolve '../templates/instant_article.jade') sd = APP_URL: 'http://localhost' { fabricate } = require 'antigravity' Article = require '../../../models/article' Articles = require '../../../collections/articles' moment = require 'moment' describe '/instant_articles', -> describe 'instant articles', -> it 'renders no instant articles', -> rendered = iasTemplate(sd: sd, articles: new Articles) rendered.should.containEql '<title>Artsy</title>' rendered.should.containEql '<atom:link href="http://localhost/rss/instant-articles" rel="self" type="application/rss+xml">' rendered.should.containEql '<description>Featured Artsy articles</description>' it 'renders articles', -> articles = new Articles [ new Article(title: 'Hello', published_at: new Date().toISOString(), author: name: 'PI:NAME:<NAME>END_PI'), new Article(title: 'World', published_at: new Date().toISOString(), author: name: 'PI:NAME:<NAME>END_PI') ] rendered = iasTemplate(sd: sd, articles: articles, moment: moment) rendered.should.containEql '<title>Artsy</title>' rendered.should.containEql '<atom:link href="http://localhost/rss/instant-articles" rel="self" type="application/rss+xml">' rendered.should.containEql '<description>Featured Artsy articles</description>' rendered.should.containEql '<item><title>Hello</title>' rendered.should.containEql '<item><title>World</title>' describe 'article', -> it 'renders contributing authors and their profiles by default', -> article = new Article( contributing_authors: [{ name: 'PI:NAME:<NAME>END_PI' profile_id: 'foo' }], author: { name: 'PI:NAME:<NAME>END_PI' profile_id: '5086df078523e60002000009' } ) rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql '<address>PI:NAME:<NAME>END_PI</address>' rendered.should.containEql '<address>Artsy Editorial</address>' it 'renders multiple contributing authors and their profiles', -> article = new Article( contributing_authors: [ { name: 'PI:NAME:<NAME>END_PI' profile_id: 'foo' }, { name: 'PI:NAME:<NAME>END_PI' profile_id: 'bar' }, { name: 'PI:NAME:<NAME>END_PI' profile_id: 'baz' } ], author: { name: 'PI:NAME:<NAME>END_PI' profile_id: '5086df078523e60002000009' } ) rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql '<address>PI:NAME:<NAME>END_PI</address>' rendered.should.containEql '<address>Artsy Editorial</address>' rendered.should.containEql '<address>Plato</address>' rendered.should.containEql '<address>Aeschylus</address>' it 'renders the lead paragraph', -> article = new Article( lead_paragraph: 'PI:NAME:<NAME>END_PI never wanted fame.' ) rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql '<h3>PI:NAME:<NAME>END_PI never wanted fame.</h3>' it 'renders sections', -> article = new Article fabricate 'article' rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql '<img src="https://artsy-media-uploads.s3.amazonaws.com/9-vuUwfMbo9-dibbqjZQHQ%2FSterling_Ruby_2013_%282%29.jpg"/>' rendered.should.containEql '<figcaption><p>Sterling Ruby, Los Angeles, 2013. Photo by PI:NAME:<NAME>END_PI. Courtesy Sterling Ruby Studio and Gagosian Gallery</p></figcaption>' rendered.should.containEql '<p>Installation view of&nbsp;“The Los Angeles Project” at Ullens Center for Contemporary Art, Beijing. Courtesy UCCA</p>' rendered.should.containEql '<a href="https://artsy.net/ucca">' it 'renders a signup embed for every article', -> article = new Article fabricate 'article' rendered = iaTemplate(sd: sd, article: article) rendered.should.containEql 'link.artsy.net/join/sign-up-editorial-facebook' it 'renders the description', -> articles = new Articles [ new Article _.extend fabricate 'article', description: 'A piece about the Whitney.' ] rendered = iasTemplate(sd: sd, articles: articles) rendered.should.containEql '<description>A piece about the Whitney.</description>'
[ { "context": "ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(\n\t\t(?:1(?:[\\s\\xa0]*Giovanni|John|[\\s\\xa0]*Gv)|(?:1\\xB0|I)[\\s\\xa0]*Giovanni|(?", "end": 14954, "score": 0.9063640236854553, "start": 14946, "tag": "NAME", "value": "Giovanni" }, { "context": "ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(\n\t\t(?:1(?:[\\s\\xa0]*Giovanni|John|[\\s\\xa0]*Gv)|(?:1\\xB0|I)[\\s\\xa0]*Giovanni|(?:1\\xB", "end": 14959, "score": 0.9512500166893005, "start": 14955, "tag": "NAME", "value": "John" }, { "context": "ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(\n\t\t(?:2(?:[\\s\\xa0]*Giovanni|John|[\\s\\xa0]*Gv)|(?:2\\xB0|II)[\\s\\xa0]*Giovanni|(", "end": 15300, "score": 0.9993845224380493, "start": 15292, "tag": "NAME", "value": "Giovanni" }, { "context": "ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(\n\t\t(?:2(?:[\\s\\xa0]*Giovanni|John|[\\s\\xa0]*Gv)|(?:2\\xB0|II)[\\s\\xa0]*Giovanni|(?:2\\x", "end": 15305, "score": 0.9995911717414856, "start": 15301, "tag": "NAME", "value": "John" }, { "context": "]*Giovanni|John|[\\s\\xa0]*Gv)|(?:2\\xB0|II)[\\s\\xa0]*Giovanni|(?:2\\xB0?|II)\\.[\\s\\xa0]*Giovanni|Second(?:a[\\s\\x", "end": 15347, "score": 0.8539056777954102, "start": 15340, "tag": "NAME", "value": "Giovann" }, { "context": "\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\n\t,\n\t\tosis: [\"3John\"]\n\t\tregexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-", "end": 15557, "score": 0.5087331533432007, "start": 15553, "tag": "NAME", "value": "John" }, { "context": "ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(\n\t\t(?:3(?:[\\s\\xa0]*Giovanni|John|[\\s\\xa0]*Gv)|(?:3\\xB0|III)[\\s\\xa0]*Giovanni|", "end": 15650, "score": 0.9987294673919678, "start": 15642, "tag": "NAME", "value": "Giovanni" }, { "context": "ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(\n\t\t(?:3(?:[\\s\\xa0]*Giovanni|John|[\\s\\xa0]*Gv)|(?:3\\xB0|III)[\\s\\xa0]*Giovanni|(?:3\\", "end": 15655, "score": 0.9996497631072998, "start": 15651, "tag": "NAME", "value": "John" }, { "context": "Giovanni|John|[\\s\\xa0]*Gv)|(?:3\\xB0|III)[\\s\\xa0]*Giovanni|(?:3\\xB0?|III)\\.[\\s\\xa0]*Giovanni|Terz(?:a[\\s", "end": 15695, "score": 0.9456769227981567, "start": 15692, "tag": "NAME", "value": "iov" }, { "context": "\\xa0]*(?:lettera[\\s\\xa0]*di[\\s\\xa0]*)?|o[\\s\\xa0]*)Giovanni)\n\t\t\t)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)\\uff0", "end": 15796, "score": 0.5532483458518982, "start": 15795, "tag": "NAME", "value": "G" }, { "context": "\n\t\t(?:Vangelo[\\s\\xa0]*di[\\s\\xa0]*(?:San[\\s\\xa0]*)?Giovanni|Giovanni|John|Gv)\n\t\t\t)(?:(?=[\\d\\s\\xa0.:,;\\x1e", "end": 16012, "score": 0.7189191579818726, "start": 16008, "tag": "NAME", "value": "Giov" }, { "context": "gelo[\\s\\xa0]*di[\\s\\xa0]*(?:San[\\s\\xa0]*)?Giovanni|Giovanni|John|Gv)\n\t\t\t)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\", "end": 16018, "score": 0.7756569385528564, "start": 16017, "tag": "NAME", "value": "G" } ]
lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/it/regexps.coffee
saiba-mais/bible-lessons
149
bcv_parser::regexps.space = "[\\s\\xa0]" bcv_parser::regexps.escaped_passage = /// (?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3` ( # Start inverted book/chapter (cb) (?: (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: \d+ (?: th | nd | st ) \s* ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter (?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* ) )? # End inverted book/chapter (cb) \x1f(\d+)(?:/\d+)?\x1f #book (?: /\d+\x1f #special Psalm chapters | [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014] | titolo (?! [a-z] ) #could be followed by a number | vedi#{bcv_parser::regexps.space}+anche | ,#{bcv_parser::regexps.space}+ecc | capitoli | capitolo | versetto | versetti | versi | capp | vedi | cap | ecc | cfr | cc | ss | al | vv | e | v | [a-d] (?! \w ) #a-e allows 1:1a | $ #or the end of the string )+ ) ///gi # These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff. bcv_parser::regexps.match_end_split = /// \d \W* titolo | \d \W* (?:ss|,#{bcv_parser::regexps.space}+ecc|ecc) (?: [\s\xa0*]* \.)? | \d [\s\xa0*]* [a-d] (?! \w ) | \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis | [\d\x1f] ///gi bcv_parser::regexps.control = /[\x1e\x1f]/g bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]" bcv_parser::regexps.first = "(?:Primo|Prima|1°|1|I)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.second = "(?:Secondo|Seconda|2°|2|II)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.third = "(?:Terzo|Terza|3°|3|III)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:vedi#{bcv_parser::regexps.space}+anche|vedi|cfr|e)|al)" bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|al)" # Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself. bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) -> books = [ osis: ["Ps"] apocrypha: true extra: "2" regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit. Ps151 # Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own. )(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS. , osis: ["Gen"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ge(?:n(?:esi)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Exod"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:E(?:s(?:odo)?|xod)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bel"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bel(?:[\s\xa0]*e[\s\xa0]*il[\s\xa0]*Drago)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:L(?:e(?:v(?:itico)?)?|v)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Num"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:N(?:u(?:m(?:eri)?)?|m)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sir"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:S(?:apienza[\s\xa0]*di[\s\xa0]*Sirac(?:ide|h)|ir(?:[a\xE0]cide)?)|Ecclesiastico) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Wis"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sap(?:ienza(?:[\s\xa0]*di[\s\xa0]*Salomone)?)?|Wis) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lam"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:La(?:m(?:entazioni)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["EpJer"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Let(?:tera[\s\xa0]*di[\s\xa0]*Geremia|\-?ger)|EpJer) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ap(?:ocalisse(?:[\s\xa0]*di[\s\xa0]*Giovanni)?)?|R(?:ivelazione|ev|iv)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrMan"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Orazione[\s\xa0]*di[\s\xa0]*Manasse(?:[\s\xa0]*Re[\s\xa0]*di[\s\xa0]*Giuda)?|Pr(?:eghiera[\s\xa0]*di[\s\xa0]*Manasse|Man)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Deut"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:D(?:e(?:ut(?:eronomio)?)?|t)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Josh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:iosu[e\xE8\xE9]|s)|Josh) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Judg"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:iudici|dc)|Judg) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ruth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:R(?:u(?:th?)?|t)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Esdras?)|(?:(?:3\xB0?|III)[\s\xa0]*Esdra|1[\s\xa0]*?Esd|(?:3\xB0?|III)\.[\s\xa0]*Esdra|Terz[ao][\s\xa0]*Esdra|Esdra[\s\xa0]*greco|1[\s\xa0]*\xC9sdras|(?:1\xB0|I)[\s\xa0]*(?:\xC9sdras|Esdras?)|(?:1\xB0?|I)\.[\s\xa0]*(?:\xC9sdras|Esdras?)|Prim[ao][\s\xa0]*(?:\xC9sdras|Esdras?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Esdras?)|(?:(?:4\xB0?|IV)[\s\xa0]*Esdra|2[\s\xa0]*?Esd|(?:4\xB0?|IV)\.[\s\xa0]*Esdra|Quart[ao][\s\xa0]*Esdra|2[\s\xa0]*\xC9sdras|(?:2\xB0|II)[\s\xa0]*(?:\xC9sdras|Esdras?)|(?:2\xB0?|II)\.[\s\xa0]*(?:\xC9sdras|Esdras?)|Second[ao][\s\xa0]*(?:\xC9sdras|Esdras?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Isa"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Is(?:a(?:ia)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Samuele)|(?:(?:2\xB0|II)[\s\xa0]*Samuele|2(?:[\s\xa0]*?Sam|[\s\xa0]*S)|(?:2\xB0?|II)\.[\s\xa0]*Samuele|Second[ao][\s\xa0]*Samuele) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Samuele)|(?:(?:1\xB0|I)[\s\xa0]*Samuele|1(?:[\s\xa0]*?Sam|[\s\xa0]*S)|(?:1\xB0?|I)\.[\s\xa0]*Samuele|Prim[ao][\s\xa0]*Samuele) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Re|Kgs|[\s\xa0]*R)|(?:2\xB0|II)[\s\xa0]*Re|(?:2\xB0?|II)\.[\s\xa0]*Re|Second[ao][\s\xa0]*Re) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Re|Kgs|[\s\xa0]*R)|(?:1\xB0|I)[\s\xa0]*Re|(?:1\xB0?|I)\.[\s\xa0]*Re|Prim[ao][\s\xa0]*Re) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Cronache)|(?:(?:2\xB0|II)[\s\xa0]*Cronache|2(?:[\s\xa0]*C|Ch)r|(?:2\xB0?|II)\.[\s\xa0]*Cronache|Second[ao][\s\xa0]*Cronache) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Cronache)|(?:(?:1\xB0|I)[\s\xa0]*Cronache|1(?:[\s\xa0]*C|Ch)r|(?:1\xB0?|I)\.[\s\xa0]*Cronache|Prim[ao][\s\xa0]*Cronache) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:E(?:sd(?:ra)?|zra|d)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Neh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ne(?:emia|h)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["GkEsth"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ester[\s\xa0]*(?:\((?:versione[\s\xa0]*greca|greco)\)|greco)|GkEsth) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Esth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:E(?:st(?:er|h)?|t)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Job"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:iobbe|b)|Job) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ps"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:S(?:al(?:m[io])?|l)|Ps) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrAzar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Pr(?:eghiera[\s\xa0]*di[\s\xa0]*Azaria|Azar)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Prov"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Pr(?:ov(?:erbi)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eccl"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Qo(?:(?:h[e\xE8]|[e\xE8])let)?|Ec(?:c(?:l(?:esiaste)?)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["SgThree"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Cantico[\s\xa0]*dei[\s\xa0]*tre[\s\xa0]*(?:giovani[\s\xa0]*nella[\s\xa0]*fornace|fanciulli)|SgThree) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Song"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:C(?:a(?:ntico(?:[\s\xa0]*d(?:ei[\s\xa0]*[Cc]antici|i[\s\xa0]*Salomone))?)?|t)|Song) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jer"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:eremia|r|er)|Jer(?:emiah)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ez(?:e(?:chiele|k))?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Dan"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:D(?:a(?:n(?:iele)?)?|n)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Os(?:ea)?|Hos) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Joel"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:ioe(?:le)?|l)|Joel) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Amos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Am(?:os)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Obad"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:O(?:vadia|bad)|A(?:bdia|b?d)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jonah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:io(?:na)?|n)|Jonah) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mic"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mi(?:c(?:hea)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Nah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Na(?:h(?:um)?|um)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hab"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:A(?:b(?:acuc)?|c)|Hab) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zeph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:So(?:f(?:onia)?)?|Zeph) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hag"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ag(?:geo)?|Hag) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zech"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Z(?:a(?:c(?:caria)?)?|ech|c)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:M(?:al(?:achia)?|l)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Matt"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Matteo)|(?:Vangelo[\s\xa0]*di[\s\xa0]*(?:San[\s\xa0]*)?Matteo|M(?:at)?t) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mark"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Vangelo[\s\xa0]*di[\s\xa0]*(?:San[\s\xa0]*)?Marco|M(?:[cr]|ark|arco)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Luke"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Luca)|(?:Vangelo[\s\xa0]*di[\s\xa0]*(?:San[\s\xa0]*)?Luca|L(?:uke|c|u)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Giovanni|John|[\s\xa0]*Gv)|(?:1\xB0|I)[\s\xa0]*Giovanni|(?:1\xB0?|I)\.[\s\xa0]*Giovanni|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)Giovanni) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Giovanni|John|[\s\xa0]*Gv)|(?:2\xB0|II)[\s\xa0]*Giovanni|(?:2\xB0?|II)\.[\s\xa0]*Giovanni|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)Giovanni) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3(?:[\s\xa0]*Giovanni|John|[\s\xa0]*Gv)|(?:3\xB0|III)[\s\xa0]*Giovanni|(?:3\xB0?|III)\.[\s\xa0]*Giovanni|Terz(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)Giovanni) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["John"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Vangelo[\s\xa0]*di[\s\xa0]*(?:San[\s\xa0]*)?Giovanni|Giovanni|John|Gv) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Acts"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:A(?:t(?:ti(?:[\s\xa0]*degli[\s\xa0]*Apostoli)?)?|cts)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rom"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Romani)|(?:Lettera[\s\xa0]*ai[\s\xa0]*Romani|R(?:o?m|o)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Corinzi)|(?:(?:2\xB0|II)[\s\xa0]*Corinzi|2(?:[\s\xa0]*?Cor|[\s\xa0]*Co)|(?:2\xB0?|II)\.[\s\xa0]*Corinzi|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*ai[\s\xa0]*)?|o[\s\xa0]*)Corinzi) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Corinzi)|(?:(?:1\xB0|I)[\s\xa0]*Corinzi|1(?:[\s\xa0]*?Cor|[\s\xa0]*Co)|(?:1\xB0?|I)\.[\s\xa0]*Corinzi|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*ai[\s\xa0]*)?|o[\s\xa0]*)Corinzi) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Gal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:a(?:lati|l)?|\xE0lati)|Lettera[\s\xa0]*ai[\s\xa0]*Galati) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lettera[\s\xa0]*agli[\s\xa0]*Efesini|E(?:fesini|ph|f)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phil"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Filippesi)|(?:Lettera[\s\xa0]*ai[\s\xa0]*Filippesi|(?:Fi?|Phi)l) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Col"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lettera[\s\xa0]*ai[\s\xa0]*Colossesi|C(?:olossesi|o?l)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Tessalonicesi)|(?:(?:2\xB0|II)[\s\xa0]*Tessalonicesi|2(?:[\s\xa0]*T[es]|Thess)|(?:2\xB0?|II)\.[\s\xa0]*Tessalonicesi|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*ai[\s\xa0]*)?|o[\s\xa0]*)Tessalonicesi) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Tessalonicesi)|(?:(?:1\xB0|I)[\s\xa0]*Tessalonicesi|1(?:[\s\xa0]*T[es]|Thess)|(?:1\xB0?|I)\.[\s\xa0]*Tessalonicesi|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*ai[\s\xa0]*)?|o[\s\xa0]*)Tessalonicesi) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Timoteo)|(?:2(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:2\xB0|II)[\s\xa0]*Timoteo|(?:2\xB0?|II)\.[\s\xa0]*Timoteo|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*a[\s\xa0]*)?|o[\s\xa0]*)Timoteo) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Timoteo)|(?:1(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:1\xB0|I)[\s\xa0]*Timoteo|(?:1\xB0?|I)\.[\s\xa0]*Timoteo|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*a[\s\xa0]*)?|o[\s\xa0]*)Timoteo) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Titus"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:T(?:it(?:us|o)|t)|Lettera[\s\xa0]*a[\s\xa0]*Tito) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phlm"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Fil[e\xE8]mone)|(?:Lettera[\s\xa0]*a[\s\xa0]*Filemone|F[im]|Phlm) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Heb"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ebrei)|(?:Lettera[\s\xa0]*agli[\s\xa0]*Ebrei|(?:He|E)b) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jas"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lettera[\s\xa0]*di[\s\xa0]*Giacomo|G[cm]|Jas|Giacomo) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Pietro)|(?:(?:2\xB0|II)[\s\xa0]*Pietro|2(?:(?:[\s\xa0]*P|Pe)t|[\s\xa0]*P)|(?:2\xB0?|II)\.[\s\xa0]*Pietro|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)Pietro) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Pietro)|(?:1(?:(?:[\s\xa0]*P|Pe)t|[\s\xa0]*P)|(?:1\xB0|I)[\s\xa0]*Pietro|(?:1\xB0?|I)\.[\s\xa0]*Pietro|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)Pietro) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jude"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lettera[\s\xa0]*di[\s\xa0]*Giuda|Jude|Gd|Giuda) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Tob"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:T(?:ob(?:i(?:olo|a)?)?|b)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jdt"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:iuditta|dt)|Jdt) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bar(?:uch?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sus"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:S(?:toria[\s\xa0]*di[\s\xa0]*Susanna|us(?:anna)?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Maccabei|Macc))|(?:(?:2\xB0|II)[\s\xa0]*Maccabei|2[\s\xa0]*Mac|(?:2\xB0?|II)\.[\s\xa0]*Maccabei|Second(?:o[\s\xa0]*(?:libro[\s\xa0]*dei[\s\xa0]*)?|a[\s\xa0]*)Maccabei) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3(?:[\s\xa0]*Maccabei|Macc))|(?:(?:3\xB0|III)[\s\xa0]*Maccabei|3[\s\xa0]*Mac|(?:3\xB0?|III)\.[\s\xa0]*Maccabei|Terz(?:o[\s\xa0]*(?:libro[\s\xa0]*dei[\s\xa0]*)?|a[\s\xa0]*)Maccabei) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["4Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:4(?:[\s\xa0]*Maccabei|Macc))|(?:(?:4\xB0|IV)[\s\xa0]*Maccabei|4[\s\xa0]*Mac|(?:4\xB0?|IV)\.[\s\xa0]*Maccabei|Quart(?:o[\s\xa0]*(?:libro[\s\xa0]*dei[\s\xa0]*)?|a[\s\xa0]*)Maccabei) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Maccabei|Macc))|(?:(?:1\xB0|I)[\s\xa0]*Maccabei|1[\s\xa0]*Mac|(?:1\xB0?|I)\.[\s\xa0]*Maccabei|Prim(?:o[\s\xa0]*(?:libro[\s\xa0]*dei[\s\xa0]*)?|a[\s\xa0]*)Maccabei) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi ] # Short-circuit the look if we know we want all the books. return books if include_apocrypha is true and case_sensitive is "none" # Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9. out = [] for book in books continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true if case_sensitive is "books" book.regexp = new RegExp book.regexp.source, "g" out.push book out # Default to not using the Apocrypha bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
154367
bcv_parser::regexps.space = "[\\s\\xa0]" bcv_parser::regexps.escaped_passage = /// (?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3` ( # Start inverted book/chapter (cb) (?: (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: \d+ (?: th | nd | st ) \s* ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter (?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* ) )? # End inverted book/chapter (cb) \x1f(\d+)(?:/\d+)?\x1f #book (?: /\d+\x1f #special Psalm chapters | [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014] | titolo (?! [a-z] ) #could be followed by a number | vedi#{bcv_parser::regexps.space}+anche | ,#{bcv_parser::regexps.space}+ecc | capitoli | capitolo | versetto | versetti | versi | capp | vedi | cap | ecc | cfr | cc | ss | al | vv | e | v | [a-d] (?! \w ) #a-e allows 1:1a | $ #or the end of the string )+ ) ///gi # These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff. bcv_parser::regexps.match_end_split = /// \d \W* titolo | \d \W* (?:ss|,#{bcv_parser::regexps.space}+ecc|ecc) (?: [\s\xa0*]* \.)? | \d [\s\xa0*]* [a-d] (?! \w ) | \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis | [\d\x1f] ///gi bcv_parser::regexps.control = /[\x1e\x1f]/g bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]" bcv_parser::regexps.first = "(?:Primo|Prima|1°|1|I)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.second = "(?:Secondo|Seconda|2°|2|II)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.third = "(?:Terzo|Terza|3°|3|III)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:vedi#{bcv_parser::regexps.space}+anche|vedi|cfr|e)|al)" bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|al)" # Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself. bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) -> books = [ osis: ["Ps"] apocrypha: true extra: "2" regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit. Ps151 # Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own. )(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS. , osis: ["Gen"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ge(?:n(?:esi)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Exod"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:E(?:s(?:odo)?|xod)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bel"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bel(?:[\s\xa0]*e[\s\xa0]*il[\s\xa0]*Drago)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:L(?:e(?:v(?:itico)?)?|v)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Num"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:N(?:u(?:m(?:eri)?)?|m)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sir"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:S(?:apienza[\s\xa0]*di[\s\xa0]*Sirac(?:ide|h)|ir(?:[a\xE0]cide)?)|Ecclesiastico) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Wis"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sap(?:ienza(?:[\s\xa0]*di[\s\xa0]*Salomone)?)?|Wis) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lam"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:La(?:m(?:entazioni)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["EpJer"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Let(?:tera[\s\xa0]*di[\s\xa0]*Geremia|\-?ger)|EpJer) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ap(?:ocalisse(?:[\s\xa0]*di[\s\xa0]*Giovanni)?)?|R(?:ivelazione|ev|iv)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrMan"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Orazione[\s\xa0]*di[\s\xa0]*Manasse(?:[\s\xa0]*Re[\s\xa0]*di[\s\xa0]*Giuda)?|Pr(?:eghiera[\s\xa0]*di[\s\xa0]*Manasse|Man)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Deut"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:D(?:e(?:ut(?:eronomio)?)?|t)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Josh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:iosu[e\xE8\xE9]|s)|Josh) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Judg"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:iudici|dc)|Judg) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ruth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:R(?:u(?:th?)?|t)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Esdras?)|(?:(?:3\xB0?|III)[\s\xa0]*Esdra|1[\s\xa0]*?Esd|(?:3\xB0?|III)\.[\s\xa0]*Esdra|Terz[ao][\s\xa0]*Esdra|Esdra[\s\xa0]*greco|1[\s\xa0]*\xC9sdras|(?:1\xB0|I)[\s\xa0]*(?:\xC9sdras|Esdras?)|(?:1\xB0?|I)\.[\s\xa0]*(?:\xC9sdras|Esdras?)|Prim[ao][\s\xa0]*(?:\xC9sdras|Esdras?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Esdras?)|(?:(?:4\xB0?|IV)[\s\xa0]*Esdra|2[\s\xa0]*?Esd|(?:4\xB0?|IV)\.[\s\xa0]*Esdra|Quart[ao][\s\xa0]*Esdra|2[\s\xa0]*\xC9sdras|(?:2\xB0|II)[\s\xa0]*(?:\xC9sdras|Esdras?)|(?:2\xB0?|II)\.[\s\xa0]*(?:\xC9sdras|Esdras?)|Second[ao][\s\xa0]*(?:\xC9sdras|Esdras?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Isa"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Is(?:a(?:ia)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Samuele)|(?:(?:2\xB0|II)[\s\xa0]*Samuele|2(?:[\s\xa0]*?Sam|[\s\xa0]*S)|(?:2\xB0?|II)\.[\s\xa0]*Samuele|Second[ao][\s\xa0]*Samuele) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Samuele)|(?:(?:1\xB0|I)[\s\xa0]*Samuele|1(?:[\s\xa0]*?Sam|[\s\xa0]*S)|(?:1\xB0?|I)\.[\s\xa0]*Samuele|Prim[ao][\s\xa0]*Samuele) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Re|Kgs|[\s\xa0]*R)|(?:2\xB0|II)[\s\xa0]*Re|(?:2\xB0?|II)\.[\s\xa0]*Re|Second[ao][\s\xa0]*Re) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Re|Kgs|[\s\xa0]*R)|(?:1\xB0|I)[\s\xa0]*Re|(?:1\xB0?|I)\.[\s\xa0]*Re|Prim[ao][\s\xa0]*Re) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Cronache)|(?:(?:2\xB0|II)[\s\xa0]*Cronache|2(?:[\s\xa0]*C|Ch)r|(?:2\xB0?|II)\.[\s\xa0]*Cronache|Second[ao][\s\xa0]*Cronache) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Cronache)|(?:(?:1\xB0|I)[\s\xa0]*Cronache|1(?:[\s\xa0]*C|Ch)r|(?:1\xB0?|I)\.[\s\xa0]*Cronache|Prim[ao][\s\xa0]*Cronache) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:E(?:sd(?:ra)?|zra|d)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Neh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ne(?:emia|h)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["GkEsth"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ester[\s\xa0]*(?:\((?:versione[\s\xa0]*greca|greco)\)|greco)|GkEsth) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Esth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:E(?:st(?:er|h)?|t)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Job"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:iobbe|b)|Job) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ps"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:S(?:al(?:m[io])?|l)|Ps) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrAzar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Pr(?:eghiera[\s\xa0]*di[\s\xa0]*Azaria|Azar)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Prov"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Pr(?:ov(?:erbi)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eccl"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Qo(?:(?:h[e\xE8]|[e\xE8])let)?|Ec(?:c(?:l(?:esiaste)?)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["SgThree"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Cantico[\s\xa0]*dei[\s\xa0]*tre[\s\xa0]*(?:giovani[\s\xa0]*nella[\s\xa0]*fornace|fanciulli)|SgThree) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Song"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:C(?:a(?:ntico(?:[\s\xa0]*d(?:ei[\s\xa0]*[Cc]antici|i[\s\xa0]*Salomone))?)?|t)|Song) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jer"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:eremia|r|er)|Jer(?:emiah)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ez(?:e(?:chiele|k))?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Dan"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:D(?:a(?:n(?:iele)?)?|n)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Os(?:ea)?|Hos) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Joel"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:ioe(?:le)?|l)|Joel) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Amos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Am(?:os)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Obad"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:O(?:vadia|bad)|A(?:bdia|b?d)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jonah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:io(?:na)?|n)|Jonah) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mic"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mi(?:c(?:hea)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Nah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Na(?:h(?:um)?|um)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hab"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:A(?:b(?:acuc)?|c)|Hab) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zeph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:So(?:f(?:onia)?)?|Zeph) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hag"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ag(?:geo)?|Hag) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zech"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Z(?:a(?:c(?:caria)?)?|ech|c)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:M(?:al(?:achia)?|l)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Matt"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Matteo)|(?:Vangelo[\s\xa0]*di[\s\xa0]*(?:San[\s\xa0]*)?Matteo|M(?:at)?t) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mark"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Vangelo[\s\xa0]*di[\s\xa0]*(?:San[\s\xa0]*)?Marco|M(?:[cr]|ark|arco)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Luke"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Luca)|(?:Vangelo[\s\xa0]*di[\s\xa0]*(?:San[\s\xa0]*)?Luca|L(?:uke|c|u)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*<NAME>|<NAME>|[\s\xa0]*Gv)|(?:1\xB0|I)[\s\xa0]*Giovanni|(?:1\xB0?|I)\.[\s\xa0]*Giovanni|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)Giovanni) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*<NAME>|<NAME>|[\s\xa0]*Gv)|(?:2\xB0|II)[\s\xa0]*<NAME>i|(?:2\xB0?|II)\.[\s\xa0]*Giovanni|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)Giovanni) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3<NAME>"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3(?:[\s\xa0]*<NAME>|<NAME>|[\s\xa0]*Gv)|(?:3\xB0|III)[\s\xa0]*G<NAME>anni|(?:3\xB0?|III)\.[\s\xa0]*Giovanni|Terz(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)<NAME>iovanni) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["John"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Vangelo[\s\xa0]*di[\s\xa0]*(?:San[\s\xa0]*)?<NAME>anni|<NAME>iovanni|John|Gv) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Acts"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:A(?:t(?:ti(?:[\s\xa0]*degli[\s\xa0]*Apostoli)?)?|cts)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rom"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Romani)|(?:Lettera[\s\xa0]*ai[\s\xa0]*Romani|R(?:o?m|o)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Corinzi)|(?:(?:2\xB0|II)[\s\xa0]*Corinzi|2(?:[\s\xa0]*?Cor|[\s\xa0]*Co)|(?:2\xB0?|II)\.[\s\xa0]*Corinzi|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*ai[\s\xa0]*)?|o[\s\xa0]*)Corinzi) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Corinzi)|(?:(?:1\xB0|I)[\s\xa0]*Corinzi|1(?:[\s\xa0]*?Cor|[\s\xa0]*Co)|(?:1\xB0?|I)\.[\s\xa0]*Corinzi|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*ai[\s\xa0]*)?|o[\s\xa0]*)Corinzi) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Gal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:a(?:lati|l)?|\xE0lati)|Lettera[\s\xa0]*ai[\s\xa0]*Galati) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lettera[\s\xa0]*agli[\s\xa0]*Efesini|E(?:fesini|ph|f)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phil"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Filippesi)|(?:Lettera[\s\xa0]*ai[\s\xa0]*Filippesi|(?:Fi?|Phi)l) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Col"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lettera[\s\xa0]*ai[\s\xa0]*Colossesi|C(?:olossesi|o?l)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Tessalonicesi)|(?:(?:2\xB0|II)[\s\xa0]*Tessalonicesi|2(?:[\s\xa0]*T[es]|Thess)|(?:2\xB0?|II)\.[\s\xa0]*Tessalonicesi|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*ai[\s\xa0]*)?|o[\s\xa0]*)Tessalonicesi) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Tessalonicesi)|(?:(?:1\xB0|I)[\s\xa0]*Tessalonicesi|1(?:[\s\xa0]*T[es]|Thess)|(?:1\xB0?|I)\.[\s\xa0]*Tessalonicesi|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*ai[\s\xa0]*)?|o[\s\xa0]*)Tessalonicesi) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Timoteo)|(?:2(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:2\xB0|II)[\s\xa0]*Timoteo|(?:2\xB0?|II)\.[\s\xa0]*Timoteo|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*a[\s\xa0]*)?|o[\s\xa0]*)Timoteo) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Timoteo)|(?:1(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:1\xB0|I)[\s\xa0]*Timoteo|(?:1\xB0?|I)\.[\s\xa0]*Timoteo|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*a[\s\xa0]*)?|o[\s\xa0]*)Timoteo) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Titus"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:T(?:it(?:us|o)|t)|Lettera[\s\xa0]*a[\s\xa0]*Tito) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phlm"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Fil[e\xE8]mone)|(?:Lettera[\s\xa0]*a[\s\xa0]*Filemone|F[im]|Phlm) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Heb"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ebrei)|(?:Lettera[\s\xa0]*agli[\s\xa0]*Ebrei|(?:He|E)b) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jas"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lettera[\s\xa0]*di[\s\xa0]*Giacomo|G[cm]|Jas|Giacomo) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Pietro)|(?:(?:2\xB0|II)[\s\xa0]*Pietro|2(?:(?:[\s\xa0]*P|Pe)t|[\s\xa0]*P)|(?:2\xB0?|II)\.[\s\xa0]*Pietro|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)Pietro) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Pietro)|(?:1(?:(?:[\s\xa0]*P|Pe)t|[\s\xa0]*P)|(?:1\xB0|I)[\s\xa0]*Pietro|(?:1\xB0?|I)\.[\s\xa0]*Pietro|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)Pietro) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jude"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lettera[\s\xa0]*di[\s\xa0]*Giuda|Jude|Gd|Giuda) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Tob"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:T(?:ob(?:i(?:olo|a)?)?|b)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jdt"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:iuditta|dt)|Jdt) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bar(?:uch?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sus"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:S(?:toria[\s\xa0]*di[\s\xa0]*Susanna|us(?:anna)?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Maccabei|Macc))|(?:(?:2\xB0|II)[\s\xa0]*Maccabei|2[\s\xa0]*Mac|(?:2\xB0?|II)\.[\s\xa0]*Maccabei|Second(?:o[\s\xa0]*(?:libro[\s\xa0]*dei[\s\xa0]*)?|a[\s\xa0]*)Maccabei) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3(?:[\s\xa0]*Maccabei|Macc))|(?:(?:3\xB0|III)[\s\xa0]*Maccabei|3[\s\xa0]*Mac|(?:3\xB0?|III)\.[\s\xa0]*Maccabei|Terz(?:o[\s\xa0]*(?:libro[\s\xa0]*dei[\s\xa0]*)?|a[\s\xa0]*)Maccabei) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["4Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:4(?:[\s\xa0]*Maccabei|Macc))|(?:(?:4\xB0|IV)[\s\xa0]*Maccabei|4[\s\xa0]*Mac|(?:4\xB0?|IV)\.[\s\xa0]*Maccabei|Quart(?:o[\s\xa0]*(?:libro[\s\xa0]*dei[\s\xa0]*)?|a[\s\xa0]*)Maccabei) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Maccabei|Macc))|(?:(?:1\xB0|I)[\s\xa0]*Maccabei|1[\s\xa0]*Mac|(?:1\xB0?|I)\.[\s\xa0]*Maccabei|Prim(?:o[\s\xa0]*(?:libro[\s\xa0]*dei[\s\xa0]*)?|a[\s\xa0]*)Maccabei) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi ] # Short-circuit the look if we know we want all the books. return books if include_apocrypha is true and case_sensitive is "none" # Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9. out = [] for book in books continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true if case_sensitive is "books" book.regexp = new RegExp book.regexp.source, "g" out.push book out # Default to not using the Apocrypha bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
true
bcv_parser::regexps.space = "[\\s\\xa0]" bcv_parser::regexps.escaped_passage = /// (?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3` ( # Start inverted book/chapter (cb) (?: (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s* \d+ \s* (?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* ) | (?: \d+ (?: th | nd | st ) \s* ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter (?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* ) )? # End inverted book/chapter (cb) \x1f(\d+)(?:/\d+)?\x1f #book (?: /\d+\x1f #special Psalm chapters | [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014] | titolo (?! [a-z] ) #could be followed by a number | vedi#{bcv_parser::regexps.space}+anche | ,#{bcv_parser::regexps.space}+ecc | capitoli | capitolo | versetto | versetti | versi | capp | vedi | cap | ecc | cfr | cc | ss | al | vv | e | v | [a-d] (?! \w ) #a-e allows 1:1a | $ #or the end of the string )+ ) ///gi # These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff. bcv_parser::regexps.match_end_split = /// \d \W* titolo | \d \W* (?:ss|,#{bcv_parser::regexps.space}+ecc|ecc) (?: [\s\xa0*]* \.)? | \d [\s\xa0*]* [a-d] (?! \w ) | \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis | [\d\x1f] ///gi bcv_parser::regexps.control = /[\x1e\x1f]/g bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]" bcv_parser::regexps.first = "(?:Primo|Prima|1°|1|I)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.second = "(?:Secondo|Seconda|2°|2|II)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.third = "(?:Terzo|Terza|3°|3|III)\\.?#{bcv_parser::regexps.space}*" bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:vedi#{bcv_parser::regexps.space}+anche|vedi|cfr|e)|al)" bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|al)" # Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself. bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) -> books = [ osis: ["Ps"] apocrypha: true extra: "2" regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit. Ps151 # Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own. )(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS. , osis: ["Gen"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ge(?:n(?:esi)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Exod"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:E(?:s(?:odo)?|xod)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bel"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bel(?:[\s\xa0]*e[\s\xa0]*il[\s\xa0]*Drago)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:L(?:e(?:v(?:itico)?)?|v)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Num"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:N(?:u(?:m(?:eri)?)?|m)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sir"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:S(?:apienza[\s\xa0]*di[\s\xa0]*Sirac(?:ide|h)|ir(?:[a\xE0]cide)?)|Ecclesiastico) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Wis"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Sap(?:ienza(?:[\s\xa0]*di[\s\xa0]*Salomone)?)?|Wis) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Lam"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:La(?:m(?:entazioni)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["EpJer"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Let(?:tera[\s\xa0]*di[\s\xa0]*Geremia|\-?ger)|EpJer) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rev"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ap(?:ocalisse(?:[\s\xa0]*di[\s\xa0]*Giovanni)?)?|R(?:ivelazione|ev|iv)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrMan"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Orazione[\s\xa0]*di[\s\xa0]*Manasse(?:[\s\xa0]*Re[\s\xa0]*di[\s\xa0]*Giuda)?|Pr(?:eghiera[\s\xa0]*di[\s\xa0]*Manasse|Man)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Deut"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:D(?:e(?:ut(?:eronomio)?)?|t)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Josh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:iosu[e\xE8\xE9]|s)|Josh) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Judg"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:iudici|dc)|Judg) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ruth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:R(?:u(?:th?)?|t)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Esdras?)|(?:(?:3\xB0?|III)[\s\xa0]*Esdra|1[\s\xa0]*?Esd|(?:3\xB0?|III)\.[\s\xa0]*Esdra|Terz[ao][\s\xa0]*Esdra|Esdra[\s\xa0]*greco|1[\s\xa0]*\xC9sdras|(?:1\xB0|I)[\s\xa0]*(?:\xC9sdras|Esdras?)|(?:1\xB0?|I)\.[\s\xa0]*(?:\xC9sdras|Esdras?)|Prim[ao][\s\xa0]*(?:\xC9sdras|Esdras?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Esd"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Esdras?)|(?:(?:4\xB0?|IV)[\s\xa0]*Esdra|2[\s\xa0]*?Esd|(?:4\xB0?|IV)\.[\s\xa0]*Esdra|Quart[ao][\s\xa0]*Esdra|2[\s\xa0]*\xC9sdras|(?:2\xB0|II)[\s\xa0]*(?:\xC9sdras|Esdras?)|(?:2\xB0?|II)\.[\s\xa0]*(?:\xC9sdras|Esdras?)|Second[ao][\s\xa0]*(?:\xC9sdras|Esdras?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Isa"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Is(?:a(?:ia)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Samuele)|(?:(?:2\xB0|II)[\s\xa0]*Samuele|2(?:[\s\xa0]*?Sam|[\s\xa0]*S)|(?:2\xB0?|II)\.[\s\xa0]*Samuele|Second[ao][\s\xa0]*Samuele) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Sam"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Samuele)|(?:(?:1\xB0|I)[\s\xa0]*Samuele|1(?:[\s\xa0]*?Sam|[\s\xa0]*S)|(?:1\xB0?|I)\.[\s\xa0]*Samuele|Prim[ao][\s\xa0]*Samuele) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Re|Kgs|[\s\xa0]*R)|(?:2\xB0|II)[\s\xa0]*Re|(?:2\xB0?|II)\.[\s\xa0]*Re|Second[ao][\s\xa0]*Re) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Kgs"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Re|Kgs|[\s\xa0]*R)|(?:1\xB0|I)[\s\xa0]*Re|(?:1\xB0?|I)\.[\s\xa0]*Re|Prim[ao][\s\xa0]*Re) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Cronache)|(?:(?:2\xB0|II)[\s\xa0]*Cronache|2(?:[\s\xa0]*C|Ch)r|(?:2\xB0?|II)\.[\s\xa0]*Cronache|Second[ao][\s\xa0]*Cronache) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Chr"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Cronache)|(?:(?:1\xB0|I)[\s\xa0]*Cronache|1(?:[\s\xa0]*C|Ch)r|(?:1\xB0?|I)\.[\s\xa0]*Cronache|Prim[ao][\s\xa0]*Cronache) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezra"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:E(?:sd(?:ra)?|zra|d)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Neh"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ne(?:emia|h)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["GkEsth"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ester[\s\xa0]*(?:\((?:versione[\s\xa0]*greca|greco)\)|greco)|GkEsth) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Esth"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:E(?:st(?:er|h)?|t)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Job"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:iobbe|b)|Job) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ps"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:S(?:al(?:m[io])?|l)|Ps) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["PrAzar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Pr(?:eghiera[\s\xa0]*di[\s\xa0]*Azaria|Azar)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Prov"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Pr(?:ov(?:erbi)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eccl"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Qo(?:(?:h[e\xE8]|[e\xE8])let)?|Ec(?:c(?:l(?:esiaste)?)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["SgThree"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Cantico[\s\xa0]*dei[\s\xa0]*tre[\s\xa0]*(?:giovani[\s\xa0]*nella[\s\xa0]*fornace|fanciulli)|SgThree) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Song"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:C(?:a(?:ntico(?:[\s\xa0]*d(?:ei[\s\xa0]*[Cc]antici|i[\s\xa0]*Salomone))?)?|t)|Song) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jer"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:eremia|r|er)|Jer(?:emiah)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Ezek"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ez(?:e(?:chiele|k))?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Dan"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:D(?:a(?:n(?:iele)?)?|n)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Os(?:ea)?|Hos) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Joel"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:ioe(?:le)?|l)|Joel) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Amos"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Am(?:os)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Obad"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:O(?:vadia|bad)|A(?:bdia|b?d)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jonah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:io(?:na)?|n)|Jonah) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mic"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Mi(?:c(?:hea)?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Nah"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Na(?:h(?:um)?|um)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hab"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:A(?:b(?:acuc)?|c)|Hab) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zeph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:So(?:f(?:onia)?)?|Zeph) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Hag"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ag(?:geo)?|Hag) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Zech"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Z(?:a(?:c(?:caria)?)?|ech|c)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:M(?:al(?:achia)?|l)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Matt"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Matteo)|(?:Vangelo[\s\xa0]*di[\s\xa0]*(?:San[\s\xa0]*)?Matteo|M(?:at)?t) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Mark"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Vangelo[\s\xa0]*di[\s\xa0]*(?:San[\s\xa0]*)?Marco|M(?:[cr]|ark|arco)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Luke"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Luca)|(?:Vangelo[\s\xa0]*di[\s\xa0]*(?:San[\s\xa0]*)?Luca|L(?:uke|c|u)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*PI:NAME:<NAME>END_PI|PI:NAME:<NAME>END_PI|[\s\xa0]*Gv)|(?:1\xB0|I)[\s\xa0]*Giovanni|(?:1\xB0?|I)\.[\s\xa0]*Giovanni|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)Giovanni) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2John"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*PI:NAME:<NAME>END_PI|PI:NAME:<NAME>END_PI|[\s\xa0]*Gv)|(?:2\xB0|II)[\s\xa0]*PI:NAME:<NAME>END_PIi|(?:2\xB0?|II)\.[\s\xa0]*Giovanni|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)Giovanni) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3PI:NAME:<NAME>END_PI"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3(?:[\s\xa0]*PI:NAME:<NAME>END_PI|PI:NAME:<NAME>END_PI|[\s\xa0]*Gv)|(?:3\xB0|III)[\s\xa0]*GPI:NAME:<NAME>END_PIanni|(?:3\xB0?|III)\.[\s\xa0]*Giovanni|Terz(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)PI:NAME:<NAME>END_PIiovanni) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["John"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Vangelo[\s\xa0]*di[\s\xa0]*(?:San[\s\xa0]*)?PI:NAME:<NAME>END_PIanni|PI:NAME:<NAME>END_PIiovanni|John|Gv) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Acts"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:A(?:t(?:ti(?:[\s\xa0]*degli[\s\xa0]*Apostoli)?)?|cts)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Rom"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Romani)|(?:Lettera[\s\xa0]*ai[\s\xa0]*Romani|R(?:o?m|o)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Corinzi)|(?:(?:2\xB0|II)[\s\xa0]*Corinzi|2(?:[\s\xa0]*?Cor|[\s\xa0]*Co)|(?:2\xB0?|II)\.[\s\xa0]*Corinzi|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*ai[\s\xa0]*)?|o[\s\xa0]*)Corinzi) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Cor"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Corinzi)|(?:(?:1\xB0|I)[\s\xa0]*Corinzi|1(?:[\s\xa0]*?Cor|[\s\xa0]*Co)|(?:1\xB0?|I)\.[\s\xa0]*Corinzi|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*ai[\s\xa0]*)?|o[\s\xa0]*)Corinzi) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Gal"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:a(?:lati|l)?|\xE0lati)|Lettera[\s\xa0]*ai[\s\xa0]*Galati) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Eph"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lettera[\s\xa0]*agli[\s\xa0]*Efesini|E(?:fesini|ph|f)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phil"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Filippesi)|(?:Lettera[\s\xa0]*ai[\s\xa0]*Filippesi|(?:Fi?|Phi)l) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Col"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lettera[\s\xa0]*ai[\s\xa0]*Colossesi|C(?:olossesi|o?l)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Tessalonicesi)|(?:(?:2\xB0|II)[\s\xa0]*Tessalonicesi|2(?:[\s\xa0]*T[es]|Thess)|(?:2\xB0?|II)\.[\s\xa0]*Tessalonicesi|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*ai[\s\xa0]*)?|o[\s\xa0]*)Tessalonicesi) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Thess"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Tessalonicesi)|(?:(?:1\xB0|I)[\s\xa0]*Tessalonicesi|1(?:[\s\xa0]*T[es]|Thess)|(?:1\xB0?|I)\.[\s\xa0]*Tessalonicesi|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*ai[\s\xa0]*)?|o[\s\xa0]*)Tessalonicesi) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Timoteo)|(?:2(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:2\xB0|II)[\s\xa0]*Timoteo|(?:2\xB0?|II)\.[\s\xa0]*Timoteo|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*a[\s\xa0]*)?|o[\s\xa0]*)Timoteo) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Tim"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Timoteo)|(?:1(?:(?:[\s\xa0]*Ti?|Ti)m|[\s\xa0]*Ti)|(?:1\xB0|I)[\s\xa0]*Timoteo|(?:1\xB0?|I)\.[\s\xa0]*Timoteo|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*a[\s\xa0]*)?|o[\s\xa0]*)Timoteo) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Titus"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:T(?:it(?:us|o)|t)|Lettera[\s\xa0]*a[\s\xa0]*Tito) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Phlm"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Fil[e\xE8]mone)|(?:Lettera[\s\xa0]*a[\s\xa0]*Filemone|F[im]|Phlm) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Heb"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Ebrei)|(?:Lettera[\s\xa0]*agli[\s\xa0]*Ebrei|(?:He|E)b) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jas"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lettera[\s\xa0]*di[\s\xa0]*Giacomo|G[cm]|Jas|Giacomo) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2[\s\xa0]*Pietro)|(?:(?:2\xB0|II)[\s\xa0]*Pietro|2(?:(?:[\s\xa0]*P|Pe)t|[\s\xa0]*P)|(?:2\xB0?|II)\.[\s\xa0]*Pietro|Second(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)Pietro) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Pet"] regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1[\s\xa0]*Pietro)|(?:1(?:(?:[\s\xa0]*P|Pe)t|[\s\xa0]*P)|(?:1\xB0|I)[\s\xa0]*Pietro|(?:1\xB0?|I)\.[\s\xa0]*Pietro|Prim(?:a[\s\xa0]*(?:lettera[\s\xa0]*di[\s\xa0]*)?|o[\s\xa0]*)Pietro) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jude"] regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Lettera[\s\xa0]*di[\s\xa0]*Giuda|Jude|Gd|Giuda) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Tob"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:T(?:ob(?:i(?:olo|a)?)?|b)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Jdt"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:G(?:iuditta|dt)|Jdt) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Bar"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:Bar(?:uch?)?) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["Sus"] apocrypha: true regexp: ///(^|#{bcv_parser::regexps.pre_book})( (?:S(?:toria[\s\xa0]*di[\s\xa0]*Susanna|us(?:anna)?)) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["2Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:2(?:[\s\xa0]*Maccabei|Macc))|(?:(?:2\xB0|II)[\s\xa0]*Maccabei|2[\s\xa0]*Mac|(?:2\xB0?|II)\.[\s\xa0]*Maccabei|Second(?:o[\s\xa0]*(?:libro[\s\xa0]*dei[\s\xa0]*)?|a[\s\xa0]*)Maccabei) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["3Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:3(?:[\s\xa0]*Maccabei|Macc))|(?:(?:3\xB0|III)[\s\xa0]*Maccabei|3[\s\xa0]*Mac|(?:3\xB0?|III)\.[\s\xa0]*Maccabei|Terz(?:o[\s\xa0]*(?:libro[\s\xa0]*dei[\s\xa0]*)?|a[\s\xa0]*)Maccabei) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["4Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:4(?:[\s\xa0]*Maccabei|Macc))|(?:(?:4\xB0|IV)[\s\xa0]*Maccabei|4[\s\xa0]*Mac|(?:4\xB0?|IV)\.[\s\xa0]*Maccabei|Quart(?:o[\s\xa0]*(?:libro[\s\xa0]*dei[\s\xa0]*)?|a[\s\xa0]*)Maccabei) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi , osis: ["1Macc"] apocrypha: true regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])( (?:1(?:[\s\xa0]*Maccabei|Macc))|(?:(?:1\xB0|I)[\s\xa0]*Maccabei|1[\s\xa0]*Mac|(?:1\xB0?|I)\.[\s\xa0]*Maccabei|Prim(?:o[\s\xa0]*(?:libro[\s\xa0]*dei[\s\xa0]*)?|a[\s\xa0]*)Maccabei) )(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi ] # Short-circuit the look if we know we want all the books. return books if include_apocrypha is true and case_sensitive is "none" # Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9. out = [] for book in books continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true if case_sensitive is "books" book.regexp = new RegExp book.regexp.source, "g" out.push book out # Default to not using the Apocrypha bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
[ { "context": "orker\n mqttUri: 'mqtt://meshblu:judgementday@127.0.0.1'\n jobTimeoutSeconds: 1\n jobLogRedisUri:", "end": 473, "score": 0.9996204376220703, "start": 464, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "ient = new Meshblumqtt uuid: 'some-uuid', token: 'some-token', hostname: 'localhost'\n @client.connect ", "end": 842, "score": 0.5880037546157837, "start": 838, "tag": "PASSWORD", "value": "some" }, { "context": "= new Meshblumqtt uuid: 'some-uuid', token: 'some-token', hostname: 'localhost'\n @client.connect done\n", "end": 848, "score": 0.48976224660873413, "start": 843, "tag": "KEY", "value": "token" }, { "context": "est.metadata.responseId\n data: { whoami:'somebody' }\n code: 200\n\n @jobManager.creat", "end": 1307, "score": 0.7583978176116943, "start": 1299, "tag": "NAME", "value": "somebody" } ]
test/whoami-spec.coffee
octoblu/meshblu-core-worker-mqtt
0
Worker = require '../src/worker' Meshblumqtt = require 'meshblu-mqtt' RedisNS = require '@octoblu/redis-ns' redis = require 'ioredis' JobManager = require 'meshblu-core-job-manager' async = require 'async' describe 'whoami', -> beforeEach -> @jobManager = new JobManager client: new RedisNS 'ns', redis.createClient() timeoutSeconds: 1 beforeEach -> @worker = new Worker mqttUri: 'mqtt://meshblu:judgementday@127.0.0.1' jobTimeoutSeconds: 1 jobLogRedisUri: 'redis://localhost:6379' jobLogQueue: 'sample-rate:0.00' jobLogSampleRate: 0 maxConnections: 10 redisUri: 'redis://localhost:6379' namespace: 'ns' @worker.run (error) => throw error if error? beforeEach (done) -> @client = new Meshblumqtt uuid: 'some-uuid', token: 'some-token', hostname: 'localhost' @client.connect done beforeEach (done) -> @asyncJobManagerGetRequest = (callback) => @jobManager.getRequest ['request'], (error, @jobManagerRequest) => return callback error if error? return callback new Error('Request timeout') unless @jobManagerRequest? responseOptions = metadata: responseId: @jobManagerRequest.metadata.responseId data: { whoami:'somebody' } code: 200 @jobManager.createResponse 'response', responseOptions, callback @asyncClientWhoAmi = (callback) => @client.whoami (error, @data) => callback(error) async.parallel [ @asyncJobManagerGetRequest, @asyncClientWhoAmi ], => done() it 'should create a @jobManagerRequest', -> expect(@jobManagerRequest.metadata.jobType).to.deep.equal 'GetDevice' it 'should give us a device', -> expect(@data).to.exist
45722
Worker = require '../src/worker' Meshblumqtt = require 'meshblu-mqtt' RedisNS = require '@octoblu/redis-ns' redis = require 'ioredis' JobManager = require 'meshblu-core-job-manager' async = require 'async' describe 'whoami', -> beforeEach -> @jobManager = new JobManager client: new RedisNS 'ns', redis.createClient() timeoutSeconds: 1 beforeEach -> @worker = new Worker mqttUri: 'mqtt://meshblu:judgementday@127.0.0.1' jobTimeoutSeconds: 1 jobLogRedisUri: 'redis://localhost:6379' jobLogQueue: 'sample-rate:0.00' jobLogSampleRate: 0 maxConnections: 10 redisUri: 'redis://localhost:6379' namespace: 'ns' @worker.run (error) => throw error if error? beforeEach (done) -> @client = new Meshblumqtt uuid: 'some-uuid', token: '<PASSWORD>-<KEY>', hostname: 'localhost' @client.connect done beforeEach (done) -> @asyncJobManagerGetRequest = (callback) => @jobManager.getRequest ['request'], (error, @jobManagerRequest) => return callback error if error? return callback new Error('Request timeout') unless @jobManagerRequest? responseOptions = metadata: responseId: @jobManagerRequest.metadata.responseId data: { whoami:'<NAME>' } code: 200 @jobManager.createResponse 'response', responseOptions, callback @asyncClientWhoAmi = (callback) => @client.whoami (error, @data) => callback(error) async.parallel [ @asyncJobManagerGetRequest, @asyncClientWhoAmi ], => done() it 'should create a @jobManagerRequest', -> expect(@jobManagerRequest.metadata.jobType).to.deep.equal 'GetDevice' it 'should give us a device', -> expect(@data).to.exist
true
Worker = require '../src/worker' Meshblumqtt = require 'meshblu-mqtt' RedisNS = require '@octoblu/redis-ns' redis = require 'ioredis' JobManager = require 'meshblu-core-job-manager' async = require 'async' describe 'whoami', -> beforeEach -> @jobManager = new JobManager client: new RedisNS 'ns', redis.createClient() timeoutSeconds: 1 beforeEach -> @worker = new Worker mqttUri: 'mqtt://meshblu:judgementday@127.0.0.1' jobTimeoutSeconds: 1 jobLogRedisUri: 'redis://localhost:6379' jobLogQueue: 'sample-rate:0.00' jobLogSampleRate: 0 maxConnections: 10 redisUri: 'redis://localhost:6379' namespace: 'ns' @worker.run (error) => throw error if error? beforeEach (done) -> @client = new Meshblumqtt uuid: 'some-uuid', token: 'PI:PASSWORD:<PASSWORD>END_PI-PI:KEY:<KEY>END_PI', hostname: 'localhost' @client.connect done beforeEach (done) -> @asyncJobManagerGetRequest = (callback) => @jobManager.getRequest ['request'], (error, @jobManagerRequest) => return callback error if error? return callback new Error('Request timeout') unless @jobManagerRequest? responseOptions = metadata: responseId: @jobManagerRequest.metadata.responseId data: { whoami:'PI:NAME:<NAME>END_PI' } code: 200 @jobManager.createResponse 'response', responseOptions, callback @asyncClientWhoAmi = (callback) => @client.whoami (error, @data) => callback(error) async.parallel [ @asyncJobManagerGetRequest, @asyncClientWhoAmi ], => done() it 'should create a @jobManagerRequest', -> expect(@jobManagerRequest.metadata.jobType).to.deep.equal 'GetDevice' it 'should give us a device', -> expect(@data).to.exist
[ { "context": "ngodb_username = process.env.mongodb_username || \"admin\"\nmongodb_password = process.env.mongodb_password ", "end": 89, "score": 0.9957559108734131, "start": 84, "tag": "USERNAME", "value": "admin" }, { "context": "ngodb_password = process.env.mongodb_password || \"whoislikingyou\"\nmongodb_port = process.env.mongodb_port || 10072", "end": 157, "score": 0.999232292175293, "start": 143, "tag": "PASSWORD", "value": "whoislikingyou" } ]
data-layer/collections/user.coffee
dfraser74/whoislikingyou
0
mongoose = require('mongoose') mongodb_username = process.env.mongodb_username || "admin" mongodb_password = process.env.mongodb_password || "whoislikingyou" mongodb_port = process.env.mongodb_port || 10072 mongodb_host = process.env.mongodb_host || "alex.mongohq.com" mongodb_database = process.env.mongodb_database || "whoislikingyou" mongodbURL = "mongodb://"+ mongodb_username + ":" + mongodb_password + "@" + mongodb_host + ":" + mongodb_port + "/" + mongodb_database db = mongoose.createConnection(mongodbURL) schema = mongoose.Schema({ facebookId: Number, username: String, name: String, email: String, pages: [{ _id: String, name: String}], activePage: { _id: String, name: String}, pageTest:Array, accessKey: String, locale: String, gender: String, timezone: String, updated_time: { type: Date, default: Date.now }, location: { _id: String, name: String}}); @User = db.model('User', schema) exports.upsert = (accessToken, profile, callback) -> first_login = false @User.findOne { 'email': profile.emails[0].value }, (err, user) => return callback err if err? if not user user = new @User({ email: profile.emails[0].value }) first_login = true user.username = profile.username user.name = profile.displayName user.accessKey = accessToken user.save (err, user) -> console.log err if err? return callback(err, user, first_login) exports.insertByEmail = (email, messages, callback) -> userdb = new @User({ email: email }) userdb.save (err) -> if err? if err.code == 11000 message = messages.exists else message = messages.error else message = messages.success callback err, message exports.addPage = (userEmail, page, callback) -> @User.findOne { email: userEmail }, (err, userdb) -> return callback err if err? return callback "no user found" if not userdb userdb.pageTest.push(page.id) userdb.pages.push({_id:page.id, name:page.name}) userdb.activePage = {_id: page.id, name: page.name} userdb.save (err) -> return callback err exports.activatePage = (userEmail, page, callback) -> @User.findOne { email: userEmail }, (err, userdb) -> return callback err if err? return callback "no user found" if not userdb userdb.activePage = {_id: page.id, name: page.name} userdb.save (err) -> return callback err
138679
mongoose = require('mongoose') mongodb_username = process.env.mongodb_username || "admin" mongodb_password = process.env.mongodb_password || "<PASSWORD>" mongodb_port = process.env.mongodb_port || 10072 mongodb_host = process.env.mongodb_host || "alex.mongohq.com" mongodb_database = process.env.mongodb_database || "whoislikingyou" mongodbURL = "mongodb://"+ mongodb_username + ":" + mongodb_password + "@" + mongodb_host + ":" + mongodb_port + "/" + mongodb_database db = mongoose.createConnection(mongodbURL) schema = mongoose.Schema({ facebookId: Number, username: String, name: String, email: String, pages: [{ _id: String, name: String}], activePage: { _id: String, name: String}, pageTest:Array, accessKey: String, locale: String, gender: String, timezone: String, updated_time: { type: Date, default: Date.now }, location: { _id: String, name: String}}); @User = db.model('User', schema) exports.upsert = (accessToken, profile, callback) -> first_login = false @User.findOne { 'email': profile.emails[0].value }, (err, user) => return callback err if err? if not user user = new @User({ email: profile.emails[0].value }) first_login = true user.username = profile.username user.name = profile.displayName user.accessKey = accessToken user.save (err, user) -> console.log err if err? return callback(err, user, first_login) exports.insertByEmail = (email, messages, callback) -> userdb = new @User({ email: email }) userdb.save (err) -> if err? if err.code == 11000 message = messages.exists else message = messages.error else message = messages.success callback err, message exports.addPage = (userEmail, page, callback) -> @User.findOne { email: userEmail }, (err, userdb) -> return callback err if err? return callback "no user found" if not userdb userdb.pageTest.push(page.id) userdb.pages.push({_id:page.id, name:page.name}) userdb.activePage = {_id: page.id, name: page.name} userdb.save (err) -> return callback err exports.activatePage = (userEmail, page, callback) -> @User.findOne { email: userEmail }, (err, userdb) -> return callback err if err? return callback "no user found" if not userdb userdb.activePage = {_id: page.id, name: page.name} userdb.save (err) -> return callback err
true
mongoose = require('mongoose') mongodb_username = process.env.mongodb_username || "admin" mongodb_password = process.env.mongodb_password || "PI:PASSWORD:<PASSWORD>END_PI" mongodb_port = process.env.mongodb_port || 10072 mongodb_host = process.env.mongodb_host || "alex.mongohq.com" mongodb_database = process.env.mongodb_database || "whoislikingyou" mongodbURL = "mongodb://"+ mongodb_username + ":" + mongodb_password + "@" + mongodb_host + ":" + mongodb_port + "/" + mongodb_database db = mongoose.createConnection(mongodbURL) schema = mongoose.Schema({ facebookId: Number, username: String, name: String, email: String, pages: [{ _id: String, name: String}], activePage: { _id: String, name: String}, pageTest:Array, accessKey: String, locale: String, gender: String, timezone: String, updated_time: { type: Date, default: Date.now }, location: { _id: String, name: String}}); @User = db.model('User', schema) exports.upsert = (accessToken, profile, callback) -> first_login = false @User.findOne { 'email': profile.emails[0].value }, (err, user) => return callback err if err? if not user user = new @User({ email: profile.emails[0].value }) first_login = true user.username = profile.username user.name = profile.displayName user.accessKey = accessToken user.save (err, user) -> console.log err if err? return callback(err, user, first_login) exports.insertByEmail = (email, messages, callback) -> userdb = new @User({ email: email }) userdb.save (err) -> if err? if err.code == 11000 message = messages.exists else message = messages.error else message = messages.success callback err, message exports.addPage = (userEmail, page, callback) -> @User.findOne { email: userEmail }, (err, userdb) -> return callback err if err? return callback "no user found" if not userdb userdb.pageTest.push(page.id) userdb.pages.push({_id:page.id, name:page.name}) userdb.activePage = {_id: page.id, name: page.name} userdb.save (err) -> return callback err exports.activatePage = (userEmail, page, callback) -> @User.findOne { email: userEmail }, (err, userdb) -> return callback err if err? return callback "no user found" if not userdb userdb.activePage = {_id: page.id, name: page.name} userdb.save (err) -> return callback err
[ { "context": "###\nCopyright 2014 Michael Krolikowski\n\nLicensed under the Apache License, Version 2.0 (", "end": 38, "score": 0.9986440539360046, "start": 19, "tag": "NAME", "value": "Michael Krolikowski" } ]
src/main/javascript/maincontroller.coffee
mkroli/shurl
1
### Copyright 2014 Michael Krolikowski 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. ### shurl = angular.module "shurl" shurl.controller "MainController", ["$scope", "shurlBackend", ($scope, shurlBackend) -> $scope.link = "" $scope.linkHasError = false $scope.name = "" $scope.nameHasError = false $scope.shortened = null $scope.shortenedStats = null urlRegex = /^(.*)\/([^/]+)$/ $scope.shorten = (link, id) -> shurlBackend.shorten "id" : id , link , (r, headers) -> $scope.shortened = headers("Location") [_, prefix, id] = urlRegex.exec($scope.shortened) $scope.shortenedStats = "#{prefix}/stats/#{id}" $scope.linkHasError = false $scope.nameHasError = false , (err) -> if (err.status == 400) $scope.linkHasError = true else if (err.status == 409) $scope.linkHasError = false $scope.nameHasError = true $scope.shortened = null $scope.shortenedStats = null ]
208917
### 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. ### shurl = angular.module "shurl" shurl.controller "MainController", ["$scope", "shurlBackend", ($scope, shurlBackend) -> $scope.link = "" $scope.linkHasError = false $scope.name = "" $scope.nameHasError = false $scope.shortened = null $scope.shortenedStats = null urlRegex = /^(.*)\/([^/]+)$/ $scope.shorten = (link, id) -> shurlBackend.shorten "id" : id , link , (r, headers) -> $scope.shortened = headers("Location") [_, prefix, id] = urlRegex.exec($scope.shortened) $scope.shortenedStats = "#{prefix}/stats/#{id}" $scope.linkHasError = false $scope.nameHasError = false , (err) -> if (err.status == 400) $scope.linkHasError = true else if (err.status == 409) $scope.linkHasError = false $scope.nameHasError = true $scope.shortened = null $scope.shortenedStats = null ]
true
### 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. ### shurl = angular.module "shurl" shurl.controller "MainController", ["$scope", "shurlBackend", ($scope, shurlBackend) -> $scope.link = "" $scope.linkHasError = false $scope.name = "" $scope.nameHasError = false $scope.shortened = null $scope.shortenedStats = null urlRegex = /^(.*)\/([^/]+)$/ $scope.shorten = (link, id) -> shurlBackend.shorten "id" : id , link , (r, headers) -> $scope.shortened = headers("Location") [_, prefix, id] = urlRegex.exec($scope.shortened) $scope.shortenedStats = "#{prefix}/stats/#{id}" $scope.linkHasError = false $scope.nameHasError = false , (err) -> if (err.status == 400) $scope.linkHasError = true else if (err.status == 409) $scope.linkHasError = false $scope.nameHasError = true $scope.shortened = null $scope.shortenedStats = null ]
[ { "context": "###\nCopyright 2016 Clemens Nylandsted Klokmose, Aarhus University\n\nLicensed under the Apache Lic", "end": 46, "score": 0.9998960494995117, "start": 19, "tag": "NAME", "value": "Clemens Nylandsted Klokmose" } ]
client_src/util.coffee
kar288/ddd
0
### Copyright 2016 Clemens Nylandsted Klokmose, Aarhus University 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. ### root = exports ? window root.util = {} #Gets the element at a given path in a jsonml document root.util.elementAtPath = (snapshot, path) -> if path.length > 0 and typeof path[path.length-1] == 'string' return null if path.length == 0 return snapshot else return util.elementAtPath(snapshot[path[0]], path[1..path.length]) #Check if elem is child of a parent with an XML namespace and return it root.util.getNs = (elem) -> if not elem? return undefined if not elem.getAttribute? return undefined ns = elem.getAttribute "xmlns" if ns? return ns; if elem.parent == elem return undefined return root.util.getNs elem.parent #Used to make operations out of a set of string patches root.util.patch_to_ot = (path, patches) -> ops = [] for patch in patches insertionPoint = patch.start1 for diff in patch.diffs if diff[0] == 0 insertionPoint += diff[1].length if diff[0] == 1 ops.push {si: diff[1], p: path.concat [insertionPoint]} insertionPoint += diff[1].length if diff[0] == -1 ops.push {sd: diff[1], p: path.concat [insertionPoint]} return ops #Generates a unique identifier root.util.generateUUID = -> 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) -> r = Math.random() * 16 | 0 v = if c is 'x' then r else (r & 0x3|0x8) v.toString(16) ) #Extract domain from URL root.util.extractDomain = (url) -> if url.indexOf("://") > -1 domain = url.split('/')[2] else domain = url.split('/')[0] return domain #Given a pathnode, compute its JsonML path root.util.getJsonMLPathFromPathNode = (node) -> if not node.parent? return [] else childIndex = 2 #JsonML specific {name, attributes, children} for sibling in node.parent.children if sibling.id == node.id break childIndex += 1 return util.getJsonMLPathFromPathNode(node.parent).concat [childIndex] #Creates a pathTree from a DOM element #If a parent pathNode is provided the generated pathTree will be a subtree in the pathTree of the parent #Per default multiple pathNodes can be added to a dom element root.util.createPathTree = (DOMNode, parentPathNode, overwrite=false) -> pathNode = {id: util.generateUUID(), children: [], parent: parentPathNode, DOMNode: DOMNode} if overwrite DOMNode.__pathNodes = [pathNode] else if not DOMNode.__pathNodes? DOMNode.__pathNodes = [] DOMNode.__pathNodes.push pathNode for child in DOMNode.childNodes pathNode.children.push(util.createPathTree(child, pathNode, overwrite)) return pathNode #Returns the last added pathNode of an element #If a parent DOM element is provided, we search for the pathNode that matches on parent root.util.getPathNode = (elem, parentElem) -> if parentElem? and parentElem.__pathNodes? and elem.__pathNodes? for parentPathNode in parentElem.__pathNodes for elemPathNode in elem.__pathNodes if elemPathNode.parent.id == parentPathNode.id return elemPathNode if elem.__pathNodes? and elem.__pathNodes.length > 0 return elem.__pathNodes[elem.__pathNodes.length - 1] return null #Cleans up the DOM tree associated from a given pathNode root.util.removePathNode = (pathNode) -> pathNode.parent = null #Remove from DOMNode pathNode.DOMNode.__pathNodes.splice (pathNode.DOMNode.__pathNodes.indexOf pathNode), 1 for child in pathNode.children util.removePathNode child pathNode.children = null pathNode.DOMNode = null #Checks consistency between a DOM tree and a pathTree root.util.check = (domNode, pathNode) -> if domNode instanceof jQuery domNode = domNode[0] if domNode.__pathNodes.length > 1 console.log domNode, domNode.__pathNodes window.alert "Webstrates has encountered an error. Please reload the page." throw "Node has multiple paths" domNodePathNode = domNode.__pathNodes[0] if domNodePathNode.id != pathNode.id console.log domNode, pathNode window.alert "Webstrates has encountered an error. Please reload the page." throw "No id match" definedChildNodesInDom = (childNode for childNode in domNode.childNodes when childNode.__pathNodes?.length > 0) if definedChildNodesInDom.length != pathNode.children.length console.log domNode, pathNode window.alert "Webstrates has encountered an error. Please reload the page." throw "Different amount of children" if definedChildNodesInDom.length != domNode.childNodes.length console.log "Warning: found zombie nodes in DOM" for definedChildDomNode, i in definedChildNodesInDom util.check(definedChildDomNode, pathNode.children[i])
211544
### Copyright 2016 <NAME>, Aarhus University 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. ### root = exports ? window root.util = {} #Gets the element at a given path in a jsonml document root.util.elementAtPath = (snapshot, path) -> if path.length > 0 and typeof path[path.length-1] == 'string' return null if path.length == 0 return snapshot else return util.elementAtPath(snapshot[path[0]], path[1..path.length]) #Check if elem is child of a parent with an XML namespace and return it root.util.getNs = (elem) -> if not elem? return undefined if not elem.getAttribute? return undefined ns = elem.getAttribute "xmlns" if ns? return ns; if elem.parent == elem return undefined return root.util.getNs elem.parent #Used to make operations out of a set of string patches root.util.patch_to_ot = (path, patches) -> ops = [] for patch in patches insertionPoint = patch.start1 for diff in patch.diffs if diff[0] == 0 insertionPoint += diff[1].length if diff[0] == 1 ops.push {si: diff[1], p: path.concat [insertionPoint]} insertionPoint += diff[1].length if diff[0] == -1 ops.push {sd: diff[1], p: path.concat [insertionPoint]} return ops #Generates a unique identifier root.util.generateUUID = -> 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) -> r = Math.random() * 16 | 0 v = if c is 'x' then r else (r & 0x3|0x8) v.toString(16) ) #Extract domain from URL root.util.extractDomain = (url) -> if url.indexOf("://") > -1 domain = url.split('/')[2] else domain = url.split('/')[0] return domain #Given a pathnode, compute its JsonML path root.util.getJsonMLPathFromPathNode = (node) -> if not node.parent? return [] else childIndex = 2 #JsonML specific {name, attributes, children} for sibling in node.parent.children if sibling.id == node.id break childIndex += 1 return util.getJsonMLPathFromPathNode(node.parent).concat [childIndex] #Creates a pathTree from a DOM element #If a parent pathNode is provided the generated pathTree will be a subtree in the pathTree of the parent #Per default multiple pathNodes can be added to a dom element root.util.createPathTree = (DOMNode, parentPathNode, overwrite=false) -> pathNode = {id: util.generateUUID(), children: [], parent: parentPathNode, DOMNode: DOMNode} if overwrite DOMNode.__pathNodes = [pathNode] else if not DOMNode.__pathNodes? DOMNode.__pathNodes = [] DOMNode.__pathNodes.push pathNode for child in DOMNode.childNodes pathNode.children.push(util.createPathTree(child, pathNode, overwrite)) return pathNode #Returns the last added pathNode of an element #If a parent DOM element is provided, we search for the pathNode that matches on parent root.util.getPathNode = (elem, parentElem) -> if parentElem? and parentElem.__pathNodes? and elem.__pathNodes? for parentPathNode in parentElem.__pathNodes for elemPathNode in elem.__pathNodes if elemPathNode.parent.id == parentPathNode.id return elemPathNode if elem.__pathNodes? and elem.__pathNodes.length > 0 return elem.__pathNodes[elem.__pathNodes.length - 1] return null #Cleans up the DOM tree associated from a given pathNode root.util.removePathNode = (pathNode) -> pathNode.parent = null #Remove from DOMNode pathNode.DOMNode.__pathNodes.splice (pathNode.DOMNode.__pathNodes.indexOf pathNode), 1 for child in pathNode.children util.removePathNode child pathNode.children = null pathNode.DOMNode = null #Checks consistency between a DOM tree and a pathTree root.util.check = (domNode, pathNode) -> if domNode instanceof jQuery domNode = domNode[0] if domNode.__pathNodes.length > 1 console.log domNode, domNode.__pathNodes window.alert "Webstrates has encountered an error. Please reload the page." throw "Node has multiple paths" domNodePathNode = domNode.__pathNodes[0] if domNodePathNode.id != pathNode.id console.log domNode, pathNode window.alert "Webstrates has encountered an error. Please reload the page." throw "No id match" definedChildNodesInDom = (childNode for childNode in domNode.childNodes when childNode.__pathNodes?.length > 0) if definedChildNodesInDom.length != pathNode.children.length console.log domNode, pathNode window.alert "Webstrates has encountered an error. Please reload the page." throw "Different amount of children" if definedChildNodesInDom.length != domNode.childNodes.length console.log "Warning: found zombie nodes in DOM" for definedChildDomNode, i in definedChildNodesInDom util.check(definedChildDomNode, pathNode.children[i])
true
### Copyright 2016 PI:NAME:<NAME>END_PI, Aarhus University 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. ### root = exports ? window root.util = {} #Gets the element at a given path in a jsonml document root.util.elementAtPath = (snapshot, path) -> if path.length > 0 and typeof path[path.length-1] == 'string' return null if path.length == 0 return snapshot else return util.elementAtPath(snapshot[path[0]], path[1..path.length]) #Check if elem is child of a parent with an XML namespace and return it root.util.getNs = (elem) -> if not elem? return undefined if not elem.getAttribute? return undefined ns = elem.getAttribute "xmlns" if ns? return ns; if elem.parent == elem return undefined return root.util.getNs elem.parent #Used to make operations out of a set of string patches root.util.patch_to_ot = (path, patches) -> ops = [] for patch in patches insertionPoint = patch.start1 for diff in patch.diffs if diff[0] == 0 insertionPoint += diff[1].length if diff[0] == 1 ops.push {si: diff[1], p: path.concat [insertionPoint]} insertionPoint += diff[1].length if diff[0] == -1 ops.push {sd: diff[1], p: path.concat [insertionPoint]} return ops #Generates a unique identifier root.util.generateUUID = -> 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) -> r = Math.random() * 16 | 0 v = if c is 'x' then r else (r & 0x3|0x8) v.toString(16) ) #Extract domain from URL root.util.extractDomain = (url) -> if url.indexOf("://") > -1 domain = url.split('/')[2] else domain = url.split('/')[0] return domain #Given a pathnode, compute its JsonML path root.util.getJsonMLPathFromPathNode = (node) -> if not node.parent? return [] else childIndex = 2 #JsonML specific {name, attributes, children} for sibling in node.parent.children if sibling.id == node.id break childIndex += 1 return util.getJsonMLPathFromPathNode(node.parent).concat [childIndex] #Creates a pathTree from a DOM element #If a parent pathNode is provided the generated pathTree will be a subtree in the pathTree of the parent #Per default multiple pathNodes can be added to a dom element root.util.createPathTree = (DOMNode, parentPathNode, overwrite=false) -> pathNode = {id: util.generateUUID(), children: [], parent: parentPathNode, DOMNode: DOMNode} if overwrite DOMNode.__pathNodes = [pathNode] else if not DOMNode.__pathNodes? DOMNode.__pathNodes = [] DOMNode.__pathNodes.push pathNode for child in DOMNode.childNodes pathNode.children.push(util.createPathTree(child, pathNode, overwrite)) return pathNode #Returns the last added pathNode of an element #If a parent DOM element is provided, we search for the pathNode that matches on parent root.util.getPathNode = (elem, parentElem) -> if parentElem? and parentElem.__pathNodes? and elem.__pathNodes? for parentPathNode in parentElem.__pathNodes for elemPathNode in elem.__pathNodes if elemPathNode.parent.id == parentPathNode.id return elemPathNode if elem.__pathNodes? and elem.__pathNodes.length > 0 return elem.__pathNodes[elem.__pathNodes.length - 1] return null #Cleans up the DOM tree associated from a given pathNode root.util.removePathNode = (pathNode) -> pathNode.parent = null #Remove from DOMNode pathNode.DOMNode.__pathNodes.splice (pathNode.DOMNode.__pathNodes.indexOf pathNode), 1 for child in pathNode.children util.removePathNode child pathNode.children = null pathNode.DOMNode = null #Checks consistency between a DOM tree and a pathTree root.util.check = (domNode, pathNode) -> if domNode instanceof jQuery domNode = domNode[0] if domNode.__pathNodes.length > 1 console.log domNode, domNode.__pathNodes window.alert "Webstrates has encountered an error. Please reload the page." throw "Node has multiple paths" domNodePathNode = domNode.__pathNodes[0] if domNodePathNode.id != pathNode.id console.log domNode, pathNode window.alert "Webstrates has encountered an error. Please reload the page." throw "No id match" definedChildNodesInDom = (childNode for childNode in domNode.childNodes when childNode.__pathNodes?.length > 0) if definedChildNodesInDom.length != pathNode.children.length console.log domNode, pathNode window.alert "Webstrates has encountered an error. Please reload the page." throw "Different amount of children" if definedChildNodesInDom.length != domNode.childNodes.length console.log "Warning: found zombie nodes in DOM" for definedChildDomNode, i in definedChildNodesInDom util.check(definedChildDomNode, pathNode.children[i])
[ { "context": " # Build the payload\n payload =\n name: \"Bugsnag\"\n client: config.apiKey\n email: \"bugsna", "end": 341, "score": 0.9983883500099182, "start": 334, "tag": "NAME", "value": "Bugsnag" }, { "context": "ugsnag\"\n client: config.apiKey\n email: \"bugsnag@bugsnag.com\"\n ticket:\n subject: \"#{event.error.ex", "end": 404, "score": 0.9999125599861145, "start": 385, "tag": "EMAIL", "value": "bugsnag@bugsnag.com" } ]
plugins/uservoice/index.coffee
jacobmarshall-etc/bugsnag-notification-plugins
0
NotificationPlugin = require "../../notification-plugin" class UserVoice extends NotificationPlugin @receiveEvent: (config, event, callback) -> if event?.trigger?.type == "linkExistingIssue" return callback(null, null) return if event?.trigger?.type == "reopened" # Build the payload payload = name: "Bugsnag" client: config.apiKey email: "bugsnag@bugsnag.com" ticket: subject: "#{event.error.exceptionClass} in #{event.error.context}" message: """ #{event.error.exceptionClass} in #{event.error.context} for project #{event.project.name} #{event.error.message if event.error.message} #{event.error.url} Stacktrace: #{@basicStacktrace(event.error.stacktrace)} """ custom_field_values: bugsnagProjectName: event.project.name # Send the request url = if config.url.startsWith(/https?:\/\//) then config.url else "https://#{config.url}" @request .post("#{url}/api/v1/tickets.json") .timeout(4000) .send(payload) .type("form") .on "error", (err) -> callback(err) .end (res) -> return callback(res.error) if res.error callback null, id: res.body.ticket.id number: res.body.ticket.ticket_number url: "#{url}/admin/tickets/#{res.body.ticket.ticket_number}" module.exports = UserVoice
122416
NotificationPlugin = require "../../notification-plugin" class UserVoice extends NotificationPlugin @receiveEvent: (config, event, callback) -> if event?.trigger?.type == "linkExistingIssue" return callback(null, null) return if event?.trigger?.type == "reopened" # Build the payload payload = name: "<NAME>" client: config.apiKey email: "<EMAIL>" ticket: subject: "#{event.error.exceptionClass} in #{event.error.context}" message: """ #{event.error.exceptionClass} in #{event.error.context} for project #{event.project.name} #{event.error.message if event.error.message} #{event.error.url} Stacktrace: #{@basicStacktrace(event.error.stacktrace)} """ custom_field_values: bugsnagProjectName: event.project.name # Send the request url = if config.url.startsWith(/https?:\/\//) then config.url else "https://#{config.url}" @request .post("#{url}/api/v1/tickets.json") .timeout(4000) .send(payload) .type("form") .on "error", (err) -> callback(err) .end (res) -> return callback(res.error) if res.error callback null, id: res.body.ticket.id number: res.body.ticket.ticket_number url: "#{url}/admin/tickets/#{res.body.ticket.ticket_number}" module.exports = UserVoice
true
NotificationPlugin = require "../../notification-plugin" class UserVoice extends NotificationPlugin @receiveEvent: (config, event, callback) -> if event?.trigger?.type == "linkExistingIssue" return callback(null, null) return if event?.trigger?.type == "reopened" # Build the payload payload = name: "PI:NAME:<NAME>END_PI" client: config.apiKey email: "PI:EMAIL:<EMAIL>END_PI" ticket: subject: "#{event.error.exceptionClass} in #{event.error.context}" message: """ #{event.error.exceptionClass} in #{event.error.context} for project #{event.project.name} #{event.error.message if event.error.message} #{event.error.url} Stacktrace: #{@basicStacktrace(event.error.stacktrace)} """ custom_field_values: bugsnagProjectName: event.project.name # Send the request url = if config.url.startsWith(/https?:\/\//) then config.url else "https://#{config.url}" @request .post("#{url}/api/v1/tickets.json") .timeout(4000) .send(payload) .type("form") .on "error", (err) -> callback(err) .end (res) -> return callback(res.error) if res.error callback null, id: res.body.ticket.id number: res.body.ticket.ticket_number url: "#{url}/admin/tickets/#{res.body.ticket.ticket_number}" module.exports = UserVoice
[ { "context": "'number'\n\n saved = {}\n input = { name: 'jakob', age: 28 }\n\n promise(api).connect(connectio", "end": 4076, "score": 0.9967633485794067, "start": 4071, "tag": "NAME", "value": "jakob" }, { "context": "should.be.a 'string'\n obj.name.should.eql 'jakob'\n obj.age.should.eql 28\n obj.should", "end": 4314, "score": 0.9973204135894775, "start": 4309, "tag": "NAME", "value": "jakob" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28 }, noErr())\n .list('stuffz', {}, n", "end": 4817, "score": 0.9979628324508667, "start": 4812, "tag": "NAME", "value": "jakob" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28 }, noErr())\n .list('stuffz', {}, n", "end": 5428, "score": 0.9982264041900635, "start": 5423, "tag": "NAME", "value": "jakob" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28 }, noErr())\n .post('stuffz', { nam", "end": 5969, "score": 0.9994747638702393, "start": 5964, "tag": "NAME", "value": "jakob" }, { "context": "ge: 28 }, noErr())\n .post('stuffz', { name: 'julia', age: 27 }, noErr())\n .list('stuffz', {}, n", "end": 6028, "score": 0.9997266530990601, "start": 6023, "tag": "NAME", "value": "julia" }, { "context": "-> _(x).omit('id')).should.eql [\n name: 'jakob'\n age: 28\n ,\n name: 'jul", "end": 6169, "score": 0.9995547533035278, "start": 6164, "tag": "NAME", "value": "jakob" }, { "context": "kob'\n age: 28\n ,\n name: 'julia'\n age: 27\n ]\n ).then ->\n ", "end": 6221, "score": 0.9997759461402893, "start": 6216, "tag": "NAME", "value": "julia" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28 }, noErr())\n .post('stuffz', { nam", "end": 6599, "score": 0.9993404150009155, "start": 6594, "tag": "NAME", "value": "jakob" }, { "context": "ge: 28 }, noErr())\n .post('stuffz', { name: 'julia', age: 27 }, noErr())\n .list('stuffz', {}, n", "end": 6658, "score": 0.9997454285621643, "start": 6653, "tag": "NAME", "value": "julia" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28 }, noErr())\n .post('stuffz', { nam", "end": 7327, "score": 0.9993826746940613, "start": 7322, "tag": "NAME", "value": "jakob" }, { "context": "ge: 28 }, noErr())\n .post('stuffz', { name: 'julia', age: 27 }, noErr (x) ->\n saved.id = x.id", "end": 7386, "score": 0.9998265504837036, "start": 7381, "tag": "NAME", "value": "julia" }, { "context": "uld.eql {\n id: saved.id\n name: 'julia'\n age: 27\n }\n ).then ->\n ", "end": 7618, "score": 0.9998270869255066, "start": 7613, "tag": "NAME", "value": "julia" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28 }, noErr())\n .post('stuffz', { nam", "end": 8000, "score": 0.9995065927505493, "start": 7995, "tag": "NAME", "value": "jakob" }, { "context": "ge: 28 }, noErr())\n .post('stuffz', { name: 'jakob', age: 42 }, noErr())\n .post('stuffz', { nam", "end": 8059, "score": 0.9994841814041138, "start": 8054, "tag": "NAME", "value": "jakob" }, { "context": "ge: 42 }, noErr())\n .post('stuffz', { name: 'julia', age: 27 }, noErr())\n .list('stuffz', { fil", "end": 8118, "score": 0.9998341798782349, "start": 8113, "tag": "NAME", "value": "julia" }, { "context": "noErr())\n .list('stuffz', { filter: { name: 'jakob' } }, noErr (x) ->\n x.should.have.length 2", "end": 8187, "score": 0.9994544982910156, "start": 8182, "tag": "NAME", "value": "jakob" }, { "context": "hould.have.length 2\n x[0].name.should.eql 'jakob'\n x[0].age.should.eql 28\n x[1].name", "end": 8273, "score": 0.9995886087417603, "start": 8268, "tag": "NAME", "value": "jakob" }, { "context": "].age.should.eql 28\n x[1].name.should.eql 'jakob'\n x[1].age.should.eql 42\n ).then ->\n ", "end": 8341, "score": 0.9995290040969849, "start": 8336, "tag": "NAME", "value": "jakob" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28, city: 'gbg' }, noErr())\n .post('s", "end": 8767, "score": 0.999433159828186, "start": 8762, "tag": "NAME", "value": "jakob" }, { "context": " 'gbg' }, noErr())\n .post('stuffz', { name: 'julia', age: 27, city: 'gbg' }, noErr())\n .post('s", "end": 8839, "score": 0.9998323321342468, "start": 8834, "tag": "NAME", "value": "julia" }, { "context": " 'gbg' }, noErr())\n .post('stuffz', { name: 'jakob', age: 28, city: 'sthlm' }, noErr())\n .post(", "end": 8911, "score": 0.999354362487793, "start": 8906, "tag": "NAME", "value": "jakob" }, { "context": "sthlm' }, noErr())\n .post('stuffz', { name: 'julia', age: 27, city: 'sthlm' }, noErr())\n .list(", "end": 8985, "score": 0.9997833371162415, "start": 8980, "tag": "NAME", "value": "julia" }, { "context": "noErr())\n .list('stuffz', { filter: { name: 'jakob', city: 'sthlm' } }, noErr (x) ->\n x.shoul", "end": 9069, "score": 0.9996334314346313, "start": 9064, "tag": "NAME", "value": "jakob" }, { "context": "hould.have.length 1\n x[0].name.should.eql 'jakob'\n x[0].age.should.eql 28\n x[0].city", "end": 9170, "score": 0.9996638894081116, "start": 9165, "tag": "NAME", "value": "jakob" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28 }, noErr())\n .post('stuffz', { nam", "end": 9565, "score": 0.9995955228805542, "start": 9560, "tag": "NAME", "value": "jakob" }, { "context": "ge: 28 }, noErr())\n .post('stuffz', { name: 'jakob', age: 42 }, noErr())\n .post('stuffz', { nam", "end": 9624, "score": 0.9995577335357666, "start": 9619, "tag": "NAME", "value": "jakob" }, { "context": "ge: 42 }, noErr())\n .post('stuffz', { name: 'julia', age: 27 }, noErr())\n .list('stuffz', { sor", "end": 9683, "score": 0.9997817873954773, "start": 9678, "tag": "NAME", "value": "julia" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28 }, noErr())\n .post('stuffz', { nam", "end": 10236, "score": 0.9994231462478638, "start": 10231, "tag": "NAME", "value": "jakob" }, { "context": "ge: 28 }, noErr())\n .post('stuffz', { name: 'jakob', age: 42 }, noErr())\n .post('stuffz', { nam", "end": 10295, "score": 0.9995392560958862, "start": 10290, "tag": "NAME", "value": "jakob" }, { "context": "ge: 42 }, noErr())\n .post('stuffz', { name: 'julia', age: 27 }, noErr())\n .list('stuffz', { lim", "end": 10354, "score": 0.9997768998146057, "start": 10349, "tag": "NAME", "value": "julia" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28 }, noErr())\n .post('stuffz', { nam", "end": 10779, "score": 0.9993771314620972, "start": 10774, "tag": "NAME", "value": "jakob" }, { "context": "ge: 28 }, noErr())\n .post('stuffz', { name: 'jakob', age: 42 }, noErr())\n .post('stuffz', { nam", "end": 10838, "score": 0.9994784593582153, "start": 10833, "tag": "NAME", "value": "jakob" }, { "context": "ge: 42 }, noErr())\n .post('stuffz', { name: 'julia', age: 27 }, noErr())\n .list('stuffz', { ski", "end": 10897, "score": 0.9997678995132446, "start": 10892, "tag": "NAME", "value": "julia" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28 }, noErr())\n .post('stuffz', { nam", "end": 11340, "score": 0.9991782307624817, "start": 11335, "tag": "NAME", "value": "jakob" }, { "context": "ge: 28 }, noErr())\n .post('stuffz', { name: 'jakob', age: 42 }, noErr())\n .post('stuffz', { nam", "end": 11399, "score": 0.9993772506713867, "start": 11394, "tag": "NAME", "value": "jakob" }, { "context": "ge: 42 }, noErr())\n .post('stuffz', { name: 'julia', age: 27 }, noErr())\n .list('stuffz', { sor", "end": 11458, "score": 0.9997946619987488, "start": 11453, "tag": "NAME", "value": "julia" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28 }, noErr())\n .post('stuffz', { nam", "end": 12011, "score": 0.9993203282356262, "start": 12006, "tag": "NAME", "value": "jakob" }, { "context": "ge: 28 }, noErr())\n .post('stuffz', { name: 'julia', age: 27 }, noErr (x) ->\n saved.id = x.id", "end": 12070, "score": 0.9997811317443848, "start": 12065, "tag": "NAME", "value": "julia" }, { "context": "uld.eql {\n id: saved.id\n name: 'julia'\n age: 27\n }\n ).then ->\n ", "end": 12270, "score": 0.9997680187225342, "start": 12265, "tag": "NAME", "value": "julia" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28 }, noErr())\n .post('stuffz', { nam", "end": 12659, "score": 0.9994379878044128, "start": 12654, "tag": "NAME", "value": "jakob" }, { "context": "ge: 28 }, noErr())\n .post('stuffz', { name: 'julia', age: 27 }, noErr())\n .getOne('stuffz', { f", "end": 12718, "score": 0.9997572302818298, "start": 12713, "tag": "NAME", "value": "julia" }, { "context": "Err())\n .getOne('stuffz', { filter: { name: 'jakob' } }, noErr (x) ->\n x.name.should.eql 'jak", "end": 12789, "score": 0.9993966817855835, "start": 12784, "tag": "NAME", "value": "jakob" }, { "context": "kob' } }, noErr (x) ->\n x.name.should.eql 'jakob'\n x.age.should.eql 28\n ).then ->\n ", "end": 12841, "score": 0.9995542168617249, "start": 12836, "tag": "NAME", "value": "jakob" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28, city: 'gbg' }, noErr())\n .post('s", "end": 13269, "score": 0.9992876052856445, "start": 13264, "tag": "NAME", "value": "jakob" }, { "context": " 'gbg' }, noErr())\n .post('stuffz', { name: 'julia', age: 27, city: 'gbg' }, noErr())\n .post('s", "end": 13341, "score": 0.9997383952140808, "start": 13336, "tag": "NAME", "value": "julia" }, { "context": " 'gbg' }, noErr())\n .post('stuffz', { name: 'jakob', age: 28, city: 'sthlm' }, noErr())\n .post(", "end": 13413, "score": 0.9994379281997681, "start": 13408, "tag": "NAME", "value": "jakob" }, { "context": "sthlm' }, noErr())\n .post('stuffz', { name: 'julia', age: 27, city: 'sthlm' }, noErr())\n .getOn", "end": 13487, "score": 0.9997201561927795, "start": 13482, "tag": "NAME", "value": "julia" }, { "context": "Err())\n .getOne('stuffz', { filter: { name: 'jakob', city: 'sthlm' } }, noErr (x) ->\n x.name.", "end": 13573, "score": 0.9994244575500488, "start": 13568, "tag": "NAME", "value": "jakob" }, { "context": "hlm' } }, noErr (x) ->\n x.name.should.eql 'jakob'\n x.age.should.eql 28\n x.city.shoul", "end": 13640, "score": 0.9995136260986328, "start": 13635, "tag": "NAME", "value": "jakob" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28 }, noErr())\n .post('stuffz', { na", "end": 14066, "score": 0.9994760751724243, "start": 14061, "tag": "NAME", "value": "jakob" }, { "context": "ge: 28 }, noErr())\n .post('stuffz', { name: 'julia', age: 27 }, noErr())\n .post('stuffz', { na", "end": 14126, "score": 0.9997431039810181, "start": 14121, "tag": "NAME", "value": "julia" }, { "context": "ge: 27 }, noErr())\n .post('stuffz', { name: 'sixten', age: 16 }, noErr())\n .list('stuffz', { fil", "end": 14187, "score": 0.9930696487426758, "start": 14181, "tag": "NAME", "value": "sixten" }, { "context": "->\n _(x).pluck('name').sort().should.eql ['jakob', 'julia']\n ).then ->\n api.close(done", "end": 14328, "score": 0.999496579170227, "start": 14323, "tag": "NAME", "value": "jakob" }, { "context": " _(x).pluck('name').sort().should.eql ['jakob', 'julia']\n ).then ->\n api.close(done)\n\n\n\n ", "end": 14337, "score": 0.9995529055595398, "start": 14332, "tag": "NAME", "value": "julia" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28 }, noErr())\n .post('stuffz', { nam", "end": 14699, "score": 0.9994099140167236, "start": 14694, "tag": "NAME", "value": "jakob" }, { "context": "ge: 28 }, noErr())\n .post('stuffz', { name: 'julia', age: 27 }, noErr())\n .getOne('stuffz', { f", "end": 14758, "score": 0.9997112154960632, "start": 14753, "tag": "NAME", "value": "julia" }, { "context": "Err())\n .getOne('stuffz', { filter: { name: 'sixten' } }, (err, x) ->\n err.should.eql new Erro", "end": 14830, "score": 0.979153037071228, "start": 14824, "tag": "NAME", "value": "sixten" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28, city: 'gbg' }, noErr())\n .post('s", "end": 15267, "score": 0.9995176792144775, "start": 15262, "tag": "NAME", "value": "jakob" }, { "context": " 'gbg' }, noErr())\n .post('stuffz', { name: 'julia', age: 27, city: 'gbg' }, noErr())\n .putOne(", "end": 15339, "score": 0.9997514486312866, "start": 15334, "tag": "NAME", "value": "julia" }, { "context": " .putOne('stuffz', { city: 'sthlm' }, { name: 'julia' }, noErr())\n .list('stuffz', { }, noErr (x)", "end": 15432, "score": 0.9997711777687073, "start": 15427, "tag": "NAME", "value": "julia" }, { "context": "hould.have.length 2\n x[0].name.should.eql 'jakob'\n x[0].age.should.eql 28\n x[0].city", "end": 15552, "score": 0.9996764659881592, "start": 15547, "tag": "NAME", "value": "jakob" }, { "context": "ty.should.eql 'gbg'\n x[1].name.should.eql 'julia'\n x[1].age.should.eql 27\n x[1].city", "end": 15655, "score": 0.9998193383216858, "start": 15650, "tag": "NAME", "value": "julia" }, { "context": "a, model, noErr())\n .post('stuffz', { name: 'jakob', age: 28, city: 'gbg' }, noErr())\n .post('s", "end": 16081, "score": 0.9996534585952759, "start": 16076, "tag": "NAME", "value": "jakob" }, { "context": " 'gbg' }, noErr())\n .post('stuffz', { name: 'julia', age: 27, city: 'gbg' }, noErr())\n .delOne(", "end": 16153, "score": 0.9998190402984619, "start": 16148, "tag": "NAME", "value": "julia" }, { "context": "gbg' }, noErr())\n .delOne('stuffz', { name: 'julia' }, noErr())\n .list('stuffz', { }, noErr (x)", "end": 16227, "score": 0.9998339414596558, "start": 16222, "tag": "NAME", "value": "julia" }, { "context": "hould.have.length 1\n x[0].name.should.eql 'jakob'\n x[0].age.should.eql 28\n x[0].city", "end": 16347, "score": 0.9996390342712402, "start": 16342, "tag": "NAME", "value": "jakob" }, { "context": "ata, model, noErr())\n .post('stuffz', { v1: 'jakob', v2: 12.5, v3: '2012-10-15', v4: true, v5: { v6:", "end": 16942, "score": 0.7587583065032959, "start": 16937, "tag": "NAME", "value": "jakob" }, { "context": ") -> _(x).omit('id')).should.eql [\n v1: 'jakob'\n v2: 12.5\n v3: '2012-10-15T00:", "end": 17167, "score": 0.8996716737747192, "start": 17162, "tag": "NAME", "value": "jakob" }, { "context": "ata, model, noErr())\n .post('stuffz', { v1: 'jakob', v2: 12.5, v3: '2012-10-15', v4: true, v5: { v6:", "end": 17827, "score": 0.8627450466156006, "start": 17822, "tag": "NAME", "value": "jakob" }, { "context": ") -> _(x).omit('id')).should.eql [\n v1: 'jakob'\n v2: 12.5\n v3: '2012-10-15T00:", "end": 18052, "score": 0.8936544060707092, "start": 18047, "tag": "NAME", "value": "jakob" }, { "context": " ]\n ).then('putOne', -> @ 'stuffz', { v1: 'jakob2', v3: '2012-10-15T13:37:00', v4: false, v5: { v6:", "end": 18249, "score": 0.8384647369384766, "start": 18243, "tag": "USERNAME", "value": "jakob2" }, { "context": " _(r).omit('id').should.eql\n v1: 'jakob2'\n v2: 12.5\n v3: '2012-10-15T13:", "end": 18408, "score": 0.8431569933891296, "start": 18402, "tag": "USERNAME", "value": "jakob2" }, { "context": " _(r).omit('id').should.eql\n v1: 'jakob2'\n v2: 12.5\n v3: '2012-10-15T13:", "end": 18684, "score": 0.9265788793563843, "start": 18681, "tag": "USERNAME", "value": "ob2" }, { "context": "ta, model, noErr())\n .post('warez', { name: 'jakob', stats: 1 }, noErr())\n .post('warez', { nam", "end": 22138, "score": 0.9996533393859863, "start": 22133, "tag": "NAME", "value": "jakob" }, { "context": "tats: 1 }, noErr())\n .post('warez', { name: 'erik', stats: 2 }, noErr())\n .post('warez', { nam", "end": 22196, "score": 0.9997742772102356, "start": 22192, "tag": "NAME", "value": "erik" }, { "context": "tats: 2 }, noErr())\n .post('warez', { name: 'julia', stats: 3 }, noErr())\n .list('warez', {}, n", "end": 22255, "score": 0.9997887015342712, "start": 22250, "tag": "NAME", "value": "julia" }, { "context": "list.map (x) -> x.name\n names.should.eql ['erik', 'jakob', 'julia']\n ).then ->\n api.c", "end": 22390, "score": 0.9997437596321106, "start": 22386, "tag": "NAME", "value": "erik" }, { "context": " (x) -> x.name\n names.should.eql ['erik', 'jakob', 'julia']\n ).then ->\n api.close(done", "end": 22399, "score": 0.999785304069519, "start": 22394, "tag": "NAME", "value": "jakob" }, { "context": ".name\n names.should.eql ['erik', 'jakob', 'julia']\n ).then ->\n api.close(done)\n\n\n\n ", "end": 22408, "score": 0.9997134804725647, "start": 22403, "tag": "NAME", "value": "julia" }, { "context": ", noErr ->\n api.post 'leet', { firstName: 'jakob', lastName: 'mattsson', age: 27 }, noErr (survey)", "end": 22831, "score": 0.9998111724853516, "start": 22826, "tag": "NAME", "value": "jakob" }, { "context": "api.post 'leet', { firstName: 'jakob', lastName: 'mattsson', age: 27 }, noErr (survey) ->\n survey.s", "end": 22853, "score": 0.9997302889823914, "start": 22845, "tag": "NAME", "value": "mattsson" }, { "context": " survey.should.eql { id: survey.id, firstName: 'jakob', lastName: 'mattsson', age: 27 }\n api.c", "end": 23020, "score": 0.9998151063919067, "start": 23015, "tag": "NAME", "value": "jakob" }, { "context": "l { id: survey.id, firstName: 'jakob', lastName: 'mattsson', age: 27 }\n api.close(done)\n\n\n\n it \"", "end": 23042, "score": 0.9997530579566956, "start": 23034, "tag": "NAME", "value": "mattsson" }, { "context": ") ->\n account.should.have.keys ['name', 'id']\n api.post 'companies', { name: 'n', or", "end": 25473, "score": 0.7736376523971558, "start": 25471, "tag": "KEY", "value": "id" }, { "context": "ccount) ->\n account.should.have.keys ['name', 'id']\n api.post 'companies', { name:", "end": 26317, "score": 0.970296323299408, "start": 26313, "tag": "KEY", "value": "name" }, { "context": "->\n account.should.have.keys ['name', 'id']\n api.post 'companies', { name: 'n', ", "end": 26323, "score": 0.9750732779502869, "start": 26321, "tag": "KEY", "value": "id" }, { "context": "r (account) ->\n account.should.have.keys ['name', 'id']\n saved.account = account\n ).t", "end": 27441, "score": 0.9552177786827087, "start": 27437, "tag": "KEY", "value": "name" }, { "context": "nt) ->\n account.should.have.keys ['name', 'id']\n saved.account = account\n ).then('p", "end": 27447, "score": 0.9650033116340637, "start": 27445, "tag": "KEY", "value": "id" }, { "context": " ).then('post', -> @ 'companies2', { name: 'n2', orgnr: 'nbr', account: saved.account.id }, noEr", "end": 27748, "score": 0.6119241118431091, "start": 27747, "tag": "NAME", "value": "2" }, { "context": "l, noErr ->\n api.post 'accounts', { name: 'a1' }, noErr (account) ->\n api.putOne 'acco", "end": 32050, "score": 0.7416774034500122, "start": 32048, "tag": "USERNAME", "value": "a1" }, { "context": "nt) ->\n api.putOne 'accounts', { name: 'n1' }, { id: 1 }, (err, data) ->\n err.sho", "end": 32118, "score": 0.784053385257721, "start": 32117, "tag": "USERNAME", "value": "1" }, { "context": "del, noErr ->\n api.post 'pizzas', { name: 'jakob' }, noErr (res) ->\n api.putOne 'pizzas',", "end": 32565, "score": 0.8921912312507629, "start": 32560, "tag": "USERNAME", "value": "jakob" }, { "context": "length % 2 == 0)\n\n indata = [\n name: 'jakob'\n response: 'something wrong'\n ,\n ", "end": 33111, "score": 0.9995952844619751, "start": 33106, "tag": "NAME", "value": "jakob" }, { "context": "esponse: 'something wrong'\n ,\n name: 'tobias'\n response: null\n ]\n\n api.connec", "end": 33178, "score": 0.9987550973892212, "start": 33172, "tag": "NAME", "value": "tobias" }, { "context": "unt) ->\n api.putOne 'accounts', { name: 'n1', age: 10, desc: 'test' }, { id: account.id }, (e", "end": 33961, "score": 0.7628028392791748, "start": 33959, "tag": "USERNAME", "value": "n1" } ]
src/base.coffee
jakobmattsson/manikin
0
assert = require 'assert' should = require 'should' async = require 'async' _ = require 'underscore' core = require './core' noErr = (cb) -> (err, args...) -> should.not.exist err cb(args...) if cb promise = core.promise exports.runTests = (manikin, dropDatabase, connectionData) -> it "should have the right methods", -> manikin.should.have.keys [ 'create' ] api = manikin.create() api.should.have.keys [ # support-methods 'connect' 'close' 'load' 'connectionData' # model operations 'post' 'list' 'getOne' 'delOne' 'putOne' 'getMany' 'delMany' 'postMany' ] describe 'Basic manikin', -> beforeEach (done) -> dropDatabase(connectionData, done) after (done) -> dropDatabase(connectionData, done) it "should be able to connect even if no models have been defined", (done) -> api = manikin.create() promise(api).connect connectionData, {}, noErr -> api.close(done) it "should raise an error if an invalid connection string is given", (done) -> api = manikin.create() api.connect "invalid-connection-string", {}, (err) -> should.exist err done() it "should be possible to load after connecting without a model", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.connect connectionData, noErr -> api.load mad, noErr -> api.post 'apa', { v1: '2' }, noErr -> api.close(done) it "should be possible to load first and then connect without a model", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.load mad, noErr -> api.connect connectionData, noErr -> api.post 'apa', { v1: '2' }, noErr -> api.close(done) it "connecting without a model and never loading will throw errors when used", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } # expecta att post throwar api.connect connectionData, noErr -> f = -> api.post('apa', { v2: '1', v1: '2' }, noErr) f.should.throw() api.close(done) describe 'connectionData', -> it "returns the data used to connect to the database", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.connect connectionData, noErr -> api.connectionData().should.eql connectionData done() describe 'should not save configuration between test runs', -> commonModelName = 'stuffzz' it "stores things for the first test run", (done) -> api = manikin.create() model = _.object([[commonModelName, fields: v1: 'string' ]]) promise(api).connect(connectionData, model, noErr()) .post(commonModelName, { v1: '2' }, noErr()) .list commonModelName, {}, noErr (list) -> list.length.should.eql 1 list[0].should.have.keys ['v1', 'id'] list[0].v1.should.eql '2' api.close(done) it "stores different things for the second test run", (done) -> api = manikin.create() model = _.object([[commonModelName, fields: v2: 'string' ]]) promise(api).connect(connectionData, model, noErr()) .post(commonModelName, { v2: '3' }, noErr()) .list commonModelName, {}, noErr (list) -> list.length.should.eql 1 list[0].should.have.keys ['v2', 'id'] list[0].v2.should.eql '3' api.close(done) it "should have a post operation that returns a copy of the given item and adds an ID", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} input = { name: 'jakob', age: 28 } promise(api).connect(connectionData, model, noErr()) .post('stuffz', input, noErr (obj) -> obj.should.have.keys ['id', 'name', 'age'] obj.id.should.be.a 'string' obj.name.should.eql 'jakob' obj.age.should.eql 28 obj.should.not.eql input ).then -> api.close(done) it "should set 'createdAt' automatically, if requested", (done) -> api = manikin.create() model = stuffz: createdAtField: 'created__at__123' fields: name: 'string' age: 'number' saved = {} now = new Date().getTime() promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28 }, noErr()) .list('stuffz', {}, noErr (list) -> list[0].created__at__123.should.not.be.below(now) list[0].created__at__123.should.not.be.above(now+1000) ).then -> api.close(done) it "should set 'updatedAt' automatically, if requested", (done) -> api = manikin.create() model = stuffz: updatedAtField: 'upd' fields: name: 'string' age: 'number' saved = {} now = new Date().getTime() promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28 }, noErr()) .list('stuffz', {}, noErr (list) -> list[0].upd.should.not.be.below(now) list[0].upd.should.not.be.above(now+1000) ).then -> api.close(done) it "should have post for creating and list for showing what has been created", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28 }, noErr()) .post('stuffz', { name: 'julia', age: 27 }, noErr()) .list('stuffz', {}, noErr (list) -> list.map((x) -> _(x).omit('id')).should.eql [ name: 'jakob' age: 28 , name: 'julia' age: 27 ] ).then -> api.close(done) it "creates unique ids for all items posted", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28 }, noErr()) .post('stuffz', { name: 'julia', age: 27 }, noErr()) .list('stuffz', {}, noErr (list) -> list.should.have.length 2 list[0].should.have.keys ['name', 'age', 'id'] list[0].id.should.be.a.string list[1].should.have.keys ['name', 'age', 'id'] list[1].id.should.be.a.string list[0].id.should.not.eql list[1].id ).then -> api.close(done) it "can list objects from their ID", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28 }, noErr()) .post('stuffz', { name: 'julia', age: 27 }, noErr (x) -> saved.id = x.id ).then('list', -> @ 'stuffz', { filter: { id: saved.id } }, noErr (x) -> x.should.have.length 1 x[0].should.eql { id: saved.id name: 'julia' age: 27 } ).then -> api.close(done) it "can list objects from any of its properties", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28 }, noErr()) .post('stuffz', { name: 'jakob', age: 42 }, noErr()) .post('stuffz', { name: 'julia', age: 27 }, noErr()) .list('stuffz', { filter: { name: 'jakob' } }, noErr (x) -> x.should.have.length 2 x[0].name.should.eql 'jakob' x[0].age.should.eql 28 x[1].name.should.eql 'jakob' x[1].age.should.eql 42 ).then -> api.close(done) it "can list objects from any combination of their properties", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' city: 'string' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28, city: 'gbg' }, noErr()) .post('stuffz', { name: 'julia', age: 27, city: 'gbg' }, noErr()) .post('stuffz', { name: 'jakob', age: 28, city: 'sthlm' }, noErr()) .post('stuffz', { name: 'julia', age: 27, city: 'sthlm' }, noErr()) .list('stuffz', { filter: { name: 'jakob', city: 'sthlm' } }, noErr (x) -> x.should.have.length 1 x[0].name.should.eql 'jakob' x[0].age.should.eql 28 x[0].city.should.eql 'sthlm' ).then -> api.close(done) it "can sort objects", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28 }, noErr()) .post('stuffz', { name: 'jakob', age: 42 }, noErr()) .post('stuffz', { name: 'julia', age: 27 }, noErr()) .list('stuffz', { sort: { age: 'asc' } }, noErr (x) -> x.should.have.length 3 x[0].age.should.eql 27 x[1].age.should.eql 28 x[2].age.should.eql 42 ).then -> api.close(done) it "can limit number of results returned", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28 }, noErr()) .post('stuffz', { name: 'jakob', age: 42 }, noErr()) .post('stuffz', { name: 'julia', age: 27 }, noErr()) .list('stuffz', { limit: 2 }, noErr (x) -> x.should.have.length 2 ).then -> api.close(done) it "can skip items", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28 }, noErr()) .post('stuffz', { name: 'jakob', age: 42 }, noErr()) .post('stuffz', { name: 'julia', age: 27 }, noErr()) .list('stuffz', { skip: 2 }, noErr (x) -> x.should.have.length 1 ).then -> api.close(done) it "can sort objects in a descending", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28 }, noErr()) .post('stuffz', { name: 'jakob', age: 42 }, noErr()) .post('stuffz', { name: 'julia', age: 27 }, noErr()) .list('stuffz', { sort: { age: 'desc' } }, noErr (x) -> x.should.have.length 3 x[0].age.should.eql 42 x[1].age.should.eql 28 x[2].age.should.eql 27 ).then -> api.close(done) it "can get a single object from its ID", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28 }, noErr()) .post('stuffz', { name: 'julia', age: 27 }, noErr (x) -> saved.id = x.id ).then('getOne', -> @ 'stuffz', { filter: { id: saved.id } }, noErr (x) -> x.should.eql { id: saved.id name: 'julia' age: 27 } ).then -> api.close(done) it "can get a single object from any of its properties", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28 }, noErr()) .post('stuffz', { name: 'julia', age: 27 }, noErr()) .getOne('stuffz', { filter: { name: 'jakob' } }, noErr (x) -> x.name.should.eql 'jakob' x.age.should.eql 28 ).then -> api.close(done) it "can get a single object from any combination of its properties", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' city: 'string' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28, city: 'gbg' }, noErr()) .post('stuffz', { name: 'julia', age: 27, city: 'gbg' }, noErr()) .post('stuffz', { name: 'jakob', age: 28, city: 'sthlm' }, noErr()) .post('stuffz', { name: 'julia', age: 27, city: 'sthlm' }, noErr()) .getOne('stuffz', { filter: { name: 'jakob', city: 'sthlm' } }, noErr (x) -> x.name.should.eql 'jakob' x.age.should.eql 28 x.city.should.eql 'sthlm' ).then -> api.close(done) it "can filter out objects using an array of valid values", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28 }, noErr()) .post('stuffz', { name: 'julia', age: 27 }, noErr()) .post('stuffz', { name: 'sixten', age: 16 }, noErr()) .list('stuffz', { filter: { age: [28, 27] } }, noErr (x) -> _(x).pluck('name').sort().should.eql ['jakob', 'julia'] ).then -> api.close(done) it "calls back with an error if no objects where found", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28 }, noErr()) .post('stuffz', { name: 'julia', age: 27 }, noErr()) .getOne('stuffz', { filter: { name: 'sixten' } }, (err, x) -> err.should.eql new Error() should.not.exist x ).then -> api.close(done) it "can update an object", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' city: 'string' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28, city: 'gbg' }, noErr()) .post('stuffz', { name: 'julia', age: 27, city: 'gbg' }, noErr()) .putOne('stuffz', { city: 'sthlm' }, { name: 'julia' }, noErr()) .list('stuffz', { }, noErr (x) -> x.should.have.length 2 x[0].name.should.eql 'jakob' x[0].age.should.eql 28 x[0].city.should.eql 'gbg' x[1].name.should.eql 'julia' x[1].age.should.eql 27 x[1].city.should.eql 'sthlm' ).then -> api.close(done) it "can delete an object", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' city: 'string' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'jakob', age: 28, city: 'gbg' }, noErr()) .post('stuffz', { name: 'julia', age: 27, city: 'gbg' }, noErr()) .delOne('stuffz', { name: 'julia' }, noErr()) .list('stuffz', { }, noErr (x) -> x.should.have.length 1 x[0].name.should.eql 'jakob' x[0].age.should.eql 28 x[0].city.should.eql 'gbg' ).then -> api.close(done) it "should allow a basic set of primitive data types to be stored and retrieved", (done) -> api = manikin.create() model = stuffz: fields: v1: 'string' v2: 'number' v3: 'date' v4: 'boolean' v5: type: 'nested' v6: 'string' v7: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { v1: 'jakob', v2: 12.5, v3: '2012-10-15', v4: true, v5: { v6: 'nest', v7: 7 } }, noErr()) .list('stuffz', {}, noErr (list) -> saved.id = list[0].id list.map((x) -> _(x).omit('id')).should.eql [ v1: 'jakob' v2: 12.5 v3: '2012-10-15T00:00:00.000Z' v4: true v5: v6: 'nest' v7: 7 ] ).then -> api.close(done) it "should allow a basic set of primitive data types to be updated", (done) -> api = manikin.create() model = stuffz: fields: v1: 'string' v2: 'number' v3: 'date' v4: 'boolean' v5: type: 'nested' v6: 'string' v7: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { v1: 'jakob', v2: 12.5, v3: '2012-10-15', v4: true, v5: { v6: 'nest', v7: 7 } }, noErr()) .list('stuffz', {}, noErr (list) -> saved.id = list[0].id list.map((x) -> _(x).omit('id')).should.eql [ v1: 'jakob' v2: 12.5 v3: '2012-10-15T00:00:00.000Z' v4: true v5: v6: 'nest' v7: 7 ] ).then('putOne', -> @ 'stuffz', { v1: 'jakob2', v3: '2012-10-15T13:37:00', v4: false, v5: { v6: 'nest2', v7: 14 } }, { id: saved.id }, noErr (r) -> _(r).omit('id').should.eql v1: 'jakob2' v2: 12.5 v3: '2012-10-15T13:37:00.000Z' v4: false v5: v6: 'nest2' v7: 14 ).then('getOne', -> @ 'stuffz', { filter: { id: saved.id } }, noErr (r) -> _(r).omit('id').should.eql v1: 'jakob2' v2: 12.5 v3: '2012-10-15T13:37:00.000Z' v4: false v5: v6: 'nest2' v7: 14 ).then -> api.close(done) it "should allow posting to nested properties", (done) -> api = manikin.create() model = stuffz: fields: v1: 'string' v5: type: 'nested' v6: 'string' v7: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { v1: 'hej', v5: { v6: 'nest', v7: 7 } }, noErr()) .then -> api.close(done) it "should allow putting null to nested properties", (done) -> api = manikin.create() model = stuffz: fields: v1: 'string' v5: type: 'nested' v6: 'string' v7: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { v1: 'hej', v5: { v6: 'nest', v7: 7 } }, noErr (v) -> saved.id = v.id ).then('putOne', -> @ 'stuffz', { v1: 'jakob2', v5: null }, { id: saved.id }, noErr (r) -> ).then -> api.close(done) it "should detect when an object id does not exist", (done) -> api = manikin.create() model = table: fields: v1: 'string' promise(api).connect(connectionData, model, noErr()) .getOne 'table', { filter: { id: '123' } }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' should.not.exist data .delOne('table', { id: '123' }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' should.not.exist data ).then -> api.close(done) it "should return an error in the callback if the given model does not exist in a listing", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.load mad, noErr -> api.connect connectionData, noErr -> api.list 'non-existing', { filter: { v2: '1', v1: '2' } }, (err) -> err.should.eql new Error() err.toString().should.eql 'Error: No model named non-existing' api.close(done) it "should allow mixed properties in models definitions", (done) -> api = manikin.create() model = stuffs: owners: {} fields: name: { type: 'string' } stats: { type: 'mixed' } api.connect connectionData, model, noErr -> api.post 'stuffs', { name: 'a1', stats: { s1: 's1', s2: 2 } }, noErr (survey) -> survey.should.have.keys ['id', 'name', 'stats'] survey.stats.should.have.keys ['s1', 's2'] api.putOne "stuffs", { name: 'a2', stats: { x: 1 } }, { id: survey.id }, noErr (survey) -> survey.should.have.keys ['id', 'name', 'stats'] survey.stats.should.have.keys ['x'] api.close(done) it "should allow default sorting orders", (done) -> api = manikin.create() model = warez: owners: {} defaultSort: 'name' fields: name: { type: 'string' } stats: { type: 'mixed' } promise(api).connect(connectionData, model, noErr()) .post('warez', { name: 'jakob', stats: 1 }, noErr()) .post('warez', { name: 'erik', stats: 2 }, noErr()) .post('warez', { name: 'julia', stats: 3 }, noErr()) .list('warez', {}, noErr (list) -> names = list.map (x) -> x.name names.should.eql ['erik', 'jakob', 'julia'] ).then -> api.close(done) it "should allow simplified field declarations (specifying type only)", (done) -> api = manikin.create() model = leet: owners: {} fields: firstName: 'string' lastName: { type: 'string' } age: 'number' api.connect connectionData, model, noErr -> api.post 'leet', { firstName: 'jakob', lastName: 'mattsson', age: 27 }, noErr (survey) -> survey.should.have.keys ['id', 'firstName', 'lastName', 'age'] survey.should.eql { id: survey.id, firstName: 'jakob', lastName: 'mattsson', age: 27 } api.close(done) it "should detect when an filter matches no objects on getOne", (done) -> api = manikin.create() model = table: fields: v1: 'string' promise(api).connect(connectionData, model, noErr()) .getOne('table', { filter: { v1: '123' } }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No match' should.not.exist data ).then -> api.close(done) it "should detect when an filter matches no objects on delOne", (done) -> api = manikin.create() model = table: fields: v1: 'string' promise(api).connect(connectionData, model, noErr()) .delOne('table', { v1: '123' }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' should.not.exist data ).then -> api.close(done) it "should be possible to specifiy the owner together with the fields when creating an object", (done) -> api = manikin.create() model = accounts: owners: {} fields: name: { type: 'string', default: '' } companies: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'accounts', { name: 'a1' }, noErr (account) -> account.should.have.keys ['name', 'id'] api.post 'companies', { name: 'n', orgnr: 'nbr', account: account.id }, noErr (company) -> _(company).omit('id').should.eql { account: account.id name: 'n' orgnr: 'nbr' } api.close(done) it "should not be ok to post without specifiying the owner", (done) -> api = manikin.create() model = accounts: owners: {} fields: name: { type: 'string', default: '' } companies: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'accounts', { name: 'a1' }, noErr (account) -> account.should.have.keys ['name', 'id'] api.post 'companies', { name: 'n', orgnr: 'nbr' }, (err, company) -> should.exist err # expect something more precise... api.close(done) it "must specify an existing owner of the right type when posting", (done) -> api = manikin.create() model = stuff: fields: {} accounts: owners: {} fields: name: { type: 'string', default: '' } companies: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'stuff', { }, noErr (stuff) -> api.post 'accounts', { name: 'a1' }, noErr (account) -> account.should.have.keys ['name', 'id'] api.post 'companies', { name: 'n', orgnr: 'nbr', account: stuff.id }, (err, company) -> should.exist err # expect something more precise... api.close(done) it "should introduce redundant references to all ancestors", (done) -> api = manikin.create() model = accounts: owners: {} fields: name: { type: 'string', default: '' } companies2: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } contacts: owners: company: 'companies2' fields: email: { type: 'string', default: '' } phone: { type: 'string', default: '' } pets: owners: contact: 'contacts' fields: race: { type: 'string', default: '' } saved = {} promise(api).connect(connectionData, model, noErr()) .post('accounts', { name: 'a1' }, noErr (account) -> account.should.have.keys ['name', 'id'] saved.account = account ).then('post', -> @ 'companies2', { name: 'n', orgnr: 'nbr', account: saved.account.id }, noErr (company) -> saved.company = company company.should.have.keys ['id', 'name', 'orgnr', 'account'] ).then('post', -> @ 'companies2', { name: 'n2', orgnr: 'nbr', account: saved.account.id }, noErr (company2) -> saved.company2 = company2 company2.should.have.keys ['id', 'name', 'orgnr', 'account'] ).then('post', -> @ 'contacts', { email: '@', phone: '112', company: saved.company.id }, noErr (contact) -> saved.contact = contact contact.should.have.keys ['id', 'email', 'phone', 'account', 'company'] ).then('post', -> @ 'contacts', { email: '@2', phone: '911', company: saved.company2.id }, noErr (contact2) -> saved.contact2 = contact2 contact2.should.have.keys ['id', 'email', 'phone', 'account', 'company'] ).then('post', -> @ 'pets', { race: 'dog', contact: saved.contact.id }, noErr (pet) -> pet.should.have.keys ['id', 'race', 'account', 'company', 'contact'] pet.contact.should.eql saved.contact.id pet.company.should.eql saved.company.id pet.account.should.eql saved.account.id ).then('post', -> @ 'pets', { race: 'dog', contact: saved.contact2.id }, noErr (pet) -> pet.should.have.keys ['id', 'race', 'account', 'company', 'contact'] pet.contact.should.eql saved.contact2.id pet.company.should.eql saved.company2.id pet.account.should.eql saved.account.id ).list('pets', {}, noErr ((res) -> res.length.should.eql 2)) .list('contacts', {}, noErr ((res) -> res.length.should.eql 2)) .list('companies2', {}, noErr ((res) -> res.length.should.eql 2)) .list('accounts', {}, noErr ((res) -> res.length.should.eql 1)) .then -> api.close(done) it "should delete owned objects when deleting ancestors", (done) -> api = manikin.create() model = accounts: owners: {} fields: name: { type: 'string', default: '' } companies2: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } contacts: owners: company: 'companies2' fields: email: { type: 'string', default: '' } phone: { type: 'string', default: '' } pets: owners: contact: 'contacts' fields: race: { type: 'string', default: '' } saved = {} promise(api).connect(connectionData, model, noErr()) .post('accounts', { name: 'a1' }, noErr (account) -> saved.account = account ).then('post', -> @ 'companies2', { name: 'n', orgnr: 'nbr', account: saved.account.id }, noErr (company) -> saved.company = company ).then('post', -> @ 'companies2', { name: 'n2', orgnr: 'nbr', account: saved.account.id }, noErr (company2) -> saved.company2 = company2 ).then('post', -> @ 'contacts', { email: '@', phone: '112', company: saved.company.id }, noErr (contact) -> saved.contact = contact ).then('post', -> @ 'contacts', { email: '@2', phone: '911', company: saved.company2.id }, noErr (contact2) -> saved.contact2 = contact2 ).then('post', -> @ 'pets', { race: 'dog', contact: saved.contact.id }, noErr (pet) -> ).then('post', -> @ 'pets', { race: 'dog', contact: saved.contact2.id }, noErr (pet) -> ).list('pets', {}, noErr ((res) -> res.length.should.eql 2)) .list('contacts', {}, noErr ((res) -> res.length.should.eql 2)) .list('companies2', {}, noErr ((res) -> res.length.should.eql 2)) .list('accounts', {}, noErr ((res) -> res.length.should.eql 1)) .then('delOne', -> @ 'companies2', { id: saved.company.id }, noErr()) .list('pets', {}, noErr ((res) -> res.length.should.eql 1)) .list('contacts', {}, noErr ((res) -> res.length.should.eql 1)) .list('companies2', {}, noErr ((res) -> res.length.should.eql 1)) .list('accounts', {}, noErr ((res) -> res.length.should.eql 1)) .then -> api.close(done) it "should raise an error if a putOne attempts to put using an id from another collection", (done) -> api = manikin.create() model = accounts: fields: name: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'accounts', { name: 'a1' }, noErr (account) -> api.putOne 'accounts', { name: 'n1' }, { id: 1 }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' api.close(done) it "should allow undefined values", (done) -> api = manikin.create() model = pizzas: owners: {} fields: name: type: 'string' api.connect connectionData, model, noErr -> api.post 'pizzas', { name: 'jakob' }, noErr (res) -> api.putOne 'pizzas', { name: undefined }, { id: res.id }, noErr (res) -> should.not.exist res.name api.close(done) it "should allow custom validators", (done) -> api = manikin.create() model = pizzas: owners: {} fields: name: type: 'string' validate: (apiRef, value, callback) -> api.should.eql apiRef callback(value.length % 2 == 0) indata = [ name: 'jakob' response: 'something wrong' , name: 'tobias' response: null ] api.connect connectionData, model, noErr -> async.forEach indata, (d, callback) -> api.post 'pizzas', { name: d.name }, (err, res) -> if d.response != null err.message.should.match /Validation failed/i err.errors.name.path.should.eql 'name' callback() , -> api.close(done) it "should raise an error if a putOne attempts to put non-existing fields", (done) -> api = manikin.create() model = accounts: fields: name: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'accounts', { name: 'a1' }, noErr (account) -> api.putOne 'accounts', { name: 'n1', age: 10, desc: 'test' }, { id: account.id }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: Invalid fields: age, desc' api.close(done) it "should raise an error if a post attempts to put nonexisting fields", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.connect connectionData, noErr -> api.load mad, noErr -> api.post 'apa', { v1: '2', v2: '1' }, (err) -> err.should.eql new Error() err.toString().should.eql 'Error: Invalid fields: v2' api.close(done) it "should raise an error if a putOne attempts to put using an id from another collection", (done) -> api = manikin.create() model = accounts: fields: name: { type: 'string', default: '' } other: fields: name: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'other', { name: 'a1' }, noErr (other) -> api.post 'accounts', { name: 'a1' }, noErr (account) -> api.putOne 'accounts', { name: 'n1' }, { id: other.id }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' api.close(done)
130911
assert = require 'assert' should = require 'should' async = require 'async' _ = require 'underscore' core = require './core' noErr = (cb) -> (err, args...) -> should.not.exist err cb(args...) if cb promise = core.promise exports.runTests = (manikin, dropDatabase, connectionData) -> it "should have the right methods", -> manikin.should.have.keys [ 'create' ] api = manikin.create() api.should.have.keys [ # support-methods 'connect' 'close' 'load' 'connectionData' # model operations 'post' 'list' 'getOne' 'delOne' 'putOne' 'getMany' 'delMany' 'postMany' ] describe 'Basic manikin', -> beforeEach (done) -> dropDatabase(connectionData, done) after (done) -> dropDatabase(connectionData, done) it "should be able to connect even if no models have been defined", (done) -> api = manikin.create() promise(api).connect connectionData, {}, noErr -> api.close(done) it "should raise an error if an invalid connection string is given", (done) -> api = manikin.create() api.connect "invalid-connection-string", {}, (err) -> should.exist err done() it "should be possible to load after connecting without a model", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.connect connectionData, noErr -> api.load mad, noErr -> api.post 'apa', { v1: '2' }, noErr -> api.close(done) it "should be possible to load first and then connect without a model", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.load mad, noErr -> api.connect connectionData, noErr -> api.post 'apa', { v1: '2' }, noErr -> api.close(done) it "connecting without a model and never loading will throw errors when used", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } # expecta att post throwar api.connect connectionData, noErr -> f = -> api.post('apa', { v2: '1', v1: '2' }, noErr) f.should.throw() api.close(done) describe 'connectionData', -> it "returns the data used to connect to the database", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.connect connectionData, noErr -> api.connectionData().should.eql connectionData done() describe 'should not save configuration between test runs', -> commonModelName = 'stuffzz' it "stores things for the first test run", (done) -> api = manikin.create() model = _.object([[commonModelName, fields: v1: 'string' ]]) promise(api).connect(connectionData, model, noErr()) .post(commonModelName, { v1: '2' }, noErr()) .list commonModelName, {}, noErr (list) -> list.length.should.eql 1 list[0].should.have.keys ['v1', 'id'] list[0].v1.should.eql '2' api.close(done) it "stores different things for the second test run", (done) -> api = manikin.create() model = _.object([[commonModelName, fields: v2: 'string' ]]) promise(api).connect(connectionData, model, noErr()) .post(commonModelName, { v2: '3' }, noErr()) .list commonModelName, {}, noErr (list) -> list.length.should.eql 1 list[0].should.have.keys ['v2', 'id'] list[0].v2.should.eql '3' api.close(done) it "should have a post operation that returns a copy of the given item and adds an ID", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} input = { name: '<NAME>', age: 28 } promise(api).connect(connectionData, model, noErr()) .post('stuffz', input, noErr (obj) -> obj.should.have.keys ['id', 'name', 'age'] obj.id.should.be.a 'string' obj.name.should.eql '<NAME>' obj.age.should.eql 28 obj.should.not.eql input ).then -> api.close(done) it "should set 'createdAt' automatically, if requested", (done) -> api = manikin.create() model = stuffz: createdAtField: 'created__at__123' fields: name: 'string' age: 'number' saved = {} now = new Date().getTime() promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28 }, noErr()) .list('stuffz', {}, noErr (list) -> list[0].created__at__123.should.not.be.below(now) list[0].created__at__123.should.not.be.above(now+1000) ).then -> api.close(done) it "should set 'updatedAt' automatically, if requested", (done) -> api = manikin.create() model = stuffz: updatedAtField: 'upd' fields: name: 'string' age: 'number' saved = {} now = new Date().getTime() promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28 }, noErr()) .list('stuffz', {}, noErr (list) -> list[0].upd.should.not.be.below(now) list[0].upd.should.not.be.above(now+1000) ).then -> api.close(done) it "should have post for creating and list for showing what has been created", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28 }, noErr()) .post('stuffz', { name: '<NAME>', age: 27 }, noErr()) .list('stuffz', {}, noErr (list) -> list.map((x) -> _(x).omit('id')).should.eql [ name: '<NAME>' age: 28 , name: '<NAME>' age: 27 ] ).then -> api.close(done) it "creates unique ids for all items posted", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28 }, noErr()) .post('stuffz', { name: '<NAME>', age: 27 }, noErr()) .list('stuffz', {}, noErr (list) -> list.should.have.length 2 list[0].should.have.keys ['name', 'age', 'id'] list[0].id.should.be.a.string list[1].should.have.keys ['name', 'age', 'id'] list[1].id.should.be.a.string list[0].id.should.not.eql list[1].id ).then -> api.close(done) it "can list objects from their ID", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28 }, noErr()) .post('stuffz', { name: '<NAME>', age: 27 }, noErr (x) -> saved.id = x.id ).then('list', -> @ 'stuffz', { filter: { id: saved.id } }, noErr (x) -> x.should.have.length 1 x[0].should.eql { id: saved.id name: '<NAME>' age: 27 } ).then -> api.close(done) it "can list objects from any of its properties", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28 }, noErr()) .post('stuffz', { name: '<NAME>', age: 42 }, noErr()) .post('stuffz', { name: '<NAME>', age: 27 }, noErr()) .list('stuffz', { filter: { name: '<NAME>' } }, noErr (x) -> x.should.have.length 2 x[0].name.should.eql '<NAME>' x[0].age.should.eql 28 x[1].name.should.eql '<NAME>' x[1].age.should.eql 42 ).then -> api.close(done) it "can list objects from any combination of their properties", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' city: 'string' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28, city: 'gbg' }, noErr()) .post('stuffz', { name: '<NAME>', age: 27, city: 'gbg' }, noErr()) .post('stuffz', { name: '<NAME>', age: 28, city: 'sthlm' }, noErr()) .post('stuffz', { name: '<NAME>', age: 27, city: 'sthlm' }, noErr()) .list('stuffz', { filter: { name: '<NAME>', city: 'sthlm' } }, noErr (x) -> x.should.have.length 1 x[0].name.should.eql '<NAME>' x[0].age.should.eql 28 x[0].city.should.eql 'sthlm' ).then -> api.close(done) it "can sort objects", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28 }, noErr()) .post('stuffz', { name: '<NAME>', age: 42 }, noErr()) .post('stuffz', { name: '<NAME>', age: 27 }, noErr()) .list('stuffz', { sort: { age: 'asc' } }, noErr (x) -> x.should.have.length 3 x[0].age.should.eql 27 x[1].age.should.eql 28 x[2].age.should.eql 42 ).then -> api.close(done) it "can limit number of results returned", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28 }, noErr()) .post('stuffz', { name: '<NAME>', age: 42 }, noErr()) .post('stuffz', { name: '<NAME>', age: 27 }, noErr()) .list('stuffz', { limit: 2 }, noErr (x) -> x.should.have.length 2 ).then -> api.close(done) it "can skip items", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28 }, noErr()) .post('stuffz', { name: '<NAME>', age: 42 }, noErr()) .post('stuffz', { name: '<NAME>', age: 27 }, noErr()) .list('stuffz', { skip: 2 }, noErr (x) -> x.should.have.length 1 ).then -> api.close(done) it "can sort objects in a descending", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28 }, noErr()) .post('stuffz', { name: '<NAME>', age: 42 }, noErr()) .post('stuffz', { name: '<NAME>', age: 27 }, noErr()) .list('stuffz', { sort: { age: 'desc' } }, noErr (x) -> x.should.have.length 3 x[0].age.should.eql 42 x[1].age.should.eql 28 x[2].age.should.eql 27 ).then -> api.close(done) it "can get a single object from its ID", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28 }, noErr()) .post('stuffz', { name: '<NAME>', age: 27 }, noErr (x) -> saved.id = x.id ).then('getOne', -> @ 'stuffz', { filter: { id: saved.id } }, noErr (x) -> x.should.eql { id: saved.id name: '<NAME>' age: 27 } ).then -> api.close(done) it "can get a single object from any of its properties", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28 }, noErr()) .post('stuffz', { name: '<NAME>', age: 27 }, noErr()) .getOne('stuffz', { filter: { name: '<NAME>' } }, noErr (x) -> x.name.should.eql '<NAME>' x.age.should.eql 28 ).then -> api.close(done) it "can get a single object from any combination of its properties", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' city: 'string' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28, city: 'gbg' }, noErr()) .post('stuffz', { name: '<NAME>', age: 27, city: 'gbg' }, noErr()) .post('stuffz', { name: '<NAME>', age: 28, city: 'sthlm' }, noErr()) .post('stuffz', { name: '<NAME>', age: 27, city: 'sthlm' }, noErr()) .getOne('stuffz', { filter: { name: '<NAME>', city: 'sthlm' } }, noErr (x) -> x.name.should.eql '<NAME>' x.age.should.eql 28 x.city.should.eql 'sthlm' ).then -> api.close(done) it "can filter out objects using an array of valid values", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28 }, noErr()) .post('stuffz', { name: '<NAME>', age: 27 }, noErr()) .post('stuffz', { name: '<NAME>', age: 16 }, noErr()) .list('stuffz', { filter: { age: [28, 27] } }, noErr (x) -> _(x).pluck('name').sort().should.eql ['<NAME>', '<NAME>'] ).then -> api.close(done) it "calls back with an error if no objects where found", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28 }, noErr()) .post('stuffz', { name: '<NAME>', age: 27 }, noErr()) .getOne('stuffz', { filter: { name: '<NAME>' } }, (err, x) -> err.should.eql new Error() should.not.exist x ).then -> api.close(done) it "can update an object", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' city: 'string' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28, city: 'gbg' }, noErr()) .post('stuffz', { name: '<NAME>', age: 27, city: 'gbg' }, noErr()) .putOne('stuffz', { city: 'sthlm' }, { name: '<NAME>' }, noErr()) .list('stuffz', { }, noErr (x) -> x.should.have.length 2 x[0].name.should.eql '<NAME>' x[0].age.should.eql 28 x[0].city.should.eql 'gbg' x[1].name.should.eql '<NAME>' x[1].age.should.eql 27 x[1].city.should.eql 'sthlm' ).then -> api.close(done) it "can delete an object", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' city: 'string' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: '<NAME>', age: 28, city: 'gbg' }, noErr()) .post('stuffz', { name: '<NAME>', age: 27, city: 'gbg' }, noErr()) .delOne('stuffz', { name: '<NAME>' }, noErr()) .list('stuffz', { }, noErr (x) -> x.should.have.length 1 x[0].name.should.eql '<NAME>' x[0].age.should.eql 28 x[0].city.should.eql 'gbg' ).then -> api.close(done) it "should allow a basic set of primitive data types to be stored and retrieved", (done) -> api = manikin.create() model = stuffz: fields: v1: 'string' v2: 'number' v3: 'date' v4: 'boolean' v5: type: 'nested' v6: 'string' v7: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { v1: '<NAME>', v2: 12.5, v3: '2012-10-15', v4: true, v5: { v6: 'nest', v7: 7 } }, noErr()) .list('stuffz', {}, noErr (list) -> saved.id = list[0].id list.map((x) -> _(x).omit('id')).should.eql [ v1: '<NAME>' v2: 12.5 v3: '2012-10-15T00:00:00.000Z' v4: true v5: v6: 'nest' v7: 7 ] ).then -> api.close(done) it "should allow a basic set of primitive data types to be updated", (done) -> api = manikin.create() model = stuffz: fields: v1: 'string' v2: 'number' v3: 'date' v4: 'boolean' v5: type: 'nested' v6: 'string' v7: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { v1: '<NAME>', v2: 12.5, v3: '2012-10-15', v4: true, v5: { v6: 'nest', v7: 7 } }, noErr()) .list('stuffz', {}, noErr (list) -> saved.id = list[0].id list.map((x) -> _(x).omit('id')).should.eql [ v1: '<NAME>' v2: 12.5 v3: '2012-10-15T00:00:00.000Z' v4: true v5: v6: 'nest' v7: 7 ] ).then('putOne', -> @ 'stuffz', { v1: 'jakob2', v3: '2012-10-15T13:37:00', v4: false, v5: { v6: 'nest2', v7: 14 } }, { id: saved.id }, noErr (r) -> _(r).omit('id').should.eql v1: 'jakob2' v2: 12.5 v3: '2012-10-15T13:37:00.000Z' v4: false v5: v6: 'nest2' v7: 14 ).then('getOne', -> @ 'stuffz', { filter: { id: saved.id } }, noErr (r) -> _(r).omit('id').should.eql v1: 'jakob2' v2: 12.5 v3: '2012-10-15T13:37:00.000Z' v4: false v5: v6: 'nest2' v7: 14 ).then -> api.close(done) it "should allow posting to nested properties", (done) -> api = manikin.create() model = stuffz: fields: v1: 'string' v5: type: 'nested' v6: 'string' v7: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { v1: 'hej', v5: { v6: 'nest', v7: 7 } }, noErr()) .then -> api.close(done) it "should allow putting null to nested properties", (done) -> api = manikin.create() model = stuffz: fields: v1: 'string' v5: type: 'nested' v6: 'string' v7: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { v1: 'hej', v5: { v6: 'nest', v7: 7 } }, noErr (v) -> saved.id = v.id ).then('putOne', -> @ 'stuffz', { v1: 'jakob2', v5: null }, { id: saved.id }, noErr (r) -> ).then -> api.close(done) it "should detect when an object id does not exist", (done) -> api = manikin.create() model = table: fields: v1: 'string' promise(api).connect(connectionData, model, noErr()) .getOne 'table', { filter: { id: '123' } }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' should.not.exist data .delOne('table', { id: '123' }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' should.not.exist data ).then -> api.close(done) it "should return an error in the callback if the given model does not exist in a listing", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.load mad, noErr -> api.connect connectionData, noErr -> api.list 'non-existing', { filter: { v2: '1', v1: '2' } }, (err) -> err.should.eql new Error() err.toString().should.eql 'Error: No model named non-existing' api.close(done) it "should allow mixed properties in models definitions", (done) -> api = manikin.create() model = stuffs: owners: {} fields: name: { type: 'string' } stats: { type: 'mixed' } api.connect connectionData, model, noErr -> api.post 'stuffs', { name: 'a1', stats: { s1: 's1', s2: 2 } }, noErr (survey) -> survey.should.have.keys ['id', 'name', 'stats'] survey.stats.should.have.keys ['s1', 's2'] api.putOne "stuffs", { name: 'a2', stats: { x: 1 } }, { id: survey.id }, noErr (survey) -> survey.should.have.keys ['id', 'name', 'stats'] survey.stats.should.have.keys ['x'] api.close(done) it "should allow default sorting orders", (done) -> api = manikin.create() model = warez: owners: {} defaultSort: 'name' fields: name: { type: 'string' } stats: { type: 'mixed' } promise(api).connect(connectionData, model, noErr()) .post('warez', { name: '<NAME>', stats: 1 }, noErr()) .post('warez', { name: '<NAME>', stats: 2 }, noErr()) .post('warez', { name: '<NAME>', stats: 3 }, noErr()) .list('warez', {}, noErr (list) -> names = list.map (x) -> x.name names.should.eql ['<NAME>', '<NAME>', '<NAME>'] ).then -> api.close(done) it "should allow simplified field declarations (specifying type only)", (done) -> api = manikin.create() model = leet: owners: {} fields: firstName: 'string' lastName: { type: 'string' } age: 'number' api.connect connectionData, model, noErr -> api.post 'leet', { firstName: '<NAME>', lastName: '<NAME>', age: 27 }, noErr (survey) -> survey.should.have.keys ['id', 'firstName', 'lastName', 'age'] survey.should.eql { id: survey.id, firstName: '<NAME>', lastName: '<NAME>', age: 27 } api.close(done) it "should detect when an filter matches no objects on getOne", (done) -> api = manikin.create() model = table: fields: v1: 'string' promise(api).connect(connectionData, model, noErr()) .getOne('table', { filter: { v1: '123' } }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No match' should.not.exist data ).then -> api.close(done) it "should detect when an filter matches no objects on delOne", (done) -> api = manikin.create() model = table: fields: v1: 'string' promise(api).connect(connectionData, model, noErr()) .delOne('table', { v1: '123' }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' should.not.exist data ).then -> api.close(done) it "should be possible to specifiy the owner together with the fields when creating an object", (done) -> api = manikin.create() model = accounts: owners: {} fields: name: { type: 'string', default: '' } companies: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'accounts', { name: 'a1' }, noErr (account) -> account.should.have.keys ['name', 'id'] api.post 'companies', { name: 'n', orgnr: 'nbr', account: account.id }, noErr (company) -> _(company).omit('id').should.eql { account: account.id name: 'n' orgnr: 'nbr' } api.close(done) it "should not be ok to post without specifiying the owner", (done) -> api = manikin.create() model = accounts: owners: {} fields: name: { type: 'string', default: '' } companies: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'accounts', { name: 'a1' }, noErr (account) -> account.should.have.keys ['name', '<KEY>'] api.post 'companies', { name: 'n', orgnr: 'nbr' }, (err, company) -> should.exist err # expect something more precise... api.close(done) it "must specify an existing owner of the right type when posting", (done) -> api = manikin.create() model = stuff: fields: {} accounts: owners: {} fields: name: { type: 'string', default: '' } companies: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'stuff', { }, noErr (stuff) -> api.post 'accounts', { name: 'a1' }, noErr (account) -> account.should.have.keys ['<KEY>', '<KEY>'] api.post 'companies', { name: 'n', orgnr: 'nbr', account: stuff.id }, (err, company) -> should.exist err # expect something more precise... api.close(done) it "should introduce redundant references to all ancestors", (done) -> api = manikin.create() model = accounts: owners: {} fields: name: { type: 'string', default: '' } companies2: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } contacts: owners: company: 'companies2' fields: email: { type: 'string', default: '' } phone: { type: 'string', default: '' } pets: owners: contact: 'contacts' fields: race: { type: 'string', default: '' } saved = {} promise(api).connect(connectionData, model, noErr()) .post('accounts', { name: 'a1' }, noErr (account) -> account.should.have.keys ['<KEY>', '<KEY>'] saved.account = account ).then('post', -> @ 'companies2', { name: 'n', orgnr: 'nbr', account: saved.account.id }, noErr (company) -> saved.company = company company.should.have.keys ['id', 'name', 'orgnr', 'account'] ).then('post', -> @ 'companies2', { name: 'n<NAME>', orgnr: 'nbr', account: saved.account.id }, noErr (company2) -> saved.company2 = company2 company2.should.have.keys ['id', 'name', 'orgnr', 'account'] ).then('post', -> @ 'contacts', { email: '@', phone: '112', company: saved.company.id }, noErr (contact) -> saved.contact = contact contact.should.have.keys ['id', 'email', 'phone', 'account', 'company'] ).then('post', -> @ 'contacts', { email: '@2', phone: '911', company: saved.company2.id }, noErr (contact2) -> saved.contact2 = contact2 contact2.should.have.keys ['id', 'email', 'phone', 'account', 'company'] ).then('post', -> @ 'pets', { race: 'dog', contact: saved.contact.id }, noErr (pet) -> pet.should.have.keys ['id', 'race', 'account', 'company', 'contact'] pet.contact.should.eql saved.contact.id pet.company.should.eql saved.company.id pet.account.should.eql saved.account.id ).then('post', -> @ 'pets', { race: 'dog', contact: saved.contact2.id }, noErr (pet) -> pet.should.have.keys ['id', 'race', 'account', 'company', 'contact'] pet.contact.should.eql saved.contact2.id pet.company.should.eql saved.company2.id pet.account.should.eql saved.account.id ).list('pets', {}, noErr ((res) -> res.length.should.eql 2)) .list('contacts', {}, noErr ((res) -> res.length.should.eql 2)) .list('companies2', {}, noErr ((res) -> res.length.should.eql 2)) .list('accounts', {}, noErr ((res) -> res.length.should.eql 1)) .then -> api.close(done) it "should delete owned objects when deleting ancestors", (done) -> api = manikin.create() model = accounts: owners: {} fields: name: { type: 'string', default: '' } companies2: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } contacts: owners: company: 'companies2' fields: email: { type: 'string', default: '' } phone: { type: 'string', default: '' } pets: owners: contact: 'contacts' fields: race: { type: 'string', default: '' } saved = {} promise(api).connect(connectionData, model, noErr()) .post('accounts', { name: 'a1' }, noErr (account) -> saved.account = account ).then('post', -> @ 'companies2', { name: 'n', orgnr: 'nbr', account: saved.account.id }, noErr (company) -> saved.company = company ).then('post', -> @ 'companies2', { name: 'n2', orgnr: 'nbr', account: saved.account.id }, noErr (company2) -> saved.company2 = company2 ).then('post', -> @ 'contacts', { email: '@', phone: '112', company: saved.company.id }, noErr (contact) -> saved.contact = contact ).then('post', -> @ 'contacts', { email: '@2', phone: '911', company: saved.company2.id }, noErr (contact2) -> saved.contact2 = contact2 ).then('post', -> @ 'pets', { race: 'dog', contact: saved.contact.id }, noErr (pet) -> ).then('post', -> @ 'pets', { race: 'dog', contact: saved.contact2.id }, noErr (pet) -> ).list('pets', {}, noErr ((res) -> res.length.should.eql 2)) .list('contacts', {}, noErr ((res) -> res.length.should.eql 2)) .list('companies2', {}, noErr ((res) -> res.length.should.eql 2)) .list('accounts', {}, noErr ((res) -> res.length.should.eql 1)) .then('delOne', -> @ 'companies2', { id: saved.company.id }, noErr()) .list('pets', {}, noErr ((res) -> res.length.should.eql 1)) .list('contacts', {}, noErr ((res) -> res.length.should.eql 1)) .list('companies2', {}, noErr ((res) -> res.length.should.eql 1)) .list('accounts', {}, noErr ((res) -> res.length.should.eql 1)) .then -> api.close(done) it "should raise an error if a putOne attempts to put using an id from another collection", (done) -> api = manikin.create() model = accounts: fields: name: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'accounts', { name: 'a1' }, noErr (account) -> api.putOne 'accounts', { name: 'n1' }, { id: 1 }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' api.close(done) it "should allow undefined values", (done) -> api = manikin.create() model = pizzas: owners: {} fields: name: type: 'string' api.connect connectionData, model, noErr -> api.post 'pizzas', { name: 'jakob' }, noErr (res) -> api.putOne 'pizzas', { name: undefined }, { id: res.id }, noErr (res) -> should.not.exist res.name api.close(done) it "should allow custom validators", (done) -> api = manikin.create() model = pizzas: owners: {} fields: name: type: 'string' validate: (apiRef, value, callback) -> api.should.eql apiRef callback(value.length % 2 == 0) indata = [ name: '<NAME>' response: 'something wrong' , name: '<NAME>' response: null ] api.connect connectionData, model, noErr -> async.forEach indata, (d, callback) -> api.post 'pizzas', { name: d.name }, (err, res) -> if d.response != null err.message.should.match /Validation failed/i err.errors.name.path.should.eql 'name' callback() , -> api.close(done) it "should raise an error if a putOne attempts to put non-existing fields", (done) -> api = manikin.create() model = accounts: fields: name: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'accounts', { name: 'a1' }, noErr (account) -> api.putOne 'accounts', { name: 'n1', age: 10, desc: 'test' }, { id: account.id }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: Invalid fields: age, desc' api.close(done) it "should raise an error if a post attempts to put nonexisting fields", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.connect connectionData, noErr -> api.load mad, noErr -> api.post 'apa', { v1: '2', v2: '1' }, (err) -> err.should.eql new Error() err.toString().should.eql 'Error: Invalid fields: v2' api.close(done) it "should raise an error if a putOne attempts to put using an id from another collection", (done) -> api = manikin.create() model = accounts: fields: name: { type: 'string', default: '' } other: fields: name: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'other', { name: 'a1' }, noErr (other) -> api.post 'accounts', { name: 'a1' }, noErr (account) -> api.putOne 'accounts', { name: 'n1' }, { id: other.id }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' api.close(done)
true
assert = require 'assert' should = require 'should' async = require 'async' _ = require 'underscore' core = require './core' noErr = (cb) -> (err, args...) -> should.not.exist err cb(args...) if cb promise = core.promise exports.runTests = (manikin, dropDatabase, connectionData) -> it "should have the right methods", -> manikin.should.have.keys [ 'create' ] api = manikin.create() api.should.have.keys [ # support-methods 'connect' 'close' 'load' 'connectionData' # model operations 'post' 'list' 'getOne' 'delOne' 'putOne' 'getMany' 'delMany' 'postMany' ] describe 'Basic manikin', -> beforeEach (done) -> dropDatabase(connectionData, done) after (done) -> dropDatabase(connectionData, done) it "should be able to connect even if no models have been defined", (done) -> api = manikin.create() promise(api).connect connectionData, {}, noErr -> api.close(done) it "should raise an error if an invalid connection string is given", (done) -> api = manikin.create() api.connect "invalid-connection-string", {}, (err) -> should.exist err done() it "should be possible to load after connecting without a model", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.connect connectionData, noErr -> api.load mad, noErr -> api.post 'apa', { v1: '2' }, noErr -> api.close(done) it "should be possible to load first and then connect without a model", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.load mad, noErr -> api.connect connectionData, noErr -> api.post 'apa', { v1: '2' }, noErr -> api.close(done) it "connecting without a model and never loading will throw errors when used", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } # expecta att post throwar api.connect connectionData, noErr -> f = -> api.post('apa', { v2: '1', v1: '2' }, noErr) f.should.throw() api.close(done) describe 'connectionData', -> it "returns the data used to connect to the database", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.connect connectionData, noErr -> api.connectionData().should.eql connectionData done() describe 'should not save configuration between test runs', -> commonModelName = 'stuffzz' it "stores things for the first test run", (done) -> api = manikin.create() model = _.object([[commonModelName, fields: v1: 'string' ]]) promise(api).connect(connectionData, model, noErr()) .post(commonModelName, { v1: '2' }, noErr()) .list commonModelName, {}, noErr (list) -> list.length.should.eql 1 list[0].should.have.keys ['v1', 'id'] list[0].v1.should.eql '2' api.close(done) it "stores different things for the second test run", (done) -> api = manikin.create() model = _.object([[commonModelName, fields: v2: 'string' ]]) promise(api).connect(connectionData, model, noErr()) .post(commonModelName, { v2: '3' }, noErr()) .list commonModelName, {}, noErr (list) -> list.length.should.eql 1 list[0].should.have.keys ['v2', 'id'] list[0].v2.should.eql '3' api.close(done) it "should have a post operation that returns a copy of the given item and adds an ID", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} input = { name: 'PI:NAME:<NAME>END_PI', age: 28 } promise(api).connect(connectionData, model, noErr()) .post('stuffz', input, noErr (obj) -> obj.should.have.keys ['id', 'name', 'age'] obj.id.should.be.a 'string' obj.name.should.eql 'PI:NAME:<NAME>END_PI' obj.age.should.eql 28 obj.should.not.eql input ).then -> api.close(done) it "should set 'createdAt' automatically, if requested", (done) -> api = manikin.create() model = stuffz: createdAtField: 'created__at__123' fields: name: 'string' age: 'number' saved = {} now = new Date().getTime() promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28 }, noErr()) .list('stuffz', {}, noErr (list) -> list[0].created__at__123.should.not.be.below(now) list[0].created__at__123.should.not.be.above(now+1000) ).then -> api.close(done) it "should set 'updatedAt' automatically, if requested", (done) -> api = manikin.create() model = stuffz: updatedAtField: 'upd' fields: name: 'string' age: 'number' saved = {} now = new Date().getTime() promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28 }, noErr()) .list('stuffz', {}, noErr (list) -> list[0].upd.should.not.be.below(now) list[0].upd.should.not.be.above(now+1000) ).then -> api.close(done) it "should have post for creating and list for showing what has been created", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27 }, noErr()) .list('stuffz', {}, noErr (list) -> list.map((x) -> _(x).omit('id')).should.eql [ name: 'PI:NAME:<NAME>END_PI' age: 28 , name: 'PI:NAME:<NAME>END_PI' age: 27 ] ).then -> api.close(done) it "creates unique ids for all items posted", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27 }, noErr()) .list('stuffz', {}, noErr (list) -> list.should.have.length 2 list[0].should.have.keys ['name', 'age', 'id'] list[0].id.should.be.a.string list[1].should.have.keys ['name', 'age', 'id'] list[1].id.should.be.a.string list[0].id.should.not.eql list[1].id ).then -> api.close(done) it "can list objects from their ID", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27 }, noErr (x) -> saved.id = x.id ).then('list', -> @ 'stuffz', { filter: { id: saved.id } }, noErr (x) -> x.should.have.length 1 x[0].should.eql { id: saved.id name: 'PI:NAME:<NAME>END_PI' age: 27 } ).then -> api.close(done) it "can list objects from any of its properties", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 42 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27 }, noErr()) .list('stuffz', { filter: { name: 'PI:NAME:<NAME>END_PI' } }, noErr (x) -> x.should.have.length 2 x[0].name.should.eql 'PI:NAME:<NAME>END_PI' x[0].age.should.eql 28 x[1].name.should.eql 'PI:NAME:<NAME>END_PI' x[1].age.should.eql 42 ).then -> api.close(done) it "can list objects from any combination of their properties", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' city: 'string' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28, city: 'gbg' }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27, city: 'gbg' }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28, city: 'sthlm' }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27, city: 'sthlm' }, noErr()) .list('stuffz', { filter: { name: 'PI:NAME:<NAME>END_PI', city: 'sthlm' } }, noErr (x) -> x.should.have.length 1 x[0].name.should.eql 'PI:NAME:<NAME>END_PI' x[0].age.should.eql 28 x[0].city.should.eql 'sthlm' ).then -> api.close(done) it "can sort objects", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 42 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27 }, noErr()) .list('stuffz', { sort: { age: 'asc' } }, noErr (x) -> x.should.have.length 3 x[0].age.should.eql 27 x[1].age.should.eql 28 x[2].age.should.eql 42 ).then -> api.close(done) it "can limit number of results returned", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 42 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27 }, noErr()) .list('stuffz', { limit: 2 }, noErr (x) -> x.should.have.length 2 ).then -> api.close(done) it "can skip items", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 42 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27 }, noErr()) .list('stuffz', { skip: 2 }, noErr (x) -> x.should.have.length 1 ).then -> api.close(done) it "can sort objects in a descending", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 42 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27 }, noErr()) .list('stuffz', { sort: { age: 'desc' } }, noErr (x) -> x.should.have.length 3 x[0].age.should.eql 42 x[1].age.should.eql 28 x[2].age.should.eql 27 ).then -> api.close(done) it "can get a single object from its ID", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27 }, noErr (x) -> saved.id = x.id ).then('getOne', -> @ 'stuffz', { filter: { id: saved.id } }, noErr (x) -> x.should.eql { id: saved.id name: 'PI:NAME:<NAME>END_PI' age: 27 } ).then -> api.close(done) it "can get a single object from any of its properties", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27 }, noErr()) .getOne('stuffz', { filter: { name: 'PI:NAME:<NAME>END_PI' } }, noErr (x) -> x.name.should.eql 'PI:NAME:<NAME>END_PI' x.age.should.eql 28 ).then -> api.close(done) it "can get a single object from any combination of its properties", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' city: 'string' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28, city: 'gbg' }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27, city: 'gbg' }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28, city: 'sthlm' }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27, city: 'sthlm' }, noErr()) .getOne('stuffz', { filter: { name: 'PI:NAME:<NAME>END_PI', city: 'sthlm' } }, noErr (x) -> x.name.should.eql 'PI:NAME:<NAME>END_PI' x.age.should.eql 28 x.city.should.eql 'sthlm' ).then -> api.close(done) it "can filter out objects using an array of valid values", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 16 }, noErr()) .list('stuffz', { filter: { age: [28, 27] } }, noErr (x) -> _(x).pluck('name').sort().should.eql ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] ).then -> api.close(done) it "calls back with an error if no objects where found", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28 }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27 }, noErr()) .getOne('stuffz', { filter: { name: 'PI:NAME:<NAME>END_PI' } }, (err, x) -> err.should.eql new Error() should.not.exist x ).then -> api.close(done) it "can update an object", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' city: 'string' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28, city: 'gbg' }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27, city: 'gbg' }, noErr()) .putOne('stuffz', { city: 'sthlm' }, { name: 'PI:NAME:<NAME>END_PI' }, noErr()) .list('stuffz', { }, noErr (x) -> x.should.have.length 2 x[0].name.should.eql 'PI:NAME:<NAME>END_PI' x[0].age.should.eql 28 x[0].city.should.eql 'gbg' x[1].name.should.eql 'PI:NAME:<NAME>END_PI' x[1].age.should.eql 27 x[1].city.should.eql 'sthlm' ).then -> api.close(done) it "can delete an object", (done) -> api = manikin.create() model = stuffz: fields: name: 'string' age: 'number' city: 'string' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 28, city: 'gbg' }, noErr()) .post('stuffz', { name: 'PI:NAME:<NAME>END_PI', age: 27, city: 'gbg' }, noErr()) .delOne('stuffz', { name: 'PI:NAME:<NAME>END_PI' }, noErr()) .list('stuffz', { }, noErr (x) -> x.should.have.length 1 x[0].name.should.eql 'PI:NAME:<NAME>END_PI' x[0].age.should.eql 28 x[0].city.should.eql 'gbg' ).then -> api.close(done) it "should allow a basic set of primitive data types to be stored and retrieved", (done) -> api = manikin.create() model = stuffz: fields: v1: 'string' v2: 'number' v3: 'date' v4: 'boolean' v5: type: 'nested' v6: 'string' v7: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { v1: 'PI:NAME:<NAME>END_PI', v2: 12.5, v3: '2012-10-15', v4: true, v5: { v6: 'nest', v7: 7 } }, noErr()) .list('stuffz', {}, noErr (list) -> saved.id = list[0].id list.map((x) -> _(x).omit('id')).should.eql [ v1: 'PI:NAME:<NAME>END_PI' v2: 12.5 v3: '2012-10-15T00:00:00.000Z' v4: true v5: v6: 'nest' v7: 7 ] ).then -> api.close(done) it "should allow a basic set of primitive data types to be updated", (done) -> api = manikin.create() model = stuffz: fields: v1: 'string' v2: 'number' v3: 'date' v4: 'boolean' v5: type: 'nested' v6: 'string' v7: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { v1: 'PI:NAME:<NAME>END_PI', v2: 12.5, v3: '2012-10-15', v4: true, v5: { v6: 'nest', v7: 7 } }, noErr()) .list('stuffz', {}, noErr (list) -> saved.id = list[0].id list.map((x) -> _(x).omit('id')).should.eql [ v1: 'PI:NAME:<NAME>END_PI' v2: 12.5 v3: '2012-10-15T00:00:00.000Z' v4: true v5: v6: 'nest' v7: 7 ] ).then('putOne', -> @ 'stuffz', { v1: 'jakob2', v3: '2012-10-15T13:37:00', v4: false, v5: { v6: 'nest2', v7: 14 } }, { id: saved.id }, noErr (r) -> _(r).omit('id').should.eql v1: 'jakob2' v2: 12.5 v3: '2012-10-15T13:37:00.000Z' v4: false v5: v6: 'nest2' v7: 14 ).then('getOne', -> @ 'stuffz', { filter: { id: saved.id } }, noErr (r) -> _(r).omit('id').should.eql v1: 'jakob2' v2: 12.5 v3: '2012-10-15T13:37:00.000Z' v4: false v5: v6: 'nest2' v7: 14 ).then -> api.close(done) it "should allow posting to nested properties", (done) -> api = manikin.create() model = stuffz: fields: v1: 'string' v5: type: 'nested' v6: 'string' v7: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { v1: 'hej', v5: { v6: 'nest', v7: 7 } }, noErr()) .then -> api.close(done) it "should allow putting null to nested properties", (done) -> api = manikin.create() model = stuffz: fields: v1: 'string' v5: type: 'nested' v6: 'string' v7: 'number' saved = {} promise(api).connect(connectionData, model, noErr()) .post('stuffz', { v1: 'hej', v5: { v6: 'nest', v7: 7 } }, noErr (v) -> saved.id = v.id ).then('putOne', -> @ 'stuffz', { v1: 'jakob2', v5: null }, { id: saved.id }, noErr (r) -> ).then -> api.close(done) it "should detect when an object id does not exist", (done) -> api = manikin.create() model = table: fields: v1: 'string' promise(api).connect(connectionData, model, noErr()) .getOne 'table', { filter: { id: '123' } }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' should.not.exist data .delOne('table', { id: '123' }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' should.not.exist data ).then -> api.close(done) it "should return an error in the callback if the given model does not exist in a listing", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.load mad, noErr -> api.connect connectionData, noErr -> api.list 'non-existing', { filter: { v2: '1', v1: '2' } }, (err) -> err.should.eql new Error() err.toString().should.eql 'Error: No model named non-existing' api.close(done) it "should allow mixed properties in models definitions", (done) -> api = manikin.create() model = stuffs: owners: {} fields: name: { type: 'string' } stats: { type: 'mixed' } api.connect connectionData, model, noErr -> api.post 'stuffs', { name: 'a1', stats: { s1: 's1', s2: 2 } }, noErr (survey) -> survey.should.have.keys ['id', 'name', 'stats'] survey.stats.should.have.keys ['s1', 's2'] api.putOne "stuffs", { name: 'a2', stats: { x: 1 } }, { id: survey.id }, noErr (survey) -> survey.should.have.keys ['id', 'name', 'stats'] survey.stats.should.have.keys ['x'] api.close(done) it "should allow default sorting orders", (done) -> api = manikin.create() model = warez: owners: {} defaultSort: 'name' fields: name: { type: 'string' } stats: { type: 'mixed' } promise(api).connect(connectionData, model, noErr()) .post('warez', { name: 'PI:NAME:<NAME>END_PI', stats: 1 }, noErr()) .post('warez', { name: 'PI:NAME:<NAME>END_PI', stats: 2 }, noErr()) .post('warez', { name: 'PI:NAME:<NAME>END_PI', stats: 3 }, noErr()) .list('warez', {}, noErr (list) -> names = list.map (x) -> x.name names.should.eql ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] ).then -> api.close(done) it "should allow simplified field declarations (specifying type only)", (done) -> api = manikin.create() model = leet: owners: {} fields: firstName: 'string' lastName: { type: 'string' } age: 'number' api.connect connectionData, model, noErr -> api.post 'leet', { firstName: 'PI:NAME:<NAME>END_PI', lastName: 'PI:NAME:<NAME>END_PI', age: 27 }, noErr (survey) -> survey.should.have.keys ['id', 'firstName', 'lastName', 'age'] survey.should.eql { id: survey.id, firstName: 'PI:NAME:<NAME>END_PI', lastName: 'PI:NAME:<NAME>END_PI', age: 27 } api.close(done) it "should detect when an filter matches no objects on getOne", (done) -> api = manikin.create() model = table: fields: v1: 'string' promise(api).connect(connectionData, model, noErr()) .getOne('table', { filter: { v1: '123' } }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No match' should.not.exist data ).then -> api.close(done) it "should detect when an filter matches no objects on delOne", (done) -> api = manikin.create() model = table: fields: v1: 'string' promise(api).connect(connectionData, model, noErr()) .delOne('table', { v1: '123' }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' should.not.exist data ).then -> api.close(done) it "should be possible to specifiy the owner together with the fields when creating an object", (done) -> api = manikin.create() model = accounts: owners: {} fields: name: { type: 'string', default: '' } companies: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'accounts', { name: 'a1' }, noErr (account) -> account.should.have.keys ['name', 'id'] api.post 'companies', { name: 'n', orgnr: 'nbr', account: account.id }, noErr (company) -> _(company).omit('id').should.eql { account: account.id name: 'n' orgnr: 'nbr' } api.close(done) it "should not be ok to post without specifiying the owner", (done) -> api = manikin.create() model = accounts: owners: {} fields: name: { type: 'string', default: '' } companies: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'accounts', { name: 'a1' }, noErr (account) -> account.should.have.keys ['name', 'PI:KEY:<KEY>END_PI'] api.post 'companies', { name: 'n', orgnr: 'nbr' }, (err, company) -> should.exist err # expect something more precise... api.close(done) it "must specify an existing owner of the right type when posting", (done) -> api = manikin.create() model = stuff: fields: {} accounts: owners: {} fields: name: { type: 'string', default: '' } companies: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'stuff', { }, noErr (stuff) -> api.post 'accounts', { name: 'a1' }, noErr (account) -> account.should.have.keys ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI'] api.post 'companies', { name: 'n', orgnr: 'nbr', account: stuff.id }, (err, company) -> should.exist err # expect something more precise... api.close(done) it "should introduce redundant references to all ancestors", (done) -> api = manikin.create() model = accounts: owners: {} fields: name: { type: 'string', default: '' } companies2: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } contacts: owners: company: 'companies2' fields: email: { type: 'string', default: '' } phone: { type: 'string', default: '' } pets: owners: contact: 'contacts' fields: race: { type: 'string', default: '' } saved = {} promise(api).connect(connectionData, model, noErr()) .post('accounts', { name: 'a1' }, noErr (account) -> account.should.have.keys ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI'] saved.account = account ).then('post', -> @ 'companies2', { name: 'n', orgnr: 'nbr', account: saved.account.id }, noErr (company) -> saved.company = company company.should.have.keys ['id', 'name', 'orgnr', 'account'] ).then('post', -> @ 'companies2', { name: 'nPI:NAME:<NAME>END_PI', orgnr: 'nbr', account: saved.account.id }, noErr (company2) -> saved.company2 = company2 company2.should.have.keys ['id', 'name', 'orgnr', 'account'] ).then('post', -> @ 'contacts', { email: '@', phone: '112', company: saved.company.id }, noErr (contact) -> saved.contact = contact contact.should.have.keys ['id', 'email', 'phone', 'account', 'company'] ).then('post', -> @ 'contacts', { email: '@2', phone: '911', company: saved.company2.id }, noErr (contact2) -> saved.contact2 = contact2 contact2.should.have.keys ['id', 'email', 'phone', 'account', 'company'] ).then('post', -> @ 'pets', { race: 'dog', contact: saved.contact.id }, noErr (pet) -> pet.should.have.keys ['id', 'race', 'account', 'company', 'contact'] pet.contact.should.eql saved.contact.id pet.company.should.eql saved.company.id pet.account.should.eql saved.account.id ).then('post', -> @ 'pets', { race: 'dog', contact: saved.contact2.id }, noErr (pet) -> pet.should.have.keys ['id', 'race', 'account', 'company', 'contact'] pet.contact.should.eql saved.contact2.id pet.company.should.eql saved.company2.id pet.account.should.eql saved.account.id ).list('pets', {}, noErr ((res) -> res.length.should.eql 2)) .list('contacts', {}, noErr ((res) -> res.length.should.eql 2)) .list('companies2', {}, noErr ((res) -> res.length.should.eql 2)) .list('accounts', {}, noErr ((res) -> res.length.should.eql 1)) .then -> api.close(done) it "should delete owned objects when deleting ancestors", (done) -> api = manikin.create() model = accounts: owners: {} fields: name: { type: 'string', default: '' } companies2: owners: account: 'accounts' fields: name: { type: 'string', default: '' } orgnr: { type: 'string', default: '' } contacts: owners: company: 'companies2' fields: email: { type: 'string', default: '' } phone: { type: 'string', default: '' } pets: owners: contact: 'contacts' fields: race: { type: 'string', default: '' } saved = {} promise(api).connect(connectionData, model, noErr()) .post('accounts', { name: 'a1' }, noErr (account) -> saved.account = account ).then('post', -> @ 'companies2', { name: 'n', orgnr: 'nbr', account: saved.account.id }, noErr (company) -> saved.company = company ).then('post', -> @ 'companies2', { name: 'n2', orgnr: 'nbr', account: saved.account.id }, noErr (company2) -> saved.company2 = company2 ).then('post', -> @ 'contacts', { email: '@', phone: '112', company: saved.company.id }, noErr (contact) -> saved.contact = contact ).then('post', -> @ 'contacts', { email: '@2', phone: '911', company: saved.company2.id }, noErr (contact2) -> saved.contact2 = contact2 ).then('post', -> @ 'pets', { race: 'dog', contact: saved.contact.id }, noErr (pet) -> ).then('post', -> @ 'pets', { race: 'dog', contact: saved.contact2.id }, noErr (pet) -> ).list('pets', {}, noErr ((res) -> res.length.should.eql 2)) .list('contacts', {}, noErr ((res) -> res.length.should.eql 2)) .list('companies2', {}, noErr ((res) -> res.length.should.eql 2)) .list('accounts', {}, noErr ((res) -> res.length.should.eql 1)) .then('delOne', -> @ 'companies2', { id: saved.company.id }, noErr()) .list('pets', {}, noErr ((res) -> res.length.should.eql 1)) .list('contacts', {}, noErr ((res) -> res.length.should.eql 1)) .list('companies2', {}, noErr ((res) -> res.length.should.eql 1)) .list('accounts', {}, noErr ((res) -> res.length.should.eql 1)) .then -> api.close(done) it "should raise an error if a putOne attempts to put using an id from another collection", (done) -> api = manikin.create() model = accounts: fields: name: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'accounts', { name: 'a1' }, noErr (account) -> api.putOne 'accounts', { name: 'n1' }, { id: 1 }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' api.close(done) it "should allow undefined values", (done) -> api = manikin.create() model = pizzas: owners: {} fields: name: type: 'string' api.connect connectionData, model, noErr -> api.post 'pizzas', { name: 'jakob' }, noErr (res) -> api.putOne 'pizzas', { name: undefined }, { id: res.id }, noErr (res) -> should.not.exist res.name api.close(done) it "should allow custom validators", (done) -> api = manikin.create() model = pizzas: owners: {} fields: name: type: 'string' validate: (apiRef, value, callback) -> api.should.eql apiRef callback(value.length % 2 == 0) indata = [ name: 'PI:NAME:<NAME>END_PI' response: 'something wrong' , name: 'PI:NAME:<NAME>END_PI' response: null ] api.connect connectionData, model, noErr -> async.forEach indata, (d, callback) -> api.post 'pizzas', { name: d.name }, (err, res) -> if d.response != null err.message.should.match /Validation failed/i err.errors.name.path.should.eql 'name' callback() , -> api.close(done) it "should raise an error if a putOne attempts to put non-existing fields", (done) -> api = manikin.create() model = accounts: fields: name: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'accounts', { name: 'a1' }, noErr (account) -> api.putOne 'accounts', { name: 'n1', age: 10, desc: 'test' }, { id: account.id }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: Invalid fields: age, desc' api.close(done) it "should raise an error if a post attempts to put nonexisting fields", (done) -> api = manikin.create() mad = { apa: fields: v1: 'string' } api.connect connectionData, noErr -> api.load mad, noErr -> api.post 'apa', { v1: '2', v2: '1' }, (err) -> err.should.eql new Error() err.toString().should.eql 'Error: Invalid fields: v2' api.close(done) it "should raise an error if a putOne attempts to put using an id from another collection", (done) -> api = manikin.create() model = accounts: fields: name: { type: 'string', default: '' } other: fields: name: { type: 'string', default: '' } api.connect connectionData, model, noErr -> api.post 'other', { name: 'a1' }, noErr (other) -> api.post 'accounts', { name: 'a1' }, noErr (account) -> api.putOne 'accounts', { name: 'n1' }, { id: other.id }, (err, data) -> err.should.eql new Error() err.toString().should.eql 'Error: No such id' api.close(done)